From a0fa9e19b1196bc10034f15474d27ce23bf5865a Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Thu, 24 Dec 2020 18:42:29 +0000 Subject: [PATCH] #65026 - Migrate tests to Junit 5 git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1884783 13f79535-47bb-0310-9956-ffa450edef68 --- build.xml | 271 +- sonar/integration-test/pom.xml | 6 - sonar/ooxml/pom.xml | 6 - sonar/pom.xml | 19 +- .../poi-ant-contrib/Junit5Progress.java | 114 + .../excelant/MockExcelAntWorkbookHandler.java | 6 +- .../apache/poi/ss/excelant/TestBuildFile.java | 50 +- .../ss/excelant/TestExcelAntPrecision.java | 14 +- .../poi/ss/excelant/TestExcelAntSet.java | 14 +- .../excelant/TestExcelAntSetDoubleCell.java | 14 +- .../TestExcelAntUserDefinedFunction.java | 10 +- .../util/TestExcelAntEvaluationResult.java | 38 +- .../util/TestExcelAntWorkbookUtil.java | 59 +- .../util/TestExcelAntWorkbookUtilFactory.java | 6 +- .../poi/stress/AbstractFileHandler.java | 20 +- .../poi/stress/BaseIntegrationTest.java | 23 +- .../org/apache/poi/stress/FileHandler.java | 8 +- .../apache/poi/stress/HDGFFileHandler.java | 16 +- .../apache/poi/stress/HMEFFileHandler.java | 8 +- .../apache/poi/stress/HPBFFileHandler.java | 14 +- .../apache/poi/stress/HPSFFileHandler.java | 10 +- .../apache/poi/stress/HSLFFileHandler.java | 18 +- .../apache/poi/stress/HSMFFileHandler.java | 14 +- .../apache/poi/stress/HSSFFileHandler.java | 9 +- .../poi/stress/HSSFRecordsStresser.java | 14 +- .../apache/poi/stress/HWPFFileHandler.java | 4 +- .../org/apache/poi/stress/OPCFileHandler.java | 13 +- .../apache/poi/stress/POIFSFileHandler.java | 12 +- .../org/apache/poi/stress/POIFileScanner.java | 8 +- .../poi/stress/POIXMLDocumentHandler.java | 2 +- .../apache/poi/stress/SlideShowHandler.java | 30 +- .../apache/poi/stress/SpreadsheetHandler.java | 18 +- .../org/apache/poi/stress/TestAllFiles.java | 65 +- .../apache/poi/stress/XDGFFileHandler.java | 2 +- .../apache/poi/stress/XSLFFileHandler.java | 8 +- .../apache/poi/stress/XSSFBFileHandler.java | 2 +- .../apache/poi/stress/XSSFFileHandler.java | 15 +- .../apache/poi/stress/XWPFFileHandler.java | 2 +- .../poi/poifs/nio/FileBackedDataSource.java | 3 +- .../apache/poi/ss/formula/atp/DateParser.java | 77 +- .../org/apache/poi/ss/util/DateParser.java | 2 +- .../excelant/test9/module-info.class | Bin 293 -> 370 bytes .../excelant/test9/module-info.java | 4 + .../integration/java9/module-info.java | 4 +- src/multimodule/ooxml/test9/module-info.class | Bin 3943 -> 4035 bytes src/multimodule/ooxml/test9/module-info.java | 41 +- src/multimodule/poi/java9/module-info.class | Bin 3320 -> 3341 bytes src/multimodule/poi/test9/module-info.class | Bin 3447 -> 3547 bytes src/multimodule/poi/test9/module-info.java | 9 +- .../scratchpad/test9/module-info.class | Bin 2690 -> 2782 bytes .../scratchpad/test9/module-info.java | 11 +- .../extractor/ooxml/TestExtractorFactory.java | 65 +- .../apache/poi/ooxml/TestDetectAsOOXML.java | 21 +- .../org/apache/poi/ooxml/TestEmbedded.java | 8 +- .../apache/poi/ooxml/TestPOIXMLDocument.java | 207 +- .../poi/ooxml/TestPOIXMLProperties.java | 142 +- .../ooxml/TestXMLPropertiesTextExtractor.java | 8 +- .../poi/openxml4j/opc/AllOpenXML4JTests.java | 36 - .../poi/openxml4j/opc/TestContentType.java | 36 +- .../poi/openxml4j/opc/TestFileHelper.java | 4 +- .../poi/openxml4j/opc/TestListParts.java | 10 +- .../apache/poi/openxml4j/opc/TestPackage.java | 129 +- .../opc/TestPackageCoreProperties.java | 78 +- .../openxml4j/opc/TestPackagePartName.java | 4 +- .../openxml4j/opc/TestPackageThumbnail.java | 27 +- .../openxml4j/opc/TestPackagingURIHelper.java | 12 +- .../poi/openxml4j/opc/TestRelationships.java | 27 +- .../poi/openxml4j/opc/ZipFileAssert.java | 42 +- .../TestOPCComplianceCoreProperties.java | 206 +- .../TestOPCCompliancePackageModel.java | 146 +- .../compliance/TestOPCCompliancePartName.java | 103 +- .../opc/internal/TestContentTypeManager.java | 12 +- .../TestZipPackagePropertiesMarshaller.java | 48 +- .../poi/openxml4j/util/TestZipSecureFile.java | 4 +- .../poifs/crypt/dsig/TestSignatureConfig.java | 14 +- .../poifs/crypt/dsig/TestSignatureInfo.java | 68 +- .../crypt/tests/AllPOIFSCryptoTests.java | 35 - .../tests/TestAgileEncryptionParameters.java | 46 +- .../poi/poifs/crypt/tests/TestDecryptor.java | 35 +- .../poifs/crypt/tests/TestEncryptionInfo.java | 11 +- .../poi/poifs/crypt/tests/TestEncryptor.java | 30 +- .../poifs/crypt/tests/TestHxxFEncryption.java | 80 +- .../poifs/crypt/tests/TestSecureTempZip.java | 11 +- .../org/apache/poi/sl/tests/TestFonts.java | 10 +- .../poi/sl/tests/TestHeadersFooters.java | 6 +- .../org/apache/poi/sl/tests/TestOleShape.java | 68 +- .../org/apache/poi/sl/tests/TestSlide.java | 8 +- .../org/apache/poi/sl/tests/TestTable.java | 54 +- .../sl/tests/draw/TestDrawPictureShape.java | 12 +- .../poi/ss/tests/TestWorkbookFactory.java | 395 +- .../extractor/TestEmbeddedExtractor.java | 6 +- .../ss/tests/format/TestCellFormatPart.java | 22 +- .../ss/tests/formula/TestFormulaParser.java | 62 +- .../formula/TestStructuredReferences.java | 33 +- .../formula/functions/CountifsTests.java | 19 +- .../tests/formula/functions/TestProper.java | 10 +- .../formula/functions/TestSumifsXSSF.java | 4 +- .../tests/formula/functions/TestVlookup.java | 14 +- .../poi/ss/tests/usermodel/BaseTestXCell.java | 4 +- .../poi/ss/tests/usermodel/BaseTestXRow.java | 2 +- .../ConditionalFormattingEvalTest.java | 119 +- .../tests/usermodel/TestEmbedOLEPackage.java | 14 +- .../tests/usermodel/TestXSSFRangeCopier.java | 12 +- .../tests/util/TestXSSFPropertyTemplate.java | 6 +- .../poi/util/tests/TestIdentifierManager.java | 70 +- .../poi/util/tests/TestTempFileThreaded.java | 20 +- .../usermodel/TestNecessaryOOXMLClasses.java | 162 +- .../poi/xddf/usermodel/TestXDDFColor.java | 36 +- .../xddf/usermodel/chart/TestXDDFChart.java | 6 +- .../chart/TestXDDFChartExtensionList.java | 6 +- .../chart/TestXDDFChartRemoveSeries.java | 12 +- .../chart/TestXDDFDataSourcesFactory.java | 12 +- .../text/TestXDDFTextBodyProperties.java | 8 +- .../xddf/usermodel/text/TestXDDFTextRun.java | 16 +- .../extractor/TestXDGFVisioExtractor.java | 22 +- .../section/CombinedIteratorTest.java | 13 +- .../poi/xslf/TestNecessaryOOXMLClasses.java | 4 +- .../org/apache/poi/xslf/TestXSLFBugs.java | 294 +- .../apache/poi/xslf/TestXSLFSlideShow.java | 50 +- .../TestXSLFPowerPointExtractor.java | 16 +- .../poi/xslf/usermodel/TestPPTX2PNG.java | 51 +- .../poi/xslf/usermodel/TestXMLSlideShow.java | 282 +- .../poi/xslf/usermodel/TestXSLFAutoShape.java | 14 +- .../xslf/usermodel/TestXSLFBackground.java | 4 +- .../poi/xslf/usermodel/TestXSLFChart.java | 14 +- .../poi/xslf/usermodel/TestXSLFColor.java | 8 +- .../usermodel/TestXSLFConnectorShape.java | 8 +- .../poi/xslf/usermodel/TestXSLFExamples.java | 2 +- .../xslf/usermodel/TestXSLFFreeformShape.java | 6 +- .../xslf/usermodel/TestXSLFGroupShape.java | 12 +- .../poi/xslf/usermodel/TestXSLFHyperlink.java | 6 +- .../poi/xslf/usermodel/TestXSLFNotes.java | 14 +- .../xslf/usermodel/TestXSLFPictureShape.java | 14 +- .../poi/xslf/usermodel/TestXSLFShape.java | 12 +- .../usermodel/TestXSLFShapeContainer.java | 4 +- .../poi/xslf/usermodel/TestXSLFSheet.java | 8 +- .../xslf/usermodel/TestXSLFSimpleShape.java | 12 +- .../poi/xslf/usermodel/TestXSLFSlide.java | 14 +- .../poi/xslf/usermodel/TestXSLFSlideShow.java | 12 +- .../usermodel/TestXSLFSlideShowFactory.java | 21 +- .../poi/xslf/usermodel/TestXSLFTable.java | 14 +- .../poi/xslf/usermodel/TestXSLFTableRow.java | 55 +- .../xslf/usermodel/TestXSLFTableStyles.java | 8 +- .../poi/xslf/usermodel/TestXSLFTextBox.java | 10 +- .../xslf/usermodel/TestXSLFTextParagraph.java | 19 +- .../poi/xslf/usermodel/TestXSLFTextRun.java | 10 +- .../poi/xslf/usermodel/TestXSLFTextShape.java | 20 +- .../poi/xslf/usermodel/TestXSLFTheme.java | 10 +- .../org/apache/poi/xssf/AllXSSFTests.java | 50 - .../poi/xssf/TestNecessaryOOXMLClasses.java | 9 +- .../apache/poi/xssf/TestSheetProtection.java | 16 +- .../poi/xssf/TestWorkbookProtection.java | 18 +- .../apache/poi/xssf/TestXSSFCloneSheet.java | 28 +- .../org/apache/poi/xssf/TestXSSFOffset.java | 4 +- .../apache/poi/xssf/XSSFMemoryLeakTests.java | 50 +- .../binary/TestXSSFBSharedStringsTable.java | 4 +- .../TestXSSFBSheetHyperlinkManager.java | 6 +- .../TestReadOnlySharedStringsTable.java | 5 +- .../xssf/eventusermodel/TestXSSFBReader.java | 6 +- .../xssf/eventusermodel/TestXSSFReader.java | 44 +- .../TestXSSFBEventBasedExcelExtractor.java | 6 +- .../TestXSSFEventBasedExcelExtractor.java | 84 +- ...FEventBasedExcelExtractorUsingFactory.java | 4 +- .../extractor/TestXSSFExcelExtractor.java | 8 +- .../TestXSSFExcelExtractorUsingFactory.java | 4 +- .../xssf/extractor/TestXSSFExportToXML.java | 38 +- .../xssf/extractor/TestXSSFImportFromXML.java | 15 +- .../apache/poi/xssf/io/TestLoadSaveXSSF.java | 6 +- .../poi/xssf/model/TestCalculationChain.java | 4 +- .../poi/xssf/model/TestCommentsTable.java | 46 +- .../xssf/model/TestExternalLinksTable.java | 18 +- .../apache/poi/xssf/model/TestMapInfo.java | 12 +- .../xssf/model/TestSharedStringsTable.java | 6 +- .../poi/xssf/model/TestStylesTable.java | 74 +- .../poi/xssf/model/TestThemesTable.java | 34 +- .../streaming/TestAutoSizeColumnTracker.java | 67 +- .../streaming/TestDeferredSXSSFWorkbook.java | 44 +- .../poi/xssf/streaming/TestOutlining.java | 81 +- .../poi/xssf/streaming/TestSXSSFCell.java | 41 +- .../streaming/TestSXSSFDataValidation.java | 4 +- .../streaming/TestSXSSFEvaluationSheet.java | 4 +- .../streaming/TestSXSSFFormulaEvaluation.java | 166 +- .../xssf/streaming/TestSXSSFHyperlink.java | 6 +- .../poi/xssf/streaming/TestSXSSFRow.java | 12 +- .../poi/xssf/streaming/TestSXSSFSheet.java | 52 +- .../TestSXSSFSheetAutoSizeColumn.java | 300 +- .../streaming/TestSXSSFUnicodeSurrogates.java | 9 +- .../poi/xssf/streaming/TestSXSSFWorkbook.java | 47 +- ...SXSSFWorkbookWithCustomZipEntrySource.java | 21 +- .../xssf/streaming/TestSheetDataWriter.java | 10 +- .../xssf/usermodel/AllXSSFUsermodelTests.java | 64 - .../usermodel/BaseTestXSSFPivotTable.java | 37 +- .../usermodel/TestFormulaEvaluatorOnXSSF.java | 82 +- .../TestMatrixFormulasFromXMLSpreadsheet.java | 86 +- .../usermodel/TestMissingWorkbookOnXSSF.java | 6 +- .../TestMultiSheetFormulaEvaluatorOnXSSF.java | 116 +- .../poi/xssf/usermodel/TestSXSSFBugs.java | 38 +- .../poi/xssf/usermodel/TestTableStyles.java | 56 +- .../poi/xssf/usermodel/TestUnfixedBugs.java | 39 +- .../poi/xssf/usermodel/TestXSSFBugs.java | 390 +- .../poi/xssf/usermodel/TestXSSFCell.java | 78 +- .../poi/xssf/usermodel/TestXSSFCellStyle.java | 22 +- .../poi/xssf/usermodel/TestXSSFChart.java | 8 +- .../xssf/usermodel/TestXSSFChartSheet.java | 9 +- .../xssf/usermodel/TestXSSFColGrouping.java | 326 +- .../poi/xssf/usermodel/TestXSSFColor.java | 14 +- .../poi/xssf/usermodel/TestXSSFComment.java | 44 +- .../TestXSSFConditionalFormatting.java | 18 +- .../xssf/usermodel/TestXSSFDataFormat.java | 34 +- .../usermodel/TestXSSFDataValidation.java | 63 +- .../TestXSSFDataValidationConstraint.java | 4 +- .../xssf/usermodel/TestXSSFDialogSheet.java | 12 +- .../poi/xssf/usermodel/TestXSSFDrawing.java | 34 +- .../usermodel/TestXSSFEvaluationSheet.java | 32 +- .../xssf/usermodel/TestXSSFEvenFooter.java | 18 +- .../xssf/usermodel/TestXSSFEvenHeader.java | 18 +- .../xssf/usermodel/TestXSSFFirstFooter.java | 18 +- .../xssf/usermodel/TestXSSFFirstHeader.java | 18 +- .../poi/xssf/usermodel/TestXSSFFont.java | 40 +- .../usermodel/TestXSSFFormulaEvaluation.java | 202 +- .../xssf/usermodel/TestXSSFFormulaParser.java | 277 +- .../TestXSSFHeaderFooterProperties.java | 20 +- .../poi/xssf/usermodel/TestXSSFHyperlink.java | 44 +- .../poi/xssf/usermodel/TestXSSFName.java | 14 +- .../poi/xssf/usermodel/TestXSSFOddFooter.java | 18 +- .../poi/xssf/usermodel/TestXSSFOddHeader.java | 18 +- .../poi/xssf/usermodel/TestXSSFPicture.java | 8 +- .../xssf/usermodel/TestXSSFPictureData.java | 12 +- .../usermodel/TestXSSFPivotTableName.java | 16 +- .../xssf/usermodel/TestXSSFPivotTableRef.java | 18 +- .../xssf/usermodel/TestXSSFPrintSetup.java | 34 +- .../usermodel/TestXSSFRichTextString.java | 51 +- .../poi/xssf/usermodel/TestXSSFRow.java | 58 +- .../poi/xssf/usermodel/TestXSSFShape.java | 11 +- .../poi/xssf/usermodel/TestXSSFSheet.java | 628 +- .../usermodel/TestXSSFSheetMergeRegions.java | 8 +- .../usermodel/TestXSSFSheetRowGrouping.java | 22 +- .../usermodel/TestXSSFSheetShiftRows.java | 110 +- .../TestXSSFSheetShiftRowsAndColumns.java | 28 +- .../TestXSSFSheetUpdateArrayFormulas.java | 14 +- .../xssf/usermodel/TestXSSFSimpleShape.java | 12 +- .../poi/xssf/usermodel/TestXSSFTable.java | 75 +- .../xssf/usermodel/TestXSSFTableColumn.java | 8 +- .../xssf/usermodel/TestXSSFTextParagraph.java | 4 +- .../poi/xssf/usermodel/TestXSSFTextRun.java | 12 +- .../usermodel/TestXSSFUnicodeSurrogates.java | 9 +- .../xssf/usermodel/TestXSSFVMLDrawing.java | 12 +- .../poi/xssf/usermodel/TestXSSFWorkbook.java | 166 +- .../usermodel/charts/TestXDDFChartLegend.java | 8 +- .../charts/TestXDDFManualLayout.java | 12 +- .../usermodel/charts/TestXSSF3DChartData.java | 6 +- .../charts/TestXSSFCategoryAxis.java | 4 +- .../usermodel/charts/TestXSSFChartAxis.java | 18 +- .../usermodel/charts/TestXSSFChartTitle.java | 12 +- .../usermodel/charts/TestXSSFDateAxis.java | 4 +- .../charts/TestXSSFLineChartData.java | 8 +- .../charts/TestXSSFScatterChartData.java | 8 +- .../usermodel/charts/TestXSSFValueAxis.java | 4 +- .../usermodel/extensions/TestXSSFBorder.java | 4 +- .../extensions/TestXSSFCellFill.java | 14 +- .../extensions/TestXSSFHeaderFooter.java | 60 +- .../extensions/XSSFCellBorderTest.java | 8 +- .../usermodel/helpers/TestColumnHelper.java | 16 +- .../helpers/TestHeaderFooterHelper.java | 4 +- .../org/apache/poi/xssf/util/MemoryUsage.java | 2 +- .../poi/xssf/util/TestCTColComparator.java | 4 +- .../TestEvilUnclosedBRFixingInputStream.java | 4 +- .../poi/xssf/util/TestNumericRanges.java | 4 +- .../org/apache/poi/xwpf/AllXWPFTests.java | 58 - .../poi/xwpf/TestAllExtendedProperties.java | 18 +- .../poi/xwpf/TestDocumentProtection.java | 8 +- .../poi/xwpf/TestNecessaryOOXMLClasses.java | 16 +- .../TestPackageCorePropertiesGetKeywords.java | 4 +- .../org/apache/poi/xwpf/TestXWPFBugs.java | 18 +- .../xwpf/extractor/TestExternalEntities.java | 6 +- .../xwpf/extractor/TestXWPFWordExtractor.java | 16 +- .../poi/xwpf/model/TestXWPFDecorators.java | 16 +- .../model/TestXWPFHeaderFooterPolicy.java | 16 +- .../xwpf/usermodel/TestChangeTracking.java | 6 +- .../poi/xwpf/usermodel/TestXWPFBugs.java | 16 +- .../poi/xwpf/usermodel/TestXWPFChart.java | 6 +- .../poi/xwpf/usermodel/TestXWPFComment.java | 4 +- .../poi/xwpf/usermodel/TestXWPFDocument.java | 35 +- .../poi/xwpf/usermodel/TestXWPFEndnote.java | 87 +- .../poi/xwpf/usermodel/TestXWPFEndnotes.java | 8 +- .../poi/xwpf/usermodel/TestXWPFFootnote.java | 91 +- .../poi/xwpf/usermodel/TestXWPFFootnotes.java | 10 +- .../poi/xwpf/usermodel/TestXWPFHeader.java | 18 +- .../poi/xwpf/usermodel/TestXWPFHeadings.java | 8 +- .../poi/xwpf/usermodel/TestXWPFNumbering.java | 8 +- .../poi/xwpf/usermodel/TestXWPFParagraph.java | 14 +- .../xwpf/usermodel/TestXWPFPictureData.java | 26 +- .../poi/xwpf/usermodel/TestXWPFRun.java | 22 +- .../poi/xwpf/usermodel/TestXWPFSDT.java | 22 +- .../poi/xwpf/usermodel/TestXWPFSmartTag.java | 2 +- .../poi/xwpf/usermodel/TestXWPFStyles.java | 34 +- .../poi/xwpf/usermodel/TestXWPFTable.java | 14 +- .../poi/xwpf/usermodel/TestXWPFTableCell.java | 12 +- .../poi/xwpf/usermodel/TestXWPFTableRow.java | 28 +- .../xwpf/usermodel/XWPFAbstractNumTest.java | 4 +- .../org/apache/poi/hdgf/TestHDGFCore.java | 14 +- .../org/apache/poi/hdgf/TestHDGFLZW.java | 6 +- .../apache/poi/hdgf/chunks/TestChunks.java | 14 +- .../apache/poi/hdgf/dev/TestVSDDumper.java | 10 +- .../hdgf/extractor/TestVisioExtractor.java | 6 +- .../poi/hdgf/pointers/TestPointerFactory.java | 13 +- .../poi/hdgf/streams/TestStreamBasics.java | 18 +- .../poi/hdgf/streams/TestStreamBugs.java | 6 +- .../poi/hdgf/streams/TestStreamComplex.java | 18 +- .../extractor/TestHemfPlusExtractor.java | 4 +- .../poi/hemf/usermodel/TestHemfPicture.java | 22 +- .../org/apache/poi/hmef/TestAttachments.java | 10 +- .../org/apache/poi/hmef/TestBugs.java | 8 +- .../apache/poi/hmef/TestCompressedRTF.java | 10 +- .../org/apache/poi/hmef/TestHMEFMessage.java | 18 +- .../hmef/attribute/TestMAPIAttributes.java | 10 +- .../hmef/attribute/TestTNEFAttributes.java | 10 +- .../apache/poi/hmef/dev/TestHMEFDumper.java | 11 +- .../extractor/TestHMEFContentsExtractor.java | 20 +- .../org/apache/poi/hpbf/TestHPBFDocument.java | 8 +- .../extractor/TestPublisherTextExtractor.java | 6 +- .../poi/hpbf/model/TestEscherParts.java | 10 +- .../poi/hpbf/model/TestQuillContents.java | 10 +- .../org/apache/poi/hslf/AllHSLFTests.java | 46 - .../apache/poi/hslf/TestEncryptedFile.java | 21 +- .../poi/hslf/TestPOIDocumentScratchpad.java | 10 +- .../org/apache/poi/hslf/TestReWrite.java | 34 +- .../apache/poi/hslf/TestReWriteSanity.java | 16 +- .../org/apache/poi/hslf/TestRecordCounts.java | 8 +- .../poi/hslf/dev/BasePPTIteratingTest.java | 41 +- .../hslf/dev/TestPPDrawingTextListing.java | 13 +- .../apache/poi/hslf/dev/TestPPTXMLDump.java | 4 +- .../apache/poi/hslf/dev/TestSLWTListing.java | 20 +- .../poi/hslf/dev/TestSLWTTextListing.java | 13 +- .../dev/TestSlideAndNotesAtomListing.java | 13 +- .../poi/hslf/dev/TestSlideIdListing.java | 13 +- .../poi/hslf/dev/TestSlideShowDumper.java | 13 +- .../hslf/dev/TestSlideShowRecordDumper.java | 12 +- .../poi/hslf/dev/TestTextStyleListing.java | 14 +- .../dev/TestUserEditAndPersistListing.java | 13 +- .../hslf/extractor/TestCruddyExtractor.java | 8 +- .../poi/hslf/extractor/TestExtractor.java | 73 +- .../poi/hslf/model/AllHSLFModelTests.java | 45 - .../apache/poi/hslf/model/TestFreeform.java | 6 +- .../poi/hslf/model/TestHeadersFooters.java | 16 +- .../apache/poi/hslf/model/TestHyperlink.java | 7 +- .../org/apache/poi/hslf/model/TestLine.java | 4 +- .../apache/poi/hslf/model/TestMovieShape.java | 8 +- .../poi/hslf/model/TestOleEmbedding.java | 59 +- .../org/apache/poi/hslf/model/TestPPFont.java | 6 +- .../poi/hslf/model/TestSetBoldItalic.java | 4 +- .../org/apache/poi/hslf/model/TestShapes.java | 32 +- .../org/apache/poi/hslf/model/TestSheet.java | 10 +- .../poi/hslf/model/TestSlideChangeNotes.java | 8 +- .../poi/hslf/model/TestSlideMaster.java | 10 +- .../org/apache/poi/hslf/model/TestSlides.java | 6 +- .../org/apache/poi/hslf/model/TestTable.java | 19 +- .../poi/hslf/model/TestTextRunReWrite.java | 20 +- .../poi/hslf/record/AllHSLFRecordTests.java | 70 - .../hslf/record/TestAnimationInfoAtom.java | 10 +- .../apache/poi/hslf/record/TestCString.java | 8 +- .../poi/hslf/record/TestColorSchemeAtom.java | 4 +- .../poi/hslf/record/TestComment2000.java | 110 +- .../poi/hslf/record/TestComment2000Atom.java | 10 +- .../poi/hslf/record/TestCurrentUserAtom.java | 36 +- .../apache/poi/hslf/record/TestDocument.java | 10 +- .../poi/hslf/record/TestDocumentAtom.java | 10 +- .../hslf/record/TestDocumentEncryption.java | 45 +- .../record/TestDocumentEncryptionAtom.java | 4 +- .../apache/poi/hslf/record/TestExControl.java | 8 +- .../poi/hslf/record/TestExHyperlink.java | 12 +- .../poi/hslf/record/TestExHyperlinkAtom.java | 6 +- .../poi/hslf/record/TestExMediaAtom.java | 10 +- .../apache/poi/hslf/record/TestExObjList.java | 6 +- .../poi/hslf/record/TestExObjListAtom.java | 12 +- .../poi/hslf/record/TestExOleObjAtom.java | 6 +- .../poi/hslf/record/TestExOleObjStg.java | 25 +- .../poi/hslf/record/TestExVideoContainer.java | 10 +- .../poi/hslf/record/TestFontCollection.java | 18 +- .../hslf/record/TestHeadersFootersAtom.java | 10 +- .../record/TestHeadersFootersContainer.java | 10 +- .../poi/hslf/record/TestInteractiveInfo.java | 6 +- .../hslf/record/TestInteractiveInfoAtom.java | 6 +- .../apache/poi/hslf/record/TestNotesAtom.java | 8 +- .../poi/hslf/record/TestRecordContainer.java | 20 +- .../poi/hslf/record/TestRecordTypes.java | 4 +- .../apache/poi/hslf/record/TestSlideAtom.java | 14 +- .../poi/hslf/record/TestSlidePersistAtom.java | 8 +- .../org/apache/poi/hslf/record/TestSound.java | 10 +- .../hslf/record/TestStyleTextPropAtom.java | 120 +- .../poi/hslf/record/TestTextBytesAtom.java | 6 +- .../poi/hslf/record/TestTextCharsAtom.java | 6 +- .../poi/hslf/record/TestTextHeaderAtom.java | 6 +- .../poi/hslf/record/TestTextRulerAtom.java | 8 +- .../poi/hslf/record/TestTextSpecInfoAtom.java | 6 +- .../record/TestTxInteractiveInfoAtom.java | 6 +- .../hslf/record/TestTxMasterStyleAtom.java | 34 +- .../poi/hslf/record/TestUserEditAtom.java | 6 +- .../hslf/usermodel/AllHSLFUserModelTests.java | 47 - .../poi/hslf/usermodel/TestAddingSlides.java | 44 +- .../poi/hslf/usermodel/TestBackground.java | 6 +- .../apache/poi/hslf/usermodel/TestBugs.java | 27 +- .../apache/poi/hslf/usermodel/TestCounts.java | 12 +- .../poi/hslf/usermodel/TestFontRendering.java | 40 +- .../poi/hslf/usermodel/TestHSLFSlideShow.java | 22 +- .../usermodel/TestHSLFSlideShowFactory.java | 2 +- .../hslf/usermodel/TestMostRecentRecords.java | 9 +- .../poi/hslf/usermodel/TestNotesText.java | 8 +- .../poi/hslf/usermodel/TestNumberedList.java | 24 +- .../poi/hslf/usermodel/TestNumberedList2.java | 45 +- .../poi/hslf/usermodel/TestNumberedList3.java | 42 +- .../poi/hslf/usermodel/TestPicture.java | 14 +- .../poi/hslf/usermodel/TestPictures.java | 12 +- .../hslf/usermodel/TestReOrderingSlides.java | 18 +- .../poi/hslf/usermodel/TestRecordSetup.java | 8 +- .../poi/hslf/usermodel/TestRichTextRun.java | 277 +- .../poi/hslf/usermodel/TestSheetText.java | 14 +- .../poi/hslf/usermodel/TestSlideOrdering.java | 14 +- .../poi/hslf/usermodel/TestSoundData.java | 8 +- .../apache/poi/hslf/usermodel/TestTable.java | 38 +- .../poi/hslf/usermodel/TestTextRun.java | 22 +- .../poi/hslf/usermodel/TestTextShape.java | 16 +- .../poi/hslf/util/TestSystemTimeUtils.java | 10 +- .../org/apache/poi/hsmf/AllHSMFTests.java | 46 - .../org/apache/poi/hsmf/Test7BitCodepage.java | 10 +- .../org/apache/poi/hsmf/TestBasics.java | 64 +- .../apache/poi/hsmf/TestBlankFileRead.java | 27 +- .../poi/hsmf/TestExtractEmbeddedMSG.java | 14 +- .../poi/hsmf/TestFileWithAttachmentsRead.java | 18 +- .../poi/hsmf/TestFixedSizedProperties.java | 38 +- .../poi/hsmf/TestMessageSubmissionChunk.java | 10 +- .../TestMessageSubmissionChunkY2KRead.java | 8 +- .../org/apache/poi/hsmf/TestNameIdChunks.java | 14 +- .../poi/hsmf/TestOutlook30FileRead.java | 16 +- .../apache/poi/hsmf/TestSimpleFileRead.java | 9 +- .../poi/hsmf/datatypes/TestChunkData.java | 4 +- .../poi/hsmf/datatypes/TestMAPIProperty.java | 10 +- .../poi/hsmf/datatypes/TestSorters.java | 4 +- .../apache/poi/hsmf/datatypes/TestTypes.java | 4 +- .../extractor/TestOutlookTextExtractor.java | 12 +- .../hsmf/parsers/TestPOIFSChunkParser.java | 12 +- .../converter/TestExcelConverterSuite.java | 38 +- .../org/apache/poi/hwmf/TestHwmfParsing.java | 13 +- .../org/apache/poi/hwmf/TestRasterOp.java | 4 +- .../org/apache/poi/hwpf/AllHWPFTests.java | 118 - .../org/apache/poi/hwpf/HWPFTestCase.java | 8 +- .../org/apache/poi/hwpf/TestFieldsTables.java | 4 +- .../org/apache/poi/hwpf/TestHWPFPictures.java | 17 +- .../apache/poi/hwpf/TestHWPFRangeParts.java | 8 +- .../hwpf/converter/AbstractWordUtilsTest.java | 4 +- .../hwpf/converter/TestNumberFormatter.java | 4 +- .../converter/TestWordToConverterSuite.java | 89 +- .../hwpf/converter/TestWordToFoConverter.java | 2 +- .../converter/TestWordToHtmlConverter.java | 4 +- .../converter/TestWordToTextConverter.java | 4 +- .../apache/poi/hwpf/dev/TestHWPFLister.java | 14 +- .../hwpf/extractor/TestDifferentRoutes.java | 17 +- .../poi/hwpf/extractor/TestWordExtractor.java | 47 +- .../hwpf/extractor/TestWordExtractorBugs.java | 4 +- .../org/apache/poi/hwpf/model/PlfLfoTest.java | 6 +- .../poi/hwpf/model/TestBookmarksTables.java | 4 +- .../poi/hwpf/model/TestCHPBinTable.java | 12 +- .../hwpf/model/TestDocumentProperties.java | 14 +- .../hwpf/model/TestFileInformationBlock.java | 12 +- .../apache/poi/hwpf/model/TestFontTable.java | 13 +- .../apache/poi/hwpf/model/TestListTables.java | 16 +- .../poi/hwpf/model/TestNotesTables.java | 4 +- .../poi/hwpf/model/TestPAPBinTable.java | 6 +- .../apache/poi/hwpf/model/TestPlexOfCps.java | 12 +- .../model/TestRevisionMarkAuthorTable.java | 8 +- .../poi/hwpf/model/TestSavedByTable.java | 12 +- .../poi/hwpf/model/TestSectionTable.java | 12 +- .../apache/poi/hwpf/model/TestStyleSheet.java | 12 +- .../poi/hwpf/model/TestTextPieceTable.java | 16 +- .../types/LFOLVLBaseAbstractTypeTest.java | 4 +- .../model/types/LVLFAbstractTypeTest.java | 4 +- .../hwpf/sprm/TableSprmUncompressorTest.java | 4 +- .../org/apache/poi/hwpf/sprm/TestSprms.java | 6 +- .../poi/hwpf/usermodel/TestBorderCode.java | 8 +- .../poi/hwpf/usermodel/TestBug46610.java | 5 +- .../poi/hwpf/usermodel/TestBug47563.java | 49 +- .../poi/hwpf/usermodel/TestBug49820.java | 4 +- .../poi/hwpf/usermodel/TestBug50075.java | 6 +- .../apache/poi/hwpf/usermodel/TestBugs.java | 28 +- .../hwpf/usermodel/TestHWPFOldDocument.java | 60 +- .../poi/hwpf/usermodel/TestHWPFWrite.java | 25 +- .../poi/hwpf/usermodel/TestHeaderStories.java | 12 +- .../apache/poi/hwpf/usermodel/TestLists.java | 8 +- .../hwpf/usermodel/TestOfficeDrawings.java | 4 +- .../poi/hwpf/usermodel/TestPictures.java | 52 +- .../poi/hwpf/usermodel/TestProblems.java | 28 +- .../apache/poi/hwpf/usermodel/TestRange.java | 8 +- .../poi/hwpf/usermodel/TestRangeDelete.java | 4 +- .../hwpf/usermodel/TestRangeInsertion.java | 4 +- .../hwpf/usermodel/TestRangeProperties.java | 12 +- .../hwpf/usermodel/TestRangeReplacement.java | 4 +- .../poi/hwpf/usermodel/TestRangeSymbols.java | 4 +- .../poi/hwpf/usermodel/TestTableRow.java | 8 +- .../util/TestLittleEndianCP950Reader.java | 6 +- src/testcases/org/apache/poi/AllPOITests.java | 40 - src/testcases/org/apache/poi/POITestCase.java | 32 +- src/testcases/org/apache/poi/TestJDK12.java | 2 +- .../org/apache/poi/TestPOIDocumentMain.java | 22 +- .../org/apache/poi/TestPOITestCase.java | 4 +- .../org/apache/poi/ddf/AllPOIDDFTests.java | 42 - .../apache/poi/ddf/TestEscherBSERecord.java | 8 +- .../apache/poi/ddf/TestEscherBlipRecord.java | 10 +- .../poi/ddf/TestEscherBoolProperty.java | 4 +- .../poi/ddf/TestEscherChildAnchorRecord.java | 4 +- .../poi/ddf/TestEscherClientAnchorRecord.java | 4 +- .../poi/ddf/TestEscherClientDataRecord.java | 6 +- .../poi/ddf/TestEscherContainerRecord.java | 12 +- .../apache/poi/ddf/TestEscherDgRecord.java | 4 +- .../apache/poi/ddf/TestEscherDggRecord.java | 4 +- .../org/apache/poi/ddf/TestEscherDump.java | 12 +- .../apache/poi/ddf/TestEscherOptRecord.java | 6 +- .../apache/poi/ddf/TestEscherProperty.java | 10 +- .../poi/ddf/TestEscherPropertyFactory.java | 4 +- .../apache/poi/ddf/TestEscherSpRecord.java | 4 +- .../apache/poi/ddf/TestEscherSpgrRecord.java | 4 +- .../ddf/TestEscherSplitMenuColorsRecord.java | 4 +- .../poi/ddf/TestUnknownEscherRecord.java | 16 +- .../apache/poi/hpsf/TestVariantSupport.java | 24 +- .../poi/hpsf/basic/AllPOIHPSFBasicTests.java | 37 - .../org/apache/poi/hpsf/basic/TestBasic.java | 12 +- .../apache/poi/hpsf/basic/TestClassID.java | 15 +- .../poi/hpsf/basic/TestEmptyProperties.java | 12 +- .../apache/poi/hpsf/basic/TestHPSFBugs.java | 8 +- .../poi/hpsf/basic/TestMetaDataIPI.java | 160 +- .../poi/hpsf/basic/TestReadAllFiles.java | 47 +- .../apache/poi/hpsf/basic/TestUnicode.java | 10 +- .../org/apache/poi/hpsf/basic/TestWrite.java | 51 +- .../poi/hpsf/basic/TestWriteWellKnown.java | 44 +- .../org/apache/poi/hpsf/basic/Util.java | 59 +- .../TestHPSFPropertiesExtractor.java | 6 +- .../org/apache/poi/hssf/HSSFTests.java | 48 - .../poi/hssf/dev/BaseTestIteratingXLS.java | 40 +- .../poi/hssf/dev/TestBiffDrawingToXml.java | 4 +- .../apache/poi/hssf/dev/TestBiffViewer.java | 4 +- .../apache/poi/hssf/dev/TestEFBiffViewer.java | 4 +- .../poi/hssf/dev/TestFormulaViewer.java | 6 +- .../org/apache/poi/hssf/dev/TestReSave.java | 12 +- .../apache/poi/hssf/dev/TestRecordLister.java | 4 +- .../eventmodel/TestAbortableListener.java | 6 +- .../eventmodel/TestEventRecordFactory.java | 25 +- .../AllEventUserModelTests.java | 34 - .../TestEventWorkbookBuilder.java | 13 +- .../TestFormatTrackingHSSFListener.java | 36 +- .../eventusermodel/TestHSSFEventFactory.java | 25 +- .../TestMissingRecordAwareHSSFListener.java | 7 +- .../hssf/extractor/TestExcelExtractor.java | 8 +- .../hssf/extractor/TestOldExcelExtractor.java | 60 +- .../apache/poi/hssf/model/AllModelTests.java | 41 - .../poi/hssf/model/TestDrawingAggregate.java | 280 +- .../poi/hssf/model/TestDrawingManager2.java | 8 +- .../poi/hssf/model/TestDrawingShapes.java | 52 +- .../hssf/model/TestEscherRecordFactory.java | 53 +- .../poi/hssf/model/TestFormulaParser.java | 280 +- .../poi/hssf/model/TestFormulaParserEval.java | 6 +- .../poi/hssf/model/TestFormulaParserIf.java | 40 +- .../apache/poi/hssf/model/TestHSSFAnchor.java | 16 +- .../apache/poi/hssf/model/TestLinkTable.java | 14 +- .../model/TestOperandClassTransformer.java | 18 +- .../org/apache/poi/hssf/model/TestRVA.java | 64 +- .../poi/hssf/model/TestRowBlocksReader.java | 18 +- .../org/apache/poi/hssf/model/TestSheet.java | 126 +- .../poi/hssf/model/TestSheetAdditional.java | 6 +- .../apache/poi/hssf/model/TestWorkbook.java | 20 +- .../poi/hssf/record/AllRecordTests.java | 96 - .../poi/hssf/record/TestArrayRecord.java | 6 +- .../hssf/record/TestAutoFilterInfoRecord.java | 6 +- .../apache/poi/hssf/record/TestBOFRecord.java | 4 +- .../poi/hssf/record/TestBoolErrRecord.java | 10 +- .../poi/hssf/record/TestBoundSheetRecord.java | 15 +- .../poi/hssf/record/TestCFHeaderRecord.java | 20 +- .../poi/hssf/record/TestCFRuleRecord.java | 21 +- .../poi/hssf/record/TestColumnInfoRecord.java | 8 +- .../record/TestCommonObjectDataSubRecord.java | 8 +- .../poi/hssf/record/TestDConRefRecord.java | 30 +- .../poi/hssf/record/TestDVALRecord.java | 8 +- .../hssf/record/TestDrawingGroupRecord.java | 4 +- .../poi/hssf/record/TestDrawingRecord.java | 8 +- .../TestEmbeddedObjectRefSubRecord.java | 6 +- .../poi/hssf/record/TestEndSubRecord.java | 4 +- .../poi/hssf/record/TestEscherAggregate.java | 4 +- .../poi/hssf/record/TestExtSSTRecord.java | 4 +- .../hssf/record/TestExtendedFormatRecord.java | 4 +- .../hssf/record/TestExternalNameRecord.java | 14 +- .../poi/hssf/record/TestFeatRecord.java | 12 +- .../poi/hssf/record/TestFontRecord.java | 12 +- .../poi/hssf/record/TestFormulaRecord.java | 28 +- .../poi/hssf/record/TestFtCblsSubRecord.java | 6 +- .../poi/hssf/record/TestHyperlinkRecord.java | 10 +- .../hssf/record/TestInterfaceEndRecord.java | 4 +- .../poi/hssf/record/TestLabelRecord.java | 4 +- .../poi/hssf/record/TestLbsDataSubRecord.java | 10 +- .../poi/hssf/record/TestMergeCellsRecord.java | 18 +- .../hssf/record/TestNameCommentRecord.java | 4 +- .../poi/hssf/record/TestNameRecord.java | 10 +- .../poi/hssf/record/TestNoteRecord.java | 12 +- .../record/TestNoteStructureSubRecord.java | 6 +- .../apache/poi/hssf/record/TestObjRecord.java | 16 +- .../apache/poi/hssf/record/TestPLVRecord.java | 2 +- .../poi/hssf/record/TestPaletteRecord.java | 12 +- .../poi/hssf/record/TestPaneRecord.java | 4 +- .../poi/hssf/record/TestRecalcIdRecord.java | 6 +- .../poi/hssf/record/TestRecordFactory.java | 38 +- .../record/TestRecordFactoryInputStream.java | 10 +- .../hssf/record/TestRecordInputStream.java | 4 +- .../apache/poi/hssf/record/TestSCLRecord.java | 4 +- .../poi/hssf/record/TestSSTDeserializer.java | 14 +- .../apache/poi/hssf/record/TestSSTRecord.java | 16 +- .../record/TestSSTRecordSizeCalculator.java | 4 +- .../hssf/record/TestSharedFormulaRecord.java | 12 +- .../poi/hssf/record/TestStringRecord.java | 16 +- .../poi/hssf/record/TestStyleRecord.java | 4 +- .../apache/poi/hssf/record/TestSubRecord.java | 16 +- .../poi/hssf/record/TestSupBookRecord.java | 6 +- .../poi/hssf/record/TestTableRecord.java | 4 +- .../hssf/record/TestTextObjectBaseRecord.java | 8 +- .../poi/hssf/record/TestTextObjectRecord.java | 10 +- .../hssf/record/TestUnicodeNameRecord.java | 4 +- .../hssf/record/TestWriteAccessRecord.java | 4 +- .../record/TestcaseRecordInputStream.java | 6 +- .../aggregates/AllRecordAggregateTests.java | 37 - .../aggregates/TestCFRecordsAggregate.java | 40 +- .../TestColumnInfoRecordsAggregate.java | 19 +- .../TestFormulaRecordAggregate.java | 9 +- .../aggregates/TestPageSettingsBlock.java | 16 +- .../aggregates/TestRowRecordsAggregate.java | 22 +- .../aggregates/TestSharedValueManager.java | 6 +- .../aggregates/TestValueRecordsAggregate.java | 22 +- .../poi/hssf/record/cf/TestCellRange.java | 22 +- .../record/chart/AllChartRecordTests.java | 66 - .../record/chart/TestAreaFormatRecord.java | 8 +- .../poi/hssf/record/chart/TestAreaRecord.java | 8 +- .../chart/TestAxisLineFormatRecord.java | 4 +- .../record/chart/TestAxisOptionsRecord.java | 8 +- .../record/chart/TestAxisParentRecord.java | 4 +- .../poi/hssf/record/chart/TestAxisRecord.java | 4 +- .../hssf/record/chart/TestAxisUsedRecord.java | 4 +- .../poi/hssf/record/chart/TestBarRecord.java | 6 +- .../chart/TestCategorySeriesAxisRecord.java | 8 +- .../record/chart/TestChartFormatRecord.java | 10 +- .../hssf/record/chart/TestChartRecord.java | 4 +- .../chart/TestChartTitleFormatRecord.java | 21 +- .../poi/hssf/record/chart/TestDatRecord.java | 8 +- .../record/chart/TestDataFormatRecord.java | 6 +- ...tDefaultDataLabelTextPropertiesRecord.java | 4 +- .../record/chart/TestFontBasisRecord.java | 4 +- .../record/chart/TestFontIndexRecord.java | 4 +- .../hssf/record/chart/TestFrameRecord.java | 8 +- .../hssf/record/chart/TestLegendRecord.java | 8 +- .../record/chart/TestLineFormatRecord.java | 8 +- .../record/chart/TestLinkedDataRecord.java | 6 +- .../chart/TestNumberFormatIndexRecord.java | 4 +- .../record/chart/TestObjectLinkRecord.java | 4 +- .../hssf/record/chart/TestPlotAreaRecord.java | 4 +- .../record/chart/TestPlotGrowthRecord.java | 4 +- .../TestSeriesChartGroupIndexRecord.java | 4 +- .../record/chart/TestSeriesIndexRecord.java | 4 +- .../record/chart/TestSeriesLabelsRecord.java | 8 +- .../record/chart/TestSeriesListRecord.java | 4 +- .../hssf/record/chart/TestSeriesRecord.java | 4 +- .../record/chart/TestSeriesTextRecord.java | 8 +- .../chart/TestSheetPropertiesRecord.java | 12 +- .../poi/hssf/record/chart/TestTextRecord.java | 8 +- .../poi/hssf/record/chart/TestTickRecord.java | 6 +- .../hssf/record/chart/TestUnitsRecord.java | 4 +- .../record/chart/TestValueRangeRecord.java | 8 +- .../hssf/record/common/TestUnicodeString.java | 4 +- .../record/pivot/AllPivotRecordTests.java | 33 - ...estExtendedPivotTableViewFieldsRecord.java | 4 +- .../hssf/record/pivot/TestPageItemRecord.java | 8 +- .../record/pivot/TestViewFieldsRecord.java | 8 +- .../poi/hssf/usermodel/AllUserModelTests.java | 76 - .../poi/hssf/usermodel/SanityChecker.java | 246 +- .../poi/hssf/usermodel/TestBug42464.java | 8 +- .../apache/poi/hssf/usermodel/TestBugs.java | 57 +- .../poi/hssf/usermodel/TestCellStyle.java | 38 +- .../poi/hssf/usermodel/TestCloneSheet.java | 27 +- .../poi/hssf/usermodel/TestCryptoAPI.java | 5 +- .../hssf/usermodel/TestDataValidation.java | 17 +- .../hssf/usermodel/TestEmbeddedObjects.java | 6 +- .../hssf/usermodel/TestEscherGraphics.java | 22 +- .../hssf/usermodel/TestEscherGraphics2d.java | 24 +- .../TestExternalReferenceChange.java | 10 +- .../poi/hssf/usermodel/TestFontDetails.java | 8 +- .../usermodel/TestFormulaEvaluatorBugs.java | 63 +- .../usermodel/TestFormulaEvaluatorDocs.java | 4 +- .../poi/hssf/usermodel/TestFormulas.java | 75 +- .../poi/hssf/usermodel/TestHSSFCell.java | 98 +- .../poi/hssf/usermodel/TestHSSFChart.java | 38 +- .../hssf/usermodel/TestHSSFClientAnchor.java | 20 +- .../poi/hssf/usermodel/TestHSSFComment.java | 50 +- .../TestHSSFConditionalFormatting.java | 37 +- .../hssf/usermodel/TestHSSFDataFormat.java | 10 +- .../hssf/usermodel/TestHSSFDataFormatter.java | 38 +- .../poi/hssf/usermodel/TestHSSFDateUtil.java | 24 +- .../usermodel/TestHSSFEvaluationSheet.java | 10 +- .../poi/hssf/usermodel/TestHSSFFont.java | 2 +- .../usermodel/TestHSSFFormulaEvaluator.java | 475 +- .../hssf/usermodel/TestHSSFHeaderFooter.java | 16 +- .../poi/hssf/usermodel/TestHSSFHyperlink.java | 14 +- .../poi/hssf/usermodel/TestHSSFName.java | 56 +- .../poi/hssf/usermodel/TestHSSFOptimiser.java | 48 +- .../poi/hssf/usermodel/TestHSSFPalette.java | 92 +- .../poi/hssf/usermodel/TestHSSFPatriarch.java | 4 +- .../poi/hssf/usermodel/TestHSSFPicture.java | 6 +- .../hssf/usermodel/TestHSSFPictureData.java | 18 +- .../hssf/usermodel/TestHSSFRangeCopier.java | 4 +- .../usermodel/TestHSSFRichTextString.java | 4 +- .../poi/hssf/usermodel/TestHSSFRow.java | 32 +- .../poi/hssf/usermodel/TestHSSFSheet.java | 118 +- .../usermodel/TestHSSFSheetShiftColumns.java | 78 +- .../TestHSSFSheetUpdateArrayFormulas.java | 19 +- .../poi/hssf/usermodel/TestHSSFTextbox.java | 4 +- .../poi/hssf/usermodel/TestHSSFWorkbook.java | 227 +- ...stMatrixFormulasFromBinarySpreadsheet.java | 100 +- .../TestNonStandardWorkbookStreamNames.java | 18 +- .../poi/hssf/usermodel/TestOLE2Embeding.java | 64 +- .../hssf/usermodel/TestPOIFSProperties.java | 8 +- .../poi/hssf/usermodel/TestPatriarch.java | 10 +- .../poi/hssf/usermodel/TestPolygon.java | 24 +- .../hssf/usermodel/TestReadWriteChart.java | 8 +- .../poi/hssf/usermodel/TestRowStyle.java | 45 +- .../poi/hssf/usermodel/TestSanityChecker.java | 21 +- .../poi/hssf/usermodel/TestShapeGroup.java | 8 +- .../poi/hssf/usermodel/TestSheetHiding.java | 18 +- .../apache/poi/hssf/usermodel/TestText.java | 14 +- .../poi/hssf/usermodel/TestUnfixedBugs.java | 6 +- .../hssf/usermodel/TestUnicodeWorkbook.java | 6 +- .../poi/hssf/usermodel/TestWorkbook.java | 109 +- .../poi/hssf/util/AllHSSFUtilTests.java | 34 - .../poi/hssf/util/TestAreaReference.java | 58 +- .../poi/hssf/util/TestCellReference.java | 32 +- .../apache/poi/hssf/util/TestHSSFColor.java | 14 +- .../org/apache/poi/hssf/util/TestRKUtil.java | 4 +- .../org/apache/poi/poifs/AllPOIFSTests.java | 42 - .../poi/poifs/crypt/AllEncryptionTests.java | 33 - .../crypt/TestBiff8DecryptingStream.java | 14 +- .../poi/poifs/crypt/TestCipherAlgorithm.java | 27 +- .../poi/poifs/crypt/TestXorEncryption.java | 8 +- .../poifs/crypt/binaryrc4/TestBinaryRC4.java | 24 +- .../apache/poi/poifs/dev/TestPOIFSDump.java | 89 +- .../TestPOIFSReaderRegistry.java | 8 +- .../filesystem/AllPOIFSFileSystemTests.java | 42 - .../poifs/filesystem/TestDirectoryNode.java | 28 +- .../poi/poifs/filesystem/TestDocument.java | 10 +- .../filesystem/TestDocumentDescriptor.java | 10 +- .../filesystem/TestDocumentInputStream.java | 159 +- .../filesystem/TestDocumentOutputStream.java | 26 +- .../poifs/filesystem/TestEmptyDocument.java | 40 +- .../poi/poifs/filesystem/TestEntryUtils.java | 80 +- .../poi/poifs/filesystem/TestFileMagic.java | 27 +- .../poifs/filesystem/TestFileSystemBugs.java | 10 +- .../TestFilteringDirectoryNode.java | 256 +- .../filesystem/TestNotOLE2Exception.java | 24 +- .../filesystem/TestOfficeXMLException.java | 12 +- .../poi/poifs/filesystem/TestOle10Native.java | 8 +- .../filesystem/TestPOIFSDocumentPath.java | 37 +- .../poifs/filesystem/TestPOIFSFileSystem.java | 39 +- .../poifs/filesystem/TestPOIFSMiniStore.java | 783 ++- .../poi/poifs/filesystem/TestPOIFSStream.java | 5517 ++++++++--------- .../poifs/filesystem/TestPropertySorter.java | 8 +- .../poi/poifs/macros/TestVBAMacroReader.java | 36 +- .../apache/poi/poifs/nio/TestDataSource.java | 77 +- .../poifs/property/AllPOIFSPropertyTests.java | 35 - .../poifs/property/TestDirectoryProperty.java | 52 +- .../poifs/property/TestDocumentProperty.java | 17 +- .../poifs/property/TestPropertyFactory.java | 24 +- .../poi/poifs/property/TestPropertyTable.java | 16 +- .../poi/poifs/property/TestRootProperty.java | 14 +- .../poifs/storage/AllPOIFSStorageTests.java | 31 - .../poi/poifs/storage/TestBATBlock.java | 8 +- .../poifs/storage/TestHeaderBlockReading.java | 23 +- .../poi/sl/draw/geom/TestFormulaParser.java | 4 +- .../sl/draw/geom/TestPresetGeometries.java | 12 +- .../poi/sl/usermodel/BaseTestSlideShow.java | 14 +- .../usermodel/BaseTestSlideShowFactory.java | 43 +- .../apache/poi/ss/TestSpreadsheetVersion.java | 4 +- .../apache/poi/ss/format/TestCellFormat.java | 20 +- .../ss/format/TestCellFormatCondition.java | 6 +- .../poi/ss/format/TestCellFormatResult.java | 10 +- .../poi/ss/formula/AllSSFormulaTests.java | 35 - .../ss/formula/BaseTestExternalFunctions.java | 64 +- .../ss/formula/BaseTestMissingWorkbook.java | 29 +- ...eetRangeAndWorkbookIndexFormatterTest.java | 4 +- .../poi/ss/formula/TestCellCacheEntry.java | 4 +- .../poi/ss/formula/TestEvaluationCache.java | 15 +- .../poi/ss/formula/TestFormulaShifter.java | 151 +- .../poi/ss/formula/TestFunctionRegistry.java | 30 +- .../poi/ss/formula/TestPlainCellCache.java | 8 +- .../ss/formula/TestSheetNameFormatter.java | 46 +- .../poi/ss/formula/TestWorkbookEvaluator.java | 155 +- .../poi/ss/formula/atp/TestDateParser.java | 79 - .../poi/ss/formula/atp/TestIfError.java | 29 +- .../apache/poi/ss/formula/atp/TestMRound.java | 24 +- .../formula/atp/TestNetworkdaysFunction.java | 4 +- .../poi/ss/formula/atp/TestPercentile.java | 4 +- .../poi/ss/formula/atp/TestRandBetween.java | 17 +- .../ss/formula/atp/TestWorkdayCalculator.java | 10 +- .../ss/formula/atp/TestWorkdayFunction.java | 12 +- .../formula/atp/TestYearFracCalculator.java | 6 +- ...TestYearFracCalculatorFromSpreadsheet.java | 34 +- .../constant/TestConstantValueParser.java | 17 +- .../ss/formula/eval/AllFormulaEvalTests.java | 42 - .../eval/BaseTestCircularReferences.java | 12 +- .../poi/ss/formula/eval/TestAreaEval.java | 8 +- .../poi/ss/formula/eval/TestDivideEval.java | 4 +- .../poi/ss/formula/eval/TestEqualEval.java | 20 +- .../ss/formula/eval/TestExternalFunction.java | 4 +- .../poi/ss/formula/eval/TestFormulaBugs.java | 129 +- .../eval/TestFormulasFromSpreadsheet.java | 89 +- .../ss/formula/eval/TestMinusZeroResult.java | 8 +- .../ss/formula/eval/TestMissingArgEval.java | 8 +- .../ss/formula/eval/TestMultiSheetEval.java | 63 +- .../ss/formula/eval/TestOperandResolver.java | 10 +- .../poi/ss/formula/eval/TestPercentEval.java | 4 +- .../poi/ss/formula/eval/TestPowerEval.java | 4 +- .../poi/ss/formula/eval/TestRangeEval.java | 6 +- .../ss/formula/eval/TestUnaryPlusEval.java | 4 +- .../eval/forked/BaseTestForkedEvaluator.java | 8 +- .../function/AllFormulaFunctionTests.java | 33 - .../TestFunctionMetadataRegistry.java | 6 +- .../TestParseMissingBuiltInFuncs.java | 8 +- .../function/TestReadMissingBuiltInFuncs.java | 58 +- .../AllIndividualFunctionEvaluationTests.java | 64 - .../functions/AllSpreadsheetBasedTests.java | 49 - .../BaseTestFunctionsFromSpreadsheet.java | 84 +- .../ss/formula/functions/BaseTestNumeric.java | 29 +- .../functions/NumericFunctionInvoker.java | 2 +- .../poi/ss/formula/functions/TestAddress.java | 4 +- .../poi/ss/formula/functions/TestAreas.java | 4 +- .../poi/ss/formula/functions/TestAverage.java | 4 +- .../poi/ss/formula/functions/TestBin2Dec.java | 22 +- .../TestBooleanFunctionsFromSpreadsheet.java | 7 +- .../functions/TestCalendarFieldFunction.java | 10 +- .../poi/ss/formula/functions/TestClean.java | 4 +- .../poi/ss/formula/functions/TestCode.java | 8 +- .../TestCodeFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestComplex.java | 8 +- .../TestComplexFunctionsFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestCountFuncs.java | 42 +- .../TestDGetFunctionsFromSpreadsheet.java | 7 +- .../TestDStarFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestDate.java | 14 +- .../TestDateTimeToNumberFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestDateValue.java | 12 +- .../poi/ss/formula/functions/TestDays360.java | 18 +- .../poi/ss/formula/functions/TestDec2Bin.java | 37 +- .../poi/ss/formula/functions/TestDec2Hex.java | 41 +- .../poi/ss/formula/functions/TestDelta.java | 4 +- .../TestDeltaFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestEDate.java | 18 +- .../poi/ss/formula/functions/TestEOMonth.java | 18 +- ...estFactDoubleFunctionsFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestFinanceLib.java | 58 +- .../poi/ss/formula/functions/TestFind.java | 6 +- .../poi/ss/formula/functions/TestFixed.java | 24 +- .../TestFixedFunctionsFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestFrequency.java | 19 +- .../poi/ss/formula/functions/TestGeomean.java | 14 +- .../poi/ss/formula/functions/TestHex2Dec.java | 11 +- .../TestIFFunctionFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestIPMT.java | 4 +- .../TestImRealFunctionsFromSpreadsheet.java | 7 +- ...TestImaginaryFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestIndex.java | 6 +- .../TestIndexFunctionFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestIndirect.java | 28 +- .../TestIndirectFunctionFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestIntercept.java | 4 +- .../poi/ss/formula/functions/TestIrr.java | 22 +- .../poi/ss/formula/functions/TestIsBlank.java | 6 +- .../ss/formula/functions/TestLeftRight.java | 4 +- .../poi/ss/formula/functions/TestLen.java | 4 +- .../functions/TestLogicalFunction.java | 10 +- .../TestLogicalFunctionsFromSpreadsheet.java | 7 +- .../TestLookupFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestMatch.java | 15 +- .../TestMatchFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestMathX.java | 490 +- .../poi/ss/formula/functions/TestMid.java | 4 +- .../poi/ss/formula/functions/TestMirr.java | 28 +- .../TestMultiOperandNumericFunction.java | 8 +- .../poi/ss/formula/functions/TestNper.java | 4 +- .../poi/ss/formula/functions/TestNpv.java | 6 +- .../poi/ss/formula/functions/TestOct2Dec.java | 8 +- .../poi/ss/formula/functions/TestOffset.java | 50 +- .../poi/ss/formula/functions/TestPPMT.java | 4 +- .../poi/ss/formula/functions/TestPmt.java | 16 +- .../poi/ss/formula/functions/TestPoisson.java | 4 +- .../poi/ss/formula/functions/TestProduct.java | 6 +- .../ss/formula/functions/TestQuotient.java | 8 +- .../TestQuotientFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestRank.java | 10 +- .../functions/TestRelationalOperations.java | 20 +- .../TestReptFunctionsFromSpreadsheet.java | 7 +- .../TestRomanFunctionsFromSpreadsheet.java | 7 +- .../ss/formula/functions/TestRoundFuncs.java | 8 +- .../poi/ss/formula/functions/TestRowCol.java | 4 +- .../poi/ss/formula/functions/TestSlope.java | 4 +- .../ss/formula/functions/TestStatsLib.java | 97 +- .../ss/formula/functions/TestSubstitute.java | 4 +- .../ss/formula/functions/TestSubtotal.java | 32 +- .../poi/ss/formula/functions/TestSumif.java | 12 +- .../poi/ss/formula/functions/TestSumifs.java | 16 +- .../ss/formula/functions/TestSumproduct.java | 11 +- .../poi/ss/formula/functions/TestTFunc.java | 12 +- .../poi/ss/formula/functions/TestText.java | 12 +- .../poi/ss/formula/functions/TestTime.java | 10 +- .../TestTrendFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestTrim.java | 4 +- .../poi/ss/formula/functions/TestTrunc.java | 19 +- ...perandNumericFunctionsFromSpreadsheet.java | 7 +- .../poi/ss/formula/functions/TestValue.java | 4 +- .../TestWeekNumFunctionsFromSpreadsheet.java | 7 +- ...stWeekNumFunctionsFromSpreadsheet2013.java | 7 +- .../ss/formula/functions/TestWeekdayFunc.java | 54 +- .../functions/TestXYNumericFunction.java | 4 +- .../poi/ss/formula/ptg/AllFormulaTests.java | 54 - .../formula/ptg/TestAbstractFunctionPtg.java | 13 +- .../poi/ss/formula/ptg/TestArea3DPtg.java | 4 +- .../poi/ss/formula/ptg/TestAreaErrPtg.java | 8 +- .../poi/ss/formula/ptg/TestAreaPtg.java | 51 +- .../poi/ss/formula/ptg/TestArrayPtg.java | 10 +- .../poi/ss/formula/ptg/TestAttrPtg.java | 4 +- .../apache/poi/ss/formula/ptg/TestErrPtg.java | 8 +- .../ptg/TestExternalFunctionFormulas.java | 18 +- .../ptg/TestExternalNameReference.java | 6 +- .../poi/ss/formula/ptg/TestFuncPtg.java | 12 +- .../poi/ss/formula/ptg/TestFuncVarPtg.java | 6 +- .../ss/formula/ptg/TestIntersectionPtg.java | 8 +- .../poi/ss/formula/ptg/TestPercentPtg.java | 16 +- .../poi/ss/formula/ptg/TestRangePtg.java | 8 +- .../poi/ss/formula/ptg/TestRef3DPtg.java | 4 +- .../poi/ss/formula/ptg/TestReferencePtg.java | 57 +- .../poi/ss/formula/ptg/TestUnionPtg.java | 8 +- .../poi/ss/formula/udf/BaseTestUDFFinder.java | 6 +- .../formula/udf/TestAggregatingUDFFinder.java | 2 +- .../ss/formula/udf/TestDefaultUDFFinder.java | 2 +- .../poi/ss/usermodel/BaseTestBorderStyle.java | 16 +- .../ss/usermodel/BaseTestBugzillaIssues.java | 341 +- .../apache/poi/ss/usermodel/BaseTestCell.java | 184 +- .../poi/ss/usermodel/BaseTestCellComment.java | 99 +- .../poi/ss/usermodel/BaseTestCloneSheet.java | 32 +- .../ss/usermodel/BaseTestColumnShifting.java | 24 +- .../BaseTestConditionalFormatting.java | 139 +- .../poi/ss/usermodel/BaseTestDataFormat.java | 20 +- .../ss/usermodel/BaseTestDataValidation.java | 4 +- .../apache/poi/ss/usermodel/BaseTestFont.java | 16 +- .../usermodel/BaseTestFormulaEvaluator.java | 45 +- .../poi/ss/usermodel/BaseTestHyperlink.java | 8 +- .../poi/ss/usermodel/BaseTestNamedRange.java | 466 +- .../poi/ss/usermodel/BaseTestPicture.java | 24 +- .../poi/ss/usermodel/BaseTestRangeCopier.java | 12 +- .../apache/poi/ss/usermodel/BaseTestRow.java | 205 +- .../poi/ss/usermodel/BaseTestSheet.java | 116 +- .../BaseTestSheetAutosizeColumn.java | 14 +- .../poi/ss/usermodel/BaseTestSheetHiding.java | 85 +- .../usermodel/BaseTestSheetShiftColumns.java | 34 +- .../ss/usermodel/BaseTestSheetShiftRows.java | 48 +- .../BaseTestSheetUpdateArrayFormulas.java | 153 +- .../poi/ss/usermodel/BaseTestWorkbook.java | 90 +- .../usermodel/BaseTestXEvaluationSheet.java | 6 +- .../poi/ss/usermodel/TestDataFormatter.java | 111 +- .../apache/poi/ss/usermodel/TestDateUtil.java | 165 +- .../TestExcelStyleDateFormatter.java | 14 +- .../poi/ss/usermodel/TestFractionFormat.java | 18 +- .../poi/ss/usermodel/TestIndexedColors.java | 18 +- .../apache/poi/ss/util/AllSSUtilTests.java | 41 - .../apache/poi/ss/util/BaseTestCellUtil.java | 387 +- .../apache/poi/ss/util/TestAreaReference.java | 15 +- .../apache/poi/ss/util/TestCellAddress.java | 25 +- .../poi/ss/util/TestCellRangeAddress.java | 123 +- .../apache/poi/ss/util/TestCellRangeUtil.java | 15 +- .../apache/poi/ss/util/TestCellReference.java | 166 +- .../poi/ss/util/TestDateFormatConverter.java | 20 +- .../apache/poi/ss/util/TestDateParser.java | 61 +- .../poi/ss/util/TestExpandedDouble.java | 16 +- .../poi/ss/util/TestNumberComparer.java | 13 +- .../ss/util/TestNumberToTextConverter.java | 6 +- .../poi/ss/util/TestPropertyTemplate.java | 30 +- .../apache/poi/ss/util/TestRegionUtil.java | 24 +- .../apache/poi/ss/util/TestSheetBuilder.java | 8 +- .../org/apache/poi/ss/util/TestSheetUtil.java | 203 +- .../apache/poi/ss/util/TestWorkbookUtil.java | 4 +- .../poi/ss/util/cellwalk/TestCellWalk.java | 4 +- .../org/apache/poi/util/AllPOIUtilTests.java | 43 - .../apache/poi/util/MemoryLeakVerifier.java | 7 +- .../org/apache/poi/util/TestArrayUtil.java | 22 +- .../org/apache/poi/util/TestBitField.java | 8 +- .../org/apache/poi/util/TestByteField.java | 18 +- .../org/apache/poi/util/TestHexDump.java | 82 +- .../org/apache/poi/util/TestIOUtils.java | 113 +- .../org/apache/poi/util/TestIntList.java | 287 +- .../org/apache/poi/util/TestIntegerField.java | 82 +- .../org/apache/poi/util/TestLittleEndian.java | 54 +- .../poi/util/TestLittleEndianStreams.java | 16 +- .../org/apache/poi/util/TestLocaleUtil.java | 20 +- .../org/apache/poi/util/TestLongField.java | 96 +- .../apache/poi/util/TestPOILogFactory.java | 2 +- .../org/apache/poi/util/TestPOILogger.java | 20 +- .../util/TestRLEDecompressingInputStream.java | 54 +- .../org/apache/poi/util/TestShortField.java | 72 +- .../util/TestStringCodepointsIterable.java | 9 +- .../org/apache/poi/util/TestStringUtil.java | 113 +- .../org/apache/poi/util/TestTempFile.java | 60 +- .../org/apache/poi/util/TestXMLHelper.java | 18 +- 1010 files changed, 16265 insertions(+), 20726 deletions(-) create mode 100644 src/excelant/poi-ant-contrib/Junit5Progress.java delete mode 100644 src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java delete mode 100644 src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/AllPOIFSCryptoTests.java delete mode 100644 src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java delete mode 100644 src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java delete mode 100644 src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hslf/model/AllHSLFModelTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hslf/usermodel/AllHSLFUserModelTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hsmf/AllHSMFTests.java delete mode 100644 src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java delete mode 100644 src/testcases/org/apache/poi/AllPOITests.java delete mode 100644 src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java delete mode 100644 src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/HSSFTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/model/AllModelTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/AllRecordTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/record/pivot/AllPivotRecordTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java delete mode 100644 src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.java delete mode 100644 src/testcases/org/apache/poi/poifs/AllPOIFSTests.java delete mode 100644 src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java delete mode 100644 src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java delete mode 100644 src/testcases/org/apache/poi/poifs/property/AllPOIFSPropertyTests.java delete mode 100644 src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java delete mode 100644 src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java delete mode 100644 src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java delete mode 100644 src/testcases/org/apache/poi/util/AllPOIUtilTests.java diff --git a/build.xml b/build.xml index 4a9f81773a..b1f01b3fdd 100644 --- a/build.xml +++ b/build.xml @@ -96,7 +96,7 @@ under the License. - + @@ -271,7 +271,16 @@ under the License. - + + + + + + + + + + @@ -409,7 +418,14 @@ under the License. - + + + + + + + + @@ -507,9 +523,9 @@ under the License. - - - + + + @@ -611,6 +627,7 @@ under the License. + @@ -640,7 +657,14 @@ under the License. - + + + + + + + + @@ -679,7 +703,14 @@ under the License. - + + + + + + + + @@ -1147,6 +1178,9 @@ under the License. + + + @@ -1166,6 +1200,23 @@ under the License. + + + + + + + + + + + + + + + + @@ -1179,32 +1230,64 @@ under the License. - - - - - - + + + + + + + + - - - - - + - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + @@ -1222,20 +1305,16 @@ under the License. - - - - - - - - - - - - - + + + + + + + + + @@ -1461,19 +1540,15 @@ under the License. - - - - - - - - - - - - + modulepath-ref="test-main.modules" module1="poi" outputDir="${main.reports.test}"> + + + + + + + + @@ -1521,17 +1596,13 @@ under the License. - - - - - - - - - - + modulepath-ref="test-scratchpad.modules" module1="scratchpad" outputDir="${scratchpad.reports.test}"> + + + + + + @@ -1554,19 +1625,14 @@ under the License. - - - - - - - - - - - - + modulepath-ref="@{modulepath-ref}" module1="ooxml" module2="scratchpad" outputDir="${ooxml.reports.test}"> + + + + + + + @@ -1622,16 +1688,12 @@ under the License. - - - - - - - - - + modulepath-ref="test-integration.modules" module1="stress" outputDir="${integration.reports.test}"> + + + + + @@ -1810,16 +1872,12 @@ org/apache/poi/schemas/ooxml/system/ooxml/rectaf36doctype.xsb - - - - - - - - - + modulepath-ref="test-excelant.modules" module1="excelant" outputDir="${excelant.reports.test}"> + + + + + @@ -2521,7 +2579,14 @@ org/apache/poi/schemas/ooxml/system/ooxml/rectaf36doctype.xsb - + + + + + + + + diff --git a/sonar/integration-test/pom.xml b/sonar/integration-test/pom.xml index bfa37a2028..df77176341 100644 --- a/sonar/integration-test/pom.xml +++ b/sonar/integration-test/pom.xml @@ -96,12 +96,6 @@ ${project.version} - - junit - junit - ${junit.version} - test - org.reflections reflections diff --git a/sonar/ooxml/pom.xml b/sonar/ooxml/pom.xml index 966b3becba..bc8a04de38 100644 --- a/sonar/ooxml/pom.xml +++ b/sonar/ooxml/pom.xml @@ -150,12 +150,6 @@ 1.06 - - junit - junit - ${junit.version} - test - org.reflections reflections diff --git a/sonar/pom.xml b/sonar/pom.xml index 1c0ecea23b..3ae96c2475 100644 --- a/sonar/pom.xml +++ b/sonar/pom.xml @@ -80,7 +80,7 @@ 4.0.0 - 4.13.1 + 5.7.0 2.8.0 3.6.0 3.2.0 @@ -110,13 +110,6 @@ org.apache.maven.plugins maven-surefire-plugin ${maven.plugin.surefire.version} - - - org.apache.maven.surefire - surefire-junit47 - ${maven.plugin.surefire.version} - - false @@ -164,8 +157,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter ${junit.version} test @@ -181,6 +174,12 @@ ${mockito.version} test + + org.hamcrest + hamcrest + 2.2 + test + diff --git a/src/excelant/poi-ant-contrib/Junit5Progress.java b/src/excelant/poi-ant-contrib/Junit5Progress.java new file mode 100644 index 0000000000..afe51c42f0 --- /dev/null +++ b/src/excelant/poi-ant-contrib/Junit5Progress.java @@ -0,0 +1,114 @@ +/* ==================================================================== +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==================================================================== */ + +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.time.Instant; + +import org.junit.platform.engine.TestDescriptor.Type; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.TestExecutionResult.Status; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.TestPlan; + +/** + * Custom listener class for Ants junitlauncher, because it chomps the important running details + * + * @see ant and junit 5 – outputting test duration and failure to the log + **/ +public class Junit5Progress implements TestExecutionListener { + + private StringWriter inMemoryWriter = new StringWriter(); + + private int numSkippedInCurrentClass; + private int numAbortedInCurrentClass; + private int numSucceededInCurrentClass; + private int numFailedInCurrentClass; + private Instant startCurrentClass; + + private void resetCountsForNewClass() { + numSkippedInCurrentClass = 0; + numAbortedInCurrentClass = 0; + numSucceededInCurrentClass = 0; + numFailedInCurrentClass = 0; + startCurrentClass = Instant.now(); + } + + @Override + public void executionStarted(TestIdentifier testIdentifier) { + if ("[engine:junit-jupiter]".equals(testIdentifier.getParentId().orElse(""))) { + println("Ran " + testIdentifier.getLegacyReportingName()); + resetCountsForNewClass(); + } + } + + @Override + public void executionSkipped(TestIdentifier testIdentifier, String reason) { + numSkippedInCurrentClass++; + } + + @Override + public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { + if ("[engine:junit-jupiter]".equals(testIdentifier.getParentId().orElse(""))) { + int totalTestsInClass = numSucceededInCurrentClass + numAbortedInCurrentClass + + numFailedInCurrentClass + numSkippedInCurrentClass; + Duration duration = Duration.between(startCurrentClass, Instant.now()); + double numSeconds = duration.toNanos() / (double) 1_000_000_000; + String output = String.format("Tests run: %d, Failures: %d, Aborted: %d, Skipped: %d, Time elapsed: %f sec", + totalTestsInClass, numFailedInCurrentClass, numAbortedInCurrentClass, + numSkippedInCurrentClass, numSeconds); + println(output); + + } + // don't count containers since looking for legacy JUnit 4 counting style + if (testIdentifier.getType() == Type.TEST) { + if (testExecutionResult.getStatus() == Status.SUCCESSFUL) { + numSucceededInCurrentClass++; + } else if (testExecutionResult.getStatus() == Status.ABORTED) { + println(" ABORTED: " + testIdentifier.getDisplayName()); + numAbortedInCurrentClass++; + } else if (testExecutionResult.getStatus() == Status.FAILED) { + println(" FAILED: " + testIdentifier.getDisplayName()); + numFailedInCurrentClass++; + } + } + } + + private void println(String str) { + inMemoryWriter.write(str + "\n"); + } + + /* + * Append to file on disk since listener can't write to System.out (becuase legacy listeners enabled) + */ + private void flushToDisk() { + try (FileWriter writer = new FileWriter("build/status-as-tests-run.txt", true)) { + writer.write(inMemoryWriter.toString()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public void testPlanExecutionFinished(TestPlan testPlan) { + flushToDisk(); + } +} \ No newline at end of file diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java b/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java index cf4d8d7c0c..d6a3a74b7d 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java @@ -17,15 +17,15 @@ */ package org.apache.poi.ss.excelant; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.ss.usermodel.Workbook; public class MockExcelAntWorkbookHandler implements IExcelAntWorkbookHandler { public static boolean executed; public static Workbook workbook; - - + + @Override public void setWorkbook(Workbook workbook) { MockExcelAntWorkbookHandler.workbook = workbook; diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java index 49f804b4fa..9b3dbdfce9 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java @@ -20,9 +20,9 @@ package org.apache.poi.ss.excelant; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.PrintStream; @@ -30,13 +30,12 @@ import java.io.PrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.NullPrintStream; import org.apache.tools.ant.BuildEvent; -import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * JUnit test for the ExcelAnt tasks. @@ -48,10 +47,9 @@ public class TestBuildFile { private StringBuilder logBuffer; private StringBuilder fullLogBuffer; - private BuildException buildException; - @Before + @BeforeEach public void setUp() { String filename = TestBuildFile.getDataDir() + "/../src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml"; int logLevel = Project.MSG_DEBUG; @@ -77,7 +75,7 @@ public class TestBuildFile { * is automatically called, since it's trivial to have a * test target depend on it. */ - @After + @AfterEach public void tearDown() { if (project == null) { /* @@ -145,7 +143,6 @@ public class TestBuildFile { System.setErr(new NullPrintStream()); logBuffer = new StringBuilder(); fullLogBuffer = new StringBuilder(); - buildException = null; project.executeTarget(targetName); } finally { System.setOut(sysOut); @@ -166,12 +163,9 @@ public class TestBuildFile { try { executeTarget(target); } catch (org.apache.tools.ant.BuildException ex) { - buildException = ex; - if ((null != msg) && (!ex.getMessage().equals(msg))) { - fail("Should throw BuildException because '" + cause - + "' with message '" + msg - + "' (actual message '" + ex.getMessage() + "' instead)"); - } + assertTrue(msg == null || ex.getMessage().equals(msg), + "Should throw BuildException because '" + cause + "' with message '" + msg + "' (actual message '" + ex.getMessage() + "' instead)" + ); return; } fail("Should throw BuildException because: " + cause); @@ -182,27 +176,11 @@ public class TestBuildFile { return dataDirName == null ? "test-data" : dataDirName; } - /** - * an output stream which saves stuff to our buffer. - */ - protected static class AntOutputStream extends java.io.OutputStream { - private StringBuilder buffer; - - public AntOutputStream(StringBuilder buffer) { - this.buffer = buffer; - } - - @Override - public void write(int b) { - buffer.append((char) b); - } - } - /** * Our own personal build listener. */ private class AntTestListener implements BuildListener { - private int logLevel; + private final int logLevel; /** * Constructs a test listener which will ignore log events @@ -378,8 +356,8 @@ public class TestBuildFile { assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls"); assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4."); - assertNotNull("The workbook should have been passed to the handler", MockExcelAntWorkbookHandler.workbook); - assertTrue("The handler should have been executed", MockExcelAntWorkbookHandler.executed); + assertNotNull(MockExcelAntWorkbookHandler.workbook, "The workbook should have been passed to the handler"); + assertTrue(MockExcelAntWorkbookHandler.executed, "The handler should have been executed"); } @Test diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java index d815bcf161..9c73d0f5f2 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java @@ -16,23 +16,23 @@ ==================================================================== */ package org.apache.poi.ss.excelant; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestExcelAntPrecision { private ExcelAntPrecision fixture ; - @Before + @BeforeEach public void setUp() { fixture = new ExcelAntPrecision() ; } - @After + @AfterEach public void tearDown() { fixture = null ; } diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java index abf3a799ed..a192543859 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.ss.excelant; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestExcelAntSet { @@ -35,12 +35,12 @@ public class TestExcelAntSet { private static final String mortgageCalculatorFileName = TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - @Before + @BeforeEach public void setUp() { fixture = new ExcelAntSetDoubleCell() ; } - @After + @AfterEach public void tearDown() { fixture = null ; } diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java index be30f7a64e..a2744620bf 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.ss.excelant; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestExcelAntSetDoubleCell { @@ -34,14 +34,14 @@ public class TestExcelAntSetDoubleCell { private static final String mortgageCalculatorFileName = TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - @Before + @BeforeEach public void setUp() { fixture = new ExcelAntSetDoubleCell() ; util = ExcelAntWorkbookUtilFactory.getInstance(mortgageCalculatorFileName ) ; fixture.setWorkbookUtil( util ) ; } - @After + @AfterEach public void tearDown() { fixture = null ; } diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntUserDefinedFunction.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntUserDefinedFunction.java index 73b10806ab..30dbb159c0 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntUserDefinedFunction.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntUserDefinedFunction.java @@ -16,17 +16,17 @@ ==================================================================== */ package org.apache.poi.ss.excelant; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestExcelAntUserDefinedFunction { private ExcelAntUserDefinedFunctionTestHelper fixture ; - @Before + @BeforeEach public void setUp() { fixture = new ExcelAntUserDefinedFunctionTestHelper() ; } diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java index 7112f6acad..096792ff73 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java @@ -16,57 +16,57 @@ ==================================================================== */ package org.apache.poi.ss.excelant.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestExcelAntEvaluationResult { private ExcelAntEvaluationResult fixture; - + private boolean completedWithError; private boolean passed; - private double retValue = 1.1; - private String errMessage = "error message"; - private double delta = 2.2; + private double retValue = 1.1; + private String errMessage = "error message"; + private double delta = 2.2; private String cellId = "testCell!$F$1"; - - @Before + + @BeforeEach public void setUp() { fixture = new ExcelAntEvaluationResult(completedWithError, - passed, + passed, retValue, - errMessage, + errMessage, delta, cellId); } - - @After + + @AfterEach public void tearDown() { fixture = null; } - + @Test public void testCompletedWithErrorMessage() { String errMsg = fixture.getErrorMessage(); assertNotNull(errMsg); assertEquals(errMsg, errMessage); } - + @Test public void testPassed() { boolean passedValue = fixture.didTestPass(); assertEquals(passedValue, passed); } - + @Test public void testDelta() { double deltaValue = fixture.getDelta(); assertEquals(deltaValue, delta, 0.0); } - + @Test public void testCellId() { String cellIdValue = fixture.getCellName(); diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java index b6c7df7a29..10f5c8e9c1 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.ss.excelant.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.File; import java.io.FileInputStream; @@ -37,8 +37,8 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.tools.ant.BuildException; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class TestExcelAntWorkbookUtil { @@ -48,7 +48,7 @@ public class TestExcelAntWorkbookUtil { private ExcelAntWorkbookUtilTestHelper fixture ; - @After + @AfterEach public void tearDown() { fixture = null ; } @@ -62,12 +62,8 @@ public class TestExcelAntWorkbookUtil { @Test public void testLoadNotExistingFile() { - try { - new ExcelAntWorkbookUtilTestHelper("notexistingFile"); - fail("Should catch exception here"); - } catch (BuildException e) { - assertTrue(e.getMessage().contains("notexistingFile")); - } + BuildException e = assertThrows(BuildException.class, () -> new ExcelAntWorkbookUtilTestHelper("notexistingFile")); + assertTrue(e.getMessage().contains("notexistingFile")); } @Test @@ -215,9 +211,9 @@ public class TestExcelAntWorkbookUtil { precision); //System.out.println(result); - assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=false")); - assertTrue("Had:" + result, result.toString().contains("returnValue=790.79")); - assertTrue("Had:" + result, result.toString().contains("cellName='MortgageCalculator'!B4")); + assertTrue( result.toString().contains("evaluationCompletedWithError=false"), "Had:" + result ); + assertTrue( result.toString().contains("returnValue=790.79"), "Had:" + result ); + assertTrue( result.toString().contains("cellName='MortgageCalculator'!B4"), "Had:" + result ); assertFalse(result.toString().contains("#N/A")); assertFalse(result.evaluationCompleteWithError()); @@ -238,10 +234,10 @@ public class TestExcelAntWorkbookUtil { precision); //System.out.println(result); - assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=false")); - assertTrue("Had:" + result, result.toString().contains("returnValue=790.79")); - assertTrue("Had:" + result, result.toString().contains("cellName='MortgageCalculator'!B4")); - assertFalse("Should not see an error, but had:" + result, result.toString().contains("#")); + assertTrue( result.toString().contains("evaluationCompletedWithError=false"), "Had:" + result ); + assertTrue( result.toString().contains("returnValue=790.79"), "Had:" + result ); + assertTrue( result.toString().contains("cellName='MortgageCalculator'!B4"), "Had:" + result ); + assertFalse( result.toString().contains("#"), "Should not see an error, but had:" + result ); assertFalse(result.evaluationCompleteWithError()); assertFalse(result.didTestPass()); @@ -261,10 +257,10 @@ public class TestExcelAntWorkbookUtil { precision); System.out.println(result); - assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=true")); - assertTrue("Had:" + result, result.toString().contains("returnValue=0.0")); - assertTrue("Had:" + result, result.toString().contains("cellName='ErrorCell'!A1")); - assertTrue("Had:" + result, result.toString().contains("#N/A")); + assertTrue( result.toString().contains("evaluationCompletedWithError=true"), "Had:" + result ); + assertTrue( result.toString().contains("returnValue=0.0"), "Had:" + result ); + assertTrue( result.toString().contains("cellName='ErrorCell'!A1"), "Had:" + result ); + assertTrue( result.toString().contains("#N/A"), "Had:" + result ); assertTrue(result.evaluationCompleteWithError()); assertFalse(result.didTestPass()); @@ -301,14 +297,9 @@ public class TestExcelAntWorkbookUtil { public void testSetNotExistingSheet() { String cell = "'NotexistingSheet'!C14" ; - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - try { - fixture.setStringValue(cell, "some"); - fail("Should catch exception here"); - } catch (BuildException e) { - assertTrue(e.getMessage().contains("NotexistingSheet")); - } + fixture = new ExcelAntWorkbookUtilTestHelper(mortgageCalculatorFileName); + BuildException e = assertThrows(BuildException.class, () -> fixture.setStringValue(cell, "some")); + assertTrue(e.getMessage().contains("NotexistingSheet")); } @Test diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java index 360334cbe1..d6129e7609 100644 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java +++ b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.ss.excelant.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.ss.excelant.TestBuildFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** diff --git a/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java b/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java index d5a019c448..2d14a7c3eb 100644 --- a/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java @@ -16,10 +16,10 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assume.assumeFalse; +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.Assumptions.assumeFalse; import java.io.File; import java.io.FileInputStream; @@ -90,20 +90,20 @@ public abstract class AbstractFileHandler implements FileHandler { String fileAndParentName = file.getParentFile().getName() + "/" + file.getName(); try { extractor = ExtractorFactory.createExtractor(file); - assertNotNull("Should get a POITextExtractor but had none for file " + file, extractor); + assertNotNull(extractor, "Should get a POITextExtractor but had none for file " + file); - assertNotNull("Should get some text but had none for file " + file, extractor.getText()); + assertNotNull(extractor.getText(), "Should get some text but had none for file " + file); // also try metadata @SuppressWarnings("resource") POITextExtractor metadataExtractor = extractor.getMetadataTextExtractor(); assertNotNull(metadataExtractor.getText()); - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName)); + assertFalse(EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName), + "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!"); - assertEquals("File should not be modified by extractor", length, file.length()); - assertEquals("File should not be modified by extractor", modified, file.lastModified()); + assertEquals(length, file.length(), "File should not be modified by extractor"); + assertEquals(modified, file.lastModified(), "File should not be modified by extractor"); handleExtractingAsStream(file); diff --git a/src/integrationtest/org/apache/poi/stress/BaseIntegrationTest.java b/src/integrationtest/org/apache/poi/stress/BaseIntegrationTest.java index 8abe9fcff0..617355ec47 100644 --- a/src/integrationtest/org/apache/poi/stress/BaseIntegrationTest.java +++ b/src/integrationtest/org/apache/poi/stress/BaseIntegrationTest.java @@ -16,7 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.BufferedInputStream; import java.io.File; @@ -28,7 +29,6 @@ import java.util.zip.ZipException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.OldFileFormatException; import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.junit.Assume; /** * This class is used for mass-regression testing via a @@ -49,7 +49,7 @@ public class BaseIntegrationTest { } public void test() throws Exception { - assertNotNull("Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file), handler); + assertNotNull( handler, "Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file) ); testOneFile(new File(rootDir, file)); } @@ -61,14 +61,14 @@ public class BaseIntegrationTest { handleWrongOLE2XMLExtension(inputFile, e); } catch (OldFileFormatException e) { // Not even text extraction is supported for these: handler.handleExtracting(inputFile); - Assume.assumeFalse("File " + file + " excluded because it is unsupported old Excel format", true); + assumeFalse( true, "File " + file + " excluded because it is unsupported old Excel format" ); } catch (EncryptedDocumentException e) { // Do not try to read encrypted files - Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true); + assumeFalse( true, "File " + file + " excluded because it is password-encrypted" ); } catch (ZipException e) { // some files are corrupted if (e.getMessage().equals("unexpected EOF") || e.getMessage().equals("Truncated ZIP file")) { - Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true); + assumeFalse( true, "File " + file + " excluded because the Zip file is incomplete" ); } throw e; @@ -76,7 +76,7 @@ public class BaseIntegrationTest { // ignore some other ways of corrupted files String message = e.getMessage(); if(message != null && message.contains("Truncated ZIP file")) { - Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true); + assumeFalse( true, "File " + file + " excluded because the Zip file is incomplete" ); } // sometimes binary format has XML-format-extension... @@ -92,7 +92,7 @@ public class BaseIntegrationTest { if(message != null && (message.equals("The document is really a RTF file") || message.equals("The document is really a PDF file") || message.equals("The document is really a HTML file"))) { - Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file", true); + assumeFalse( true, "File " + file + " excluded because it is actually a PDF/RTF/HTML file" ); } if(message != null && message.equals("The document is really a OOXML file")) { @@ -107,7 +107,7 @@ public class BaseIntegrationTest { handler.handleExtracting(inputFile); } catch (EncryptedDocumentException e) { // Do not try to read encrypted files - Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true); + assumeFalse( true, "File " + file + " excluded because it is password-encrypted" ); } } @@ -117,10 +117,9 @@ public class BaseIntegrationTest { String message = e.getMessage(); // ignore some file-types that we do not want to handle here - Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file", - message != null && (message.equals("The document is really a RTF file") || + assumeFalse( message != null && (message.equals("The document is really a RTF file") || message.equals("The document is really a PDF file") || - message.equals("The document is really a HTML file"))); + message.equals("The document is really a HTML file")), "File " + file + " excluded because it is actually a PDF/RTF/HTML file" ); if(message != null && (message.equals("The document is really a XLS file"))) { handler = TestAllFiles.HANDLERS.get(".xls"); diff --git a/src/integrationtest/org/apache/poi/stress/FileHandler.java b/src/integrationtest/org/apache/poi/stress/FileHandler.java index aef3878afa..62e5d81ced 100644 --- a/src/integrationtest/org/apache/poi/stress/FileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/FileHandler.java @@ -20,7 +20,7 @@ import java.io.File; import java.io.InputStream; /** - * Base interface for the various file types that are + * Base interface for the various file types that are * used in the stress testing. */ public interface FileHandler { @@ -28,7 +28,7 @@ public interface FileHandler { * The FileHandler receives a stream ready for reading the * file and should handle the content that is provided and * try to read and interpret the data. - * + * * Closing is handled by the framework outside this call. * * @param stream The input stream to read the file from. @@ -36,10 +36,10 @@ public interface FileHandler { * @throws Exception If an error happens in the file-specific handler */ void handleFile(InputStream stream, String path) throws Exception; - + /** * Ensures that extracting text from the given file - * is returning some text. + * is returning some text. */ void handleExtracting(File file) throws Exception; diff --git a/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java index 5482949e52..8fb6c65827 100644 --- a/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileInputStream; @@ -29,7 +29,7 @@ import org.apache.poi.hdgf.extractor.VisioTextExtractor; import org.apache.poi.hdgf.streams.Stream; import org.apache.poi.hdgf.streams.TrailerStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HDGFFileHandler extends POIFSFileHandler { @Override @@ -41,16 +41,16 @@ public class HDGFFileHandler extends POIFSFileHandler { for(Stream str : topLevelStreams) { assertTrue(str.getPointer().getLength() >= 0); } - + TrailerStream trailerStream = diagram.getTrailerStream(); assertNotNull(trailerStream); assertTrue(trailerStream.getPointer().getLength() >= 0); diagram.close(); poifs.close(); - + // writing is not yet implemented... handlePOIDocument(diagram); } - + // a test-case to test this locally without executing the full TestAllFiles @Override @Test @@ -63,9 +63,9 @@ public class HDGFFileHandler extends POIFSFileHandler { } finally { stream.close(); } - + handleExtracting(file); - + stream = new FileInputStream(file); try { try (VisioTextExtractor extractor = new VisioTextExtractor(stream)) { diff --git a/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java index f48775cf21..91071adc23 100644 --- a/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -30,7 +30,7 @@ import org.apache.poi.hmef.attribute.TNEFProperty; import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.poifs.filesystem.FileMagic; import org.apache.poi.util.LittleEndian; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HMEFFileHandler extends AbstractFileHandler { @@ -58,8 +58,8 @@ public class HMEFFileHandler extends AbstractFileHandler { } else { bodyStr = msg.getBody(); } - assertNotNull("Body is not set", bodyStr); - assertNotNull("Subject is not set", msg.getSubject()); + assertNotNull( bodyStr, "Body is not set" ); + assertNotNull( msg.getSubject(), "Subject is not set" ); } // a test-case to test this locally without executing the full TestAllFiles diff --git a/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java index 3fc03b0bc2..a1152d58d4 100644 --- a/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -25,7 +25,7 @@ import java.io.InputStream; import org.apache.poi.hpbf.HPBFDocument; import org.apache.poi.hpbf.extractor.PublisherTextExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HPBFFileHandler extends POIFSFileHandler { @Override @@ -34,11 +34,11 @@ public class HPBFFileHandler extends POIFSFileHandler { assertNotNull(pub.getEscherDelayStm()); assertNotNull(pub.getMainContents()); assertNotNull(pub.getQuillContents()); - + // writing is not yet implemented... handlePOIDocument(pub); pub.close(); } - + // a test-case to test this locally without executing the full TestAllFiles @Override @Test @@ -51,9 +51,9 @@ public class HPBFFileHandler extends POIFSFileHandler { } finally { stream.close(); } - + handleExtracting(file); - + stream = new FileInputStream(file); try { try (PublisherTextExtractor extractor = new PublisherTextExtractor(stream)) { @@ -63,5 +63,5 @@ public class HPBFFileHandler extends POIFSFileHandler { stream.close(); } } - + } diff --git a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java index d01b0a3cba..b9c99c013f 100644 --- a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java @@ -16,7 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.ByteArrayOutputStream; import java.io.File; @@ -39,8 +40,7 @@ import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.TempFile; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HPSFFileHandler extends POIFSFileHandler { private static final String NL = System.getProperty("line.separator"); @@ -70,7 +70,7 @@ public class HPSFFileHandler extends POIFSFileHandler { @Override public void handleFile(InputStream stream, String path) throws Exception { - Assume.assumeFalse(EXCLUDES_HANDLE_FILE.contains(path)); + assumeFalse(EXCLUDES_HANDLE_FILE.contains(path)); POIFSFileSystem poifs = new POIFSFileSystem(stream); HPSFPropertiesOnlyDocument hpsf = new HPSFPropertiesOnlyDocument(poifs); DocumentSummaryInformation dsi = hpsf.getDocumentSummaryInformation(); @@ -96,7 +96,7 @@ public class HPSFFileHandler extends POIFSFileHandler { @Override public void handleAdditional(File file) throws Exception { - Assume.assumeFalse(EXCLUDES_HANDLE_ADD.contains(file.getParentFile().getName()+"/"+file.getName())); + assumeFalse(EXCLUDES_HANDLE_ADD.contains(file.getParentFile().getName()+"/"+file.getName())); if (copyOutput == null) { copyOutput = TempFile.createTempFile("hpsfCopy", "out"); copyOutput.deleteOnExit(); diff --git a/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java index 09025f4b3e..a4ae15b090 100644 --- a/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java @@ -16,16 +16,18 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.util.POILogger; import org.apache.poi.util.SystemOutLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HSLFFileHandler extends SlideShowHandler { @Override @@ -38,16 +40,16 @@ public class HSLFFileHandler extends SlideShowHandler { org.apache.poi.hslf.record.Record[] records = slide.getRecords(); assertNotNull(records); for(org.apache.poi.hslf.record.Record record : records) { - assertNotNull("Found a record which was null", record); + assertNotNull( record, "Found a record which was null" ); assertTrue(record.getRecordType() >= 0); } - + handlePOIDocument(slide); - + HSLFSlideShow ss = new HSLFSlideShow(slide); handleSlideShow(ss); } - + @Test public void testOne() throws Exception { testOneFile(new File("test-data/slideshow/54880_chinese.ppt")); diff --git a/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java index 212904308b..9fa3160cda 100644 --- a/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -25,7 +25,7 @@ import java.io.InputStream; import org.apache.poi.hsmf.MAPIMessage; import org.apache.poi.hsmf.datatypes.AttachmentChunks; import org.apache.poi.hsmf.datatypes.DirectoryChunk; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HSMFFileHandler extends POIFSFileHandler { @Override @@ -52,18 +52,18 @@ public class HSMFFileHandler extends POIFSFileHandler { // write out the file File file = TempFile.createTempFile("StressTest", ".msg"); writeToFile(mapi, file); - + MAPIMessage read = new MAPIMessage(file.getAbsolutePath()); assertNotNull(read.getAttachmentFiles()); assertNotNull(read.getDisplayBCC()); assertNotNull(read.getMessageDate()); */ - + // writing is not yet supported... handlePOIDocument(mapi); - + mapi.close(); } - + // private void writeToFile(MAPIMessage mapi, File file) // throws FileNotFoundException, IOException { // OutputStream stream = new FileOutputStream(file); @@ -82,7 +82,7 @@ public class HSMFFileHandler extends POIFSFileHandler { try (InputStream stream = new FileInputStream(file)) { handleFile(stream, file.getPath()); } - + handleExtracting(file); } } \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java index d4299776cc..f2b56880e7 100644 --- a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -34,7 +34,7 @@ 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.util.NullPrintStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HSSFFileHandler extends SpreadsheetHandler { private final POIFSFileHandler delegate = new POIFSFileHandler(); @@ -92,8 +92,7 @@ public class HSSFFileHandler extends SpreadsheetHandler { BiffViewer.main(new String[]{file.getAbsolutePath()}); - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent)); + assertFalse( EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent), "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!" ); } catch (OldExcelFormatException e) { // old excel formats are not supported here } catch (RuntimeException e) { diff --git a/src/integrationtest/org/apache/poi/stress/HSSFRecordsStresser.java b/src/integrationtest/org/apache/poi/stress/HSSFRecordsStresser.java index 9417ee7e61..24b30e8abd 100644 --- a/src/integrationtest/org/apache/poi/stress/HSSFRecordsStresser.java +++ b/src/integrationtest/org/apache/poi/stress/HSSFRecordsStresser.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.FileInputStream; import java.io.InputStream; @@ -27,7 +27,7 @@ import java.util.List; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Needs to be implemented in this package to have access to @@ -50,14 +50,12 @@ public class HSSFRecordsStresser { try { Record newRecord = record.copy(); - assertEquals("Expecting the same class back from clone(), but had Record of type " + record.getClass() + " and got back a " + newRecord.getClass() + " from clone()", - record.getClass(), newRecord.getClass()); + assertEquals( record.getClass(), newRecord.getClass(), "Expecting the same class back from clone(), but had Record of type " + record.getClass() + " and got back a " + newRecord.getClass() + " from clone()" ); byte[] origBytes = record.serialize(); byte[] newBytes = newRecord.serialize(); - assertArrayEquals("Record of type " + record.getClass() + " should return the same byte array via the clone() method, but did return a different array", - origBytes, newBytes); + assertArrayEquals( origBytes, newBytes, "Record of type " + record.getClass() + " should return the same byte array via the clone() method, but did return a different array" ); } catch (RuntimeException e) { // some Records do not implement clone, ignore those for now assertTrue(e.getMessage().contains("needs to define a clone method")); diff --git a/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java index cc10106d9e..a7180af75d 100644 --- a/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -27,7 +27,7 @@ import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.hwpf.model.PicturesTable; import org.apache.poi.hwpf.usermodel.Picture; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HWPFFileHandler extends POIFSFileHandler { @Override diff --git a/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java b/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java index 59c352c129..7746a37f49 100644 --- a/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileInputStream; @@ -28,7 +28,7 @@ import org.apache.poi.openxml4j.opc.ContentTypes; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class OPCFileHandler extends AbstractFileHandler { @Override @@ -43,11 +43,10 @@ public class OPCFileHandler extends AbstractFileHandler { assertEquals(ContentTypes.CORE_PROPERTIES_PART, part.getContentType()); } if (part.getPartName().toString().equals("/word/document.xml")) { - assertTrue("Expected one of " + XWPFRelation.MACRO_DOCUMENT + ", " + XWPFRelation.DOCUMENT + ", " + XWPFRelation.TEMPLATE + - ", but had " + part.getContentType(), - XWPFRelation.DOCUMENT.getContentType().equals(part.getContentType()) || + assertTrue( XWPFRelation.DOCUMENT.getContentType().equals(part.getContentType()) || XWPFRelation.MACRO_DOCUMENT.getContentType().equals(part.getContentType()) || - XWPFRelation.TEMPLATE.getContentType().equals(part.getContentType())); + XWPFRelation.TEMPLATE.getContentType().equals(part.getContentType()), "Expected one of " + XWPFRelation.MACRO_DOCUMENT + ", " + XWPFRelation.DOCUMENT + ", " + XWPFRelation.TEMPLATE + + ", but had " + part.getContentType() ); } if (part.getPartName().toString().equals("/word/theme/theme1.xml")) { assertEquals(XWPFRelation.THEME.getContentType(), part.getContentType()); diff --git a/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java b/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java index 09460cd76f..99843096cd 100644 --- a/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -28,7 +28,7 @@ import java.io.InputStream; import org.apache.poi.POIDocument; import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class POIFSFileHandler extends AbstractFileHandler { @@ -56,17 +56,17 @@ public class POIFSFileHandler extends AbstractFileHandler { assertNotNull(fs); assertNotNull(fs.getRoot()); } - + protected void handlePOIDocument(POIDocument doc) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); doc.write(out); - + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); POIFSFileSystem fs = new POIFSFileSystem(in); handlePOIFSFileSystem(fs); fs.close(); } - + // a test-case to test this locally without executing the full TestAllFiles @Test public void test() throws Exception { @@ -75,7 +75,7 @@ public class POIFSFileHandler extends AbstractFileHandler { try (InputStream stream = new FileInputStream(file)) { handleFile(stream, file.getPath()); } - + //handleExtracting(file); } } diff --git a/src/integrationtest/org/apache/poi/stress/POIFileScanner.java b/src/integrationtest/org/apache/poi/stress/POIFileScanner.java index 947e709dd2..c1f426d9ba 100644 --- a/src/integrationtest/org/apache/poi/stress/POIFileScanner.java +++ b/src/integrationtest/org/apache/poi/stress/POIFileScanner.java @@ -19,7 +19,7 @@ package org.apache.poi.stress; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.FileInputStream; @@ -39,8 +39,8 @@ import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.util.SuppressForbidden; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.tools.ant.DirectoryScanner; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Helper class to scan a folder for files and return a collection of @@ -191,7 +191,7 @@ public class POIFileScanner { return TestAllFiles.NullFileHandler.instance; } - @Ignore + @Disabled @Test @SuppressForbidden("Just an ignored test") public void testInvalidFile() throws IOException, InterruptedException { diff --git a/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java b/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java index 1c2e942b7e..a06b315d6e 100644 --- a/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java +++ b/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; diff --git a/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java b/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java index 8e426a1d98..b5a1104d2b 100644 --- a/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java +++ b/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java @@ -16,6 +16,18 @@ ==================================================================== */ package org.apache.poi.stress; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.ref.WeakReference; + import org.apache.poi.sl.draw.Drawable; import org.apache.poi.sl.usermodel.GroupShape; import org.apache.poi.sl.usermodel.Notes; @@ -29,18 +41,6 @@ import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.sl.usermodel.TextShape; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.ref.WeakReference; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - public abstract class SlideShowHandler extends POIFSFileHandler { public void handleSlideShow(SlideShow ss) throws IOException { renderSlides(ss); @@ -127,10 +127,8 @@ public abstract class SlideShowHandler extends POIFSFileHandler { private void readPictures(SlideShow ss) { for (PictureData pd : ss.getPictureData()) { Dimension dim = pd.getImageDimension(); - assertTrue("Expecting a valid height, but had an image with height: " + dim.getHeight(), - dim.getHeight() >= 0); - assertTrue("Expecting a valid width, but had an image with width: " + dim.getWidth(), - dim.getWidth() >= 0); + assertTrue( dim.getHeight() >= 0, "Expecting a valid height, but had an image with height: " + dim.getHeight() ); + assertTrue( dim.getWidth() >= 0, "Expecting a valid width, but had an image with width: " + dim.getWidth() ); } } diff --git a/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java b/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java index 38f633b4cd..abc1ca5615 100644 --- a/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java +++ b/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -37,10 +37,10 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { public void handleWorkbook(Workbook wb) throws IOException { // try to access some of the content readContent(wb); - + // write out the file writeToArray(wb); - + // access some more content (we had cases where writing corrupts the data in memory) readContent(wb); @@ -51,11 +51,11 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { Workbook read = WorkbookFactory.create(new ByteArrayInputStream(out.toByteArray())); assertNotNull(read); - + readContent(read); - + extractEmbedded(read); - + modifyContent(read); read.close(); @@ -68,7 +68,7 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { } finally { stream.close(); } - + return stream; } @@ -84,7 +84,7 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { if(sheet.getPhysicalNumberOfRows() > 1000) { continue; } - + for(Row row : sheet) { for(Cell cell : row) { assertNotNull(cell.toString()); @@ -111,7 +111,7 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { } } } - + private void modifyContent(Workbook wb) { /* a number of file fail because of various things: udf, unimplemented functions, ... we would need quite a list of excludes and the large regression tests would probably diff --git a/src/integrationtest/org/apache/poi/stress/TestAllFiles.java b/src/integrationtest/org/apache/poi/stress/TestAllFiles.java index 020d436c45..cf059642a7 100644 --- a/src/integrationtest/org/apache/poi/stress/TestAllFiles.java +++ b/src/integrationtest/org/apache/poi/stress/TestAllFiles.java @@ -17,9 +17,8 @@ package org.apache.poi.stress; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.BufferedInputStream; import java.io.File; @@ -34,18 +33,16 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import org.apache.poi.OldFileFormatException; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.poifs.crypt.Decryptor; import org.apache.tools.ant.DirectoryScanner; -import org.junit.AssumptionViolatedException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.opentest4j.TestAbortedException; /** * This is an integration test which performs various actions on all stored test-files and tries @@ -54,7 +51,7 @@ import org.junit.runners.Parameterized.Parameters; * This test looks for any file under the test-data directory and tries to do some useful * processing with it based on it's type. * - * The test is implemented as a junit {@link Parameterized} test, which leads + * The test is implemented as a junit {@link ParameterizedTest} test, which leads * to one test-method call for each file (currently around 950 files are handled). * * There is a a mapping of extension to implementations of the interface @@ -71,7 +68,6 @@ import org.junit.runners.Parameterized.Parameters; * here as well! This is to ensure that files that should not work really do not work, e.g. * that we do not remove expected sanity checks. */ -@RunWith(Parameterized.class) public class TestAllFiles { private static final File ROOT_DIR = new File("test-data"); private static final boolean IGNORE_SCRATCHPAD = Boolean.getBoolean("scratchpad.ignore"); @@ -344,8 +340,7 @@ public class TestAllFiles { "spreadsheet/61300.xls"//intentionally fuzzed -- used to cause infinite loop ); - @Parameters(name="{index}: {0} using {1}") - public static Iterable files() { + public static Stream files() { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(ROOT_DIR); scanner.setExcludes(SCAN_EXCLUDES); @@ -354,7 +349,7 @@ public class TestAllFiles { System.out.println("Handling " + scanner.getIncludedFiles().length + " files"); - List files = new ArrayList<>(); + List files = new ArrayList<>(); for(String file : scanner.getIncludedFiles()) { file = file.replace('\\', '/'); // ... failures/handlers lookup doesn't work on windows otherwise if (IGNORED.contains(file)) { @@ -362,49 +357,41 @@ public class TestAllFiles { continue; } FileHandler handler = HANDLERS.get(getExtension(file)); - files.add(new Object[] { file, handler }); + files.add(Arguments.of( file, handler )); // for some file-types also run OPCFileHandler if(handler instanceof XSSFFileHandler || handler instanceof XWPFFileHandler || handler instanceof XSLFFileHandler || handler instanceof XDGFFileHandler) { - files.add(new Object[] { file, new OPCFileHandler() }); + files.add(Arguments.of( file, new OPCFileHandler() )); } if (handler instanceof HSSFFileHandler || handler instanceof HSLFFileHandler || handler instanceof HWPFFileHandler || handler instanceof HDGFFileHandler) { - files.add(new Object[] { file, new HPSFFileHandler() }); + files.add(Arguments.of( file, new HPSFFileHandler() )); } } - return files; + return files.stream(); } - @SuppressWarnings("DefaultAnnotationParam") - @Parameter(value=0) - public String file; + // the display name annotation is ignored by ants junitlauncher listeners :( + // ... even when using a custom display name generator + @ParameterizedTest(name = "#{index} {0}" ) + @MethodSource("files") + public void testAllFiles(String file, FileHandler handler) throws Exception { + assertNotNull(handler, "Did not find a handler for file " + file); - @Parameter(value=1) - public FileHandler handler; - - @Before - public void setPassword() { // this also removes the password for non encrypted files String pass = TestAllFiles.FILE_PASSWORD.get(file); Biff8EncryptionKey.setCurrentUserPassword(pass); - } - @Test - public void testAllFiles() throws Exception { - if(handler == null) { - fail("Did not find a handler for file " + file); - } System.out.println("Reading " + file + " with " + handler.getClass().getSimpleName()); - assertNotNull("Unknown file extension for file: " + file + ": " + getExtension(file), handler); + assertNotNull( handler, "Unknown file extension for file: " + file + ": " + getExtension(file) ); File inputFile = new File(ROOT_DIR, file); // special cases where docx-handling breaks, but OPCPackage handling works @@ -416,14 +403,12 @@ public class TestAllFiles { try { try (InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64 * 1024)) { handler.handleFile(stream, file); - assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!", - OLD_FILES_HWPF.contains(file) && !ignoreHPSF); + assertFalse( OLD_FILES_HWPF.contains(file) && !ignoreHPSF, "Expected to fail for file " + file + " and handler " + handler + ", but did not fail!" ); } handler.handleExtracting(inputFile); - assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!", - EXPECTED_FAILURES.contains(file) && !ignoredOPC && !ignoreHPSF); + assertFalse( EXPECTED_FAILURES.contains(file) && !ignoredOPC && !ignoreHPSF, "Expected to fail for file " + file + " and handler " + handler + ", but did not fail!" ); } catch (OldFileFormatException e) { // for old word files we should still support extracting text if(OLD_FILES_HWPF.contains(file)) { @@ -435,7 +420,7 @@ public class TestAllFiles { throw new Exception("While handling " + file, e); } } - } catch (AssumptionViolatedException e) { + } catch (TestAbortedException e) { // file handler ignored this file } catch (Exception e) { // check if we expect failure for this file @@ -448,7 +433,7 @@ public class TestAllFiles { try { // let some file handlers do additional stuff handler.handleAdditional(inputFile); - } catch (AssumptionViolatedException e) { + } catch (TestAbortedException e) { // file handler ignored this file } catch (Exception e) { if(!EXPECTED_FAILURES.contains(file) && !AbstractFileHandler.EXPECTED_EXTRACTOR_FAILURES.contains(file)) { diff --git a/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java index 0f00a9aeab..b48a8bafef 100644 --- a/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java @@ -21,7 +21,7 @@ import java.io.InputStream; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XDGFFileHandler extends AbstractFileHandler { @Override diff --git a/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java index 78515f450a..6c54be4f7e 100644 --- a/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -27,7 +27,7 @@ import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.sl.extractor.SlideShowExtractor; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XSLFFileHandler extends SlideShowHandler { @Override @@ -64,7 +64,7 @@ public class XSLFFileHandler extends SlideShowHandler { extractor.setNotesByDefault(false); extractor.setMasterByDefault(false); - assertEquals("With all options disabled we should not get text", "", extractor.getText()); + assertEquals("", extractor.getText(), "With all options disabled we should not get text"); } } diff --git a/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java index b728828c4f..d2e4df1191 100644 --- a/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java @@ -24,7 +24,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XLSBUnsupportedException; import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XSSFBFileHandler extends AbstractFileHandler { diff --git a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java index b1aa5b718c..ec060dee05 100644 --- a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java @@ -16,10 +16,10 @@ ==================================================================== */ package org.apache.poi.stress; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +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.Assumptions.assumeFalse; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -54,7 +54,7 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.extractor.XSSFExportToXml; import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; public class XSSFFileHandler extends SpreadsheetHandler { @@ -78,7 +78,7 @@ public class XSSFFileHandler extends SpreadsheetHandler { Decryptor dec = ei.getDecryptor(); try { boolean b = dec.verifyPassword(pass); - assertTrue("password mismatch", b); + assertTrue( b, "password mismatch" ); } catch (EncryptedDocumentException e) { String msg = "Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files"; assumeFalse(msg.equals(e.getMessage())); @@ -190,8 +190,7 @@ public class XSSFFileHandler extends SpreadsheetHandler { XLSX2CSV.main(new String[]{file.getAbsolutePath()}); ExcelComparator.main(new String[]{file.getAbsolutePath(), file.getAbsolutePath()}); - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_ADDITIONAL_FAILURES.contains(testFile)); + assertFalse( EXPECTED_ADDITIONAL_FAILURES.contains(testFile), "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!" ); } catch (OLE2NotOfficeXmlFileException e) { // we have some files that are not actually OOXML and thus cannot be tested here diff --git a/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java index 582a28cadc..92bfabbc49 100644 --- a/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java +++ b/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java @@ -22,7 +22,7 @@ import java.io.FileInputStream; import java.io.InputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XWPFFileHandler extends AbstractFileHandler { @Override diff --git a/src/java/org/apache/poi/poifs/nio/FileBackedDataSource.java b/src/java/org/apache/poi/poifs/nio/FileBackedDataSource.java index ce73077910..a4ec0a35c4 100644 --- a/src/java/org/apache/poi/poifs/nio/FileBackedDataSource.java +++ b/src/java/org/apache/poi/poifs/nio/FileBackedDataSource.java @@ -17,6 +17,7 @@ package org.apache.poi.poifs.nio; +import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -35,7 +36,7 @@ import org.apache.poi.util.POILogger; /** * A POIFS {@link DataSource} backed by a File */ -public class FileBackedDataSource extends DataSource { +public class FileBackedDataSource extends DataSource implements Closeable { private final static POILogger logger = POILogFactory.getLogger(FileBackedDataSource.class); private final FileChannel channel; diff --git a/src/java/org/apache/poi/ss/formula/atp/DateParser.java b/src/java/org/apache/poi/ss/formula/atp/DateParser.java index 1cb25527b6..a8419bc51f 100644 --- a/src/java/org/apache/poi/ss/formula/atp/DateParser.java +++ b/src/java/org/apache/poi/ss/formula/atp/DateParser.java @@ -17,80 +17,13 @@ package org.apache.poi.ss.formula.atp; -import java.util.Calendar; -import java.util.regex.Pattern; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.util.LocaleUtil; +import org.apache.poi.util.Removal; /** * Parser for java dates. + * @deprecated in 5.0.0 - use {@link org.apache.poi.ss.util.DateParser} */ -public class DateParser { - private DateParser() { - // enforcing singleton - } - - /** - * Parses a date from a string. - * - * @param strVal a string with a date pattern. - * @return a date parsed from argument. - * @throws EvaluationException exception upon parsing. - */ - public static Calendar parseDate(String strVal) throws EvaluationException { - String[] parts = Pattern.compile("/").split(strVal); - if (parts.length != 3) { - throw new EvaluationException(ErrorEval.VALUE_INVALID); - } - String part2 = parts[2]; - int spacePos = part2.indexOf(' '); - if (spacePos > 0) { - // drop time portion if present - part2 = part2.substring(0, spacePos); - } - int f0; - int f1; - int f2; - try { - f0 = Integer.parseInt(parts[0]); - f1 = Integer.parseInt(parts[1]); - f2 = Integer.parseInt(part2); - } catch (NumberFormatException e) { - throw new EvaluationException(ErrorEval.VALUE_INVALID); - } - if (f0 < 0 || f1 < 0 || f2 < 0 || (f0 > 12 && f1 > 12 && f2 > 12)) { - // easy to see this cannot be a valid date - throw new EvaluationException(ErrorEval.VALUE_INVALID); - } - - if (f0 >= 1900 && f0 < 9999) { - // when 4 digit value appears first, the format is YYYY/MM/DD, regardless of OS settings - return makeDate(f0, f1, f2); - } - // otherwise the format seems to depend on OS settings (default date format) -// if (false) { -// // MM/DD/YYYY is probably a good guess, if the in the US -// return makeDate(f2, f0, f1); -// } - // TODO - find a way to choose the correct date format - throw new RuntimeException("Unable to determine date format for text '" + strVal + "'"); - } - - /** - * @param month 1-based - */ - private static Calendar makeDate(int year, int month, int day) throws EvaluationException { - if (month < 1 || month > 12) { - throw new EvaluationException(ErrorEval.VALUE_INVALID); - } - Calendar cal = LocaleUtil.getLocaleCalendar(year, month - 1, 1, 0, 0, 0); - if (day < 1 || day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) { - throw new EvaluationException(ErrorEval.VALUE_INVALID); - } - cal.set(Calendar.DAY_OF_MONTH, day); - return cal; - } - +@Removal(version = "6.0.0") +@Deprecated +public class DateParser extends org.apache.poi.ss.util.DateParser { } diff --git a/src/java/org/apache/poi/ss/util/DateParser.java b/src/java/org/apache/poi/ss/util/DateParser.java index 996a1384f1..a69dae6383 100644 --- a/src/java/org/apache/poi/ss/util/DateParser.java +++ b/src/java/org/apache/poi/ss/util/DateParser.java @@ -35,7 +35,7 @@ import org.apache.poi.util.LocaleUtil; * Parser for java dates. */ public class DateParser { - private DateParser() { + protected DateParser() { // enforcing singleton } diff --git a/src/multimodule/excelant/test9/module-info.class b/src/multimodule/excelant/test9/module-info.class index 2d75c59c3f2a0d3bee8e8ebb0bb8d92a3b2df147..904b2ebeab9d09eef3b6899d4d21da749e8189d3 100644 GIT binary patch literal 370 zcmZ{gO;Q3e5QSf(3?lwv22nSjfW!^O4cu{vc8C&cW|Ep@ES8+hg$M9ZmLcE<$}GO> z*DtBO?(d(^F91`Fd*~1bm0h%@o|yX060&(x0$sw`Ht&)h7fUUjHBzq&U2+`+dW8Op zKUlu9*8+XQN$L*>`N1P=*HtNSNq9JLe9>?ymW~$!*M!m5UbVFek%pJC!r} zEO1M>KfdC);mYU836IfLySOUGRo<(=#5wK=PyhR>4W`@x6!)?_aiUnf;55k$*=Adu YC3T*7k$4q(gJEI^BK1azv{zC50vT3L)20QgO&gqmYmCl2k=nFT1-q#oW+~>=1tyY z9?#nyz#7vwx&(Kt!%LzVdJKJr0mG1Ckj^ZkUoyZlTX(#^AuGZx#AI24MR3)TIs;4-lX*gxE9+M8|c{XS)`9L;sqb>LEr!Y diff --git a/src/multimodule/excelant/test9/module-info.java b/src/multimodule/excelant/test9/module-info.java index 43b64560a7..3d62f5f449 100644 --- a/src/multimodule/excelant/test9/module-info.java +++ b/src/multimodule/excelant/test9/module-info.java @@ -25,4 +25,8 @@ module org.apache.poi.excelant { exports org.apache.poi.ss.excelant.util; opens org.apache.poi.ss.excelant; + + // test specific exports + requires org.junit.jupiter.api; + requires org.junit.jupiter.params; } \ No newline at end of file diff --git a/src/multimodule/integration/java9/module-info.java b/src/multimodule/integration/java9/module-info.java index 51d730c132..5dff7e4feb 100644 --- a/src/multimodule/integration/java9/module-info.java +++ b/src/multimodule/integration/java9/module-info.java @@ -16,12 +16,12 @@ ==================================================================== */ module org.apache.poi.stress { - requires junit; + requires org.junit.jupiter.api; + requires org.junit.jupiter.params; requires net.bytebuddy; requires java.desktop; requires org.apache.poi.examples; exports org.apache.poi.stress; - } \ No newline at end of file diff --git a/src/multimodule/ooxml/test9/module-info.class b/src/multimodule/ooxml/test9/module-info.class index bbd2c51907425f845cb1c2f22db2c5483d59cb97..f5564abd5c56d5014813d074c5469aa2fdc7e24f 100644 GIT binary patch literal 4035 zcma)9hnv(y6n~?_iGTKysmTWYn8yJ>!9ASkvK5y1wDuY>tq>8XK&=^c^?`!a|zDa}W z3?`L4?gwJ49hO9>!Au5I+9XHTYPMU`U^dbyyyVT?_M3_bhC}ITFdt(kP9UtNZ--;X zP%S{m7otLXkI@>IKjwu}gT)NyrW_5p8#cLbO9M%`UxTF#W=DjwY`WH%#e>kng!{5( zSA?&@at71$%ft4l1}m`?WggnY26wPBs~Jp9S@J5?vP9OY-4&`zH>CILun-kt_%g&_ z--zi(&F5a-wt|fn4NR;ddf9%36`)FJutE7W)O7987;1WUD17V{o58q#V~ep~gUzZw z-4x6}Z(ycQLswCoQIoQU(Z-5(IGw?KjKGY$&cxm@M@PJ>DMmw|Tj-?@XZD~p1L0#U z3rB~uK^H@`PpNFREy zpejUZ37n>#>iIoXr6^%OiDWIIn04WJl#LdHRhevLsMrd^4Wb)KhfxM|ir8h_<8v}Td!HP_ZvLv(0EfHcmAI>K~$Hl_8Y)c^f(IcA= zMZ?qK@%#iyW`{|0LW3vcD&n0M-E5x2!>aTf?VC@Brx~owgwSd9=nUdj<~cTZEu6d0 zGFX%$r(+035JmcYe$oaGju~2fF+UaBi>k6O7i1xLtH|odv zE{_)43H!8YN;x>CKJRgWk`B`0O9nGCA<_A?r4C=`6O)-GbYEaQd|TiFegpNv_YBr# z)F;NxZS60lJ?g`;4-PTt&+s!BrnzVLj=^0!lf47KQUOF*^0GJ@@(#x{%~2! z;f}Gx`3ol#-(aaU(B79A`jx@DtRW|5sN~>BaH%dwI+lKCurae`G)PY}bFj2?AlaCh z`ZHevJW0`XGAu8 zcLmIG!xh{SHR3KRi@vEZzF1|ISoq|dua>2S-afexzI^|^r*HSYeR}5G?C%-pyWBdZX1}vMmTOx-IZt)xy!B>cLqYi|27U7vc+O1R>2~JRSGoT&~6k>3oDCRVeVGxJwrzEKrlI zGw#;|4=$d&mgO#*hby_CQnU)8N3H1WYgN>fSF2grC>Q;@Um6dJ^{`T$8ZD0%%RyN4 z;0oSCNxCY!;}~_?qrpZGu13g2v;Uv^T0Tk{yq^D|Jl@FJwv*_l=p6r2+AfyH{YJ}! zTe#lVPq!kZIA^2`4}64z8Wz;Bgs?~r7xD>4I|iIKhN&FAWzI;NlXA=o?{PbfW^>Gg z4Sdw-=DmhXHH17LGd%vmI1xit&f^_3<{&i@`c*y6tIT$qM3^s&>ZV1TqP|9V>@-ch zQyw&Hx^%a^pwVf_Uia|NW*VpYPcx5Oc)pdvt-Q=i(*p=up0={8@elE4>tuQ)+GpCz z@%NTPk40BQJKa{Rd+-GRZS|^kJ9xxC1)t=qT|nj^?GC3}Yz56$(}SmZ*6zh;RWXIT z_z!y_y%06lcT$$G+VxWOINymjdxh6I1GEQWKoxSl&vEHBgkJv5NxIFTp?@N8@UKoU zzBS`!aPM5Rs;XK0c-YO;dk9_8Yg?7jgIR>Ws5{Qwmr+OAuh#d_M+k#_+)DCKZU=pW z>ZhqbGRG2m{EQ2UMf64Vk)p0{N_63uygjiPzvd%}rFe+{N(|7E=zPDJJ-nj5&t40p z{sREryrF&TG{9n+jlk)WXNbe%nc~^v3h^BAJn;hYBJmROQt>kJa`8%Wjd+cCop^(| z7C`L}H_K$5c$;{;I4X{b1nN(`k zQba_gez=I=YW)j>P~5pt!JP{QH!g%iL0k#yLU2`l6XL>lch9-!e%|4}KhcSL<^9~N z*8tEB&#o%(#$?mZbUL~IHG^TOL8u(mhPBR|naN}enK0D-V|2qAa!o4?QG_Lf`cP-F z;1n&(v|U5z(15U5^iefSOAi>TWo9|V5o-SD)U=t;n*|ODghV+-eHig`SVjl1J=Tn{ zbY6+B_j5=gL}*%$#5lAfgy%^HEJtYC=o2>K3i^#rtV4*X*B2IzRqFD^u#0y4n%QcE zCP7E(lCOewBXpL5OmBRPv4=kRns6Qc@-^ams`4jr1FiJ8vrPzb8u!PT7_x=V_*1x* ze)<#TUi!!qxQ~9Y6m1M7D*Lhp%^tDSYd9RFO@TIc7@?V_S#8)Jv0T-0wSunM z!u}%&jUG?W0}4A`P}5R)R6c`a?54u?!xD;KgRhpe~c zG^?SLlEQ`%VkIys$@O`J+Ig-!IaRl{6ErJDD!o9>7-pWsar!DH_d5u63-#H&mJwbQ z5gHaIi;iLEP2I?GIDt?-Um%tpp+mtWj?!o_&Q2plX(kwzIE;B)&jjlw&9yj;)0bc? zJL?%DI7)^jb`Bv`224@=O?${Y+4DjeCo`n53!bZ<*bIe&V$Q{KLwXwuu!%B|i{2q# z7OT^&+#tqY^{Qs&*rEX=XBoDrBVm$Y!jhX6kGMvA)Hp}0DiLVQwP_m*Y7%9b@UmmR( c#ng=w03o;qci=8efnP)j4+KJZBrw90zb63}f&c&j delta 1041 zcmZuw&1(};5T8k2HrY*EwRvrmHfe0rSp4eZXAvo_h=_^S{c?SSn z;Q6HX{$kxpF)DfrRxW3jauH}k`0dFWPTsZ35okeJb~2mqsg#^bxop|4k>wCWXt3;@ zF3KWv!qCf>$)OFQ>2IH&v5G~j#36x@{BKC7OQ`xeBq@h$;vEQ$HMDGYghL7;O7m(o z&LNEusiB-GJCf5)i`Yq@F-mQ|aO>Lt&>WApo(6nz)M?0t>q}dg!<>MzcPZ zKKdGP3k|ZCI^&FMi;Qd89D1kx?YNDS{v>Xve*YTm^BB~}f`N>b?57ET8h6kSe==Ns z?@sw%y5)~6R>|eCONLhAZkgI%Up7ZA*A>GBgTo#v(}{bfzlCnF2=1dfmSFo4+GvqA zhpJkG^ob?$AT6;pJA}|h7-&<6&62Rk?968B2y{>(5N3xFQeG(RxT2I5wp`K?dK5^p zA#Zq#tVzupqa2QT3KG%xzzQb3HYHd-VipW%%yEq(hs^K#O?5?)u`P##Q58^1ro|yg zr<6`+BE)~myin9c9-+BrCr&}n+Tt{aB5erD($dy*hE=2mCA#{L(VjwR`8U-pikzH} zBXd_qD+nuUDYC26G8mzA!Fn8{>%jy&ix8u)!I;9~JVHX6t%`8V94?XwB^okT$s3H^ z#yCQ|7bQKUu*(Q(4>TB~qM(mhcHX=0D>9{kgmqO3 zmFl!coTa3;5$EWDwwgUcdA{>%jHb0_d_pg^t@w<-XankJVDdu)sHBH`g98xt!0Tf8 aEG9vQrr{pUzyt703*n(e2#+O3c={7WEFH7} diff --git a/src/multimodule/poi/test9/module-info.class b/src/multimodule/poi/test9/module-info.class index d3bfb0afd1601487e4af28268fc6ba0925dcb3ee..5df619f8a0b7839dfaa1d284774550d8b3756531 100644 GIT binary patch literal 3547 zcmai$XPetZ5P)aXjwF|aM4R3lCFHDxHp{rYKcJEDc!5U~^8)3Oq0H2wu zFkt59?inJ|lCInEgO<^+Sy5h*}uTBMi0-U(K}YB2pZVGT1swiYk}Gje1_@O|vlDINW>|T~Rw!0f$>g zyBRvoKq*miC5Pif+{|s|i6Pp0B4%B>p^PwSx9dqyP9(~~s=AZG`hiGbwN~R^ZQiAC zUq>KyjKe*8z;olceNO7qeGGOKFOzC9D~>Osc4Y16@W5zEi^7Smh{Hn+wvW&mE8*KB z&Ebk(LwOTVrNwXSQOabf3ai76qB5+ai*Y+v(&JFqQzp}s7n&XxbWd1OfP3Z+v&MHY zm3%!vvNggez&%%O4k3dLg|UgT)rlJJNW@^(fJE$?b|hLHlx|;V%&f@(y=)c= zy{DlD$D^emDV*I)T@H^iSUzYQM&*fud2zlI&FEo^V>}chJW4q{rT3}MXyOVE&*)L@ z51T@T9G=q~ZB7K+L7H>8(hGXR<>X{jVBx)_SMY#LYIs9p{=PDD*=pj`<$}X&dO_q= zcI7aTZ;W&`R5cE7jTA}J)AXIf?Z|E8dxiG&1o|!NgMwU)&8$Ivq!$!Am5!Mf9DV$FgYOya9*|Fc?%svWlb9HlAZYYw{K#NpaE6Dp{rDT41Q;@cfg+P(CPVb zv|K*Y^`kfKPd!jwoAC1MiEx%>GXM-P@7agJT!1-?U>-e=!-ARg&pGt8h&WDMN<5di zg2;)hh---JkQ-nl@gQubcUy_ui93ns6E7rQM4TX+#J$9Q#7W`-;$_4uh*uG>Azn+o zj(C`O1MwK~CgK$FR^n~MGVu=LN#fnadx`fGA0!H*MU=!E(IGa79x)(3OpJ*Mu|;eX zA0<9cJWYI(_%!iZ;`788i7yjhCB9C4llV6AUE=%14~ZWWKPAqE&+(VRm+*DxH;rog bJP*#mckl!JgnNGm-~57441U9B27mky_J;|_ literal 3447 zcmai$cbD5l5Wr_ck|SISi8j4AO2}D+T<9ePawNb(h=I^yEv;>xWv!4_c1+9Bd+$B; z&IjNRJ^-JI$73{dQM|Hq@7+(9c6N4Vc4l_}`R}j40pI}qIROh8Og5F9_;Sh%s*1tl zS$eZz5rb7Ks+B}2oVqN9%1i$(m|(DEPP9a+B4TO55(ZmyVvcGyRS=gP<@?gn9{!%T zV3NVQLLpZ=7A#}1tT(SIbbY@CD;O*-ha!sQAy1d3wqPZL6+Ize)oNZ)v%o?zvZeoJ zb?=KSCV775MdKO(#C)A3=ZR6bxy_V8iRD8){c7&U`t-N!Dw!Vm6mwqTC z4BB00(vuU3_OPnT3^oo$0;{ze_iOVWbNjjisbd^Ym;uj?_V*_q7*i;ys7+amF;f~-* zwPr{n_H8#3Z4Qr{_I1bXnpEgzTquz135nU$P=nW`rQ3zG`>D&J!(ipGZ5Wj&3+Bc7 zPV}@Hwm8N^A;LqE!zr^*bw?9laCp{?>R{LwI^^)Y*=Tbj*bdU1!SME@(5ZCHcJOd*3%|kPQ}b-iW`Azl*bWC51`c1ENs%7RHeA^Fs&-d)E&fg4{@sxg@H z1B0pI8Gdd?*++rY?(3sSmUrgl#^Jj$@^j(;tt5RnIeq*q2 z$e!#_>HBb`T%PIq(VzB*8K|C3cuj4J@C?i50T^Dhvp)vs;OoDzkX|QY@qGH@TzWf? zxRkh@cs_9zkrUSt*AX`m55gvTZXs?X?jY_WUO>EvxQDoxSR!6Zyo@+ayqtI?@oM6= z#OsL%iHC?c6K9A=h_@1NC*DCkMm$cun|LqrKH>w!hlr05A0t+XF0o3i6X%FNF(8J- zh^UDz;z{BY#HWbQ5a)@{5nmv_M0|z#8u1O{Tf}#W?-4&Benk9)_!)5le1T7F+VEBP bxe!jnx9~muh`W6nM}EdP2EXDvgWvxL@FnVM diff --git a/src/multimodule/poi/test9/module-info.java b/src/multimodule/poi/test9/module-info.java index 79a6a70c2e..6923f4cc7e 100644 --- a/src/multimodule/poi/test9/module-info.java +++ b/src/multimodule/poi/test9/module-info.java @@ -103,8 +103,11 @@ module org.apache.poi.poi { exports org.apache.poi.wp.usermodel; // test specific exports - requires junit; requires net.bytebuddy; - opens org.apache.poi.hpsf.basic to junit; - opens org.apache.poi.hssf.record.pivot to junit; + requires org.junit.jupiter.api; + requires org.junit.jupiter.params; + + opens org.apache.poi.hpsf.basic to org.junit.platform.commons; + opens org.apache.poi.hssf.record.pivot to org.junit.platform.commons; + opens org.apache.poi.hssf.dev to org.junit.platform.commons; } \ No newline at end of file diff --git a/src/multimodule/scratchpad/test9/module-info.class b/src/multimodule/scratchpad/test9/module-info.class index e74671e4fb1d2f31a2b76fed8288ef8680d75711..2bc8390055e9d1e432f42a05cfa6baa6421d1986 100644 GIT binary patch literal 2782 zcmZ{mX@A>95XPSkw5GJ>sJ8TOLn);cVwIFoj&hTbLP|@`earGXQX*NZw6+t@aNqDH z_!PY01Ms2vF*{OZM_%W}Un|dOXXcsFD*yiX_dfs@@Mi-v0(;}6(~s0#*y|<&yRY({ zgIxkgl5Dlfny#o8#t)udF zoum%-3+(rkI8J(bGxl_F(ZQVp2hGE4{a&bvX{c33fkS~^3(ZT-3l0tl9G-MZz08Yq z2a>8V);RIkL!C(6BjC^vZjro8sklL`x)O&44p|ItM-3#73Y@SR)rQVIUniNw@hL8z z)>+u@Yb9~g61%fXv1cu@$xy^TEpV(J+Zc15DXLN8j3u&h7)$P~z;W9iRDO>XrA^KW zoV0nU4PT`?q@GBe7dUG3@q>PEo$L==>Kmq1U(-?_8H)NY6b;r5MJF>}5yNsVJJHD0r-gfMWpTb$ech`qmiVi;*}xA1bG04vXe5{0iYQVmNQR@JKMBm& z9tq6!R~oy^t(B$f!79`*0%vN^Q7F?l_e$)osvD|DMVYdGo0K6ir!4y})2inGhsA$; zCfsFO?eO0M1pSv({0ZDbw}0VQzHMOlmRa0}S>o+xiG9pFhWQF^@2h zF;6g0G4EyG$Go5U0P{iSL(Dm*%Y1}+k-5OU#C(GJ6!U53v&`q2FESUIFEg(&Uu9lp zUSqz_Y%$+tzRi4>`9AYQ=EqEr=`$5`l^HVEnK3hA-el&?K66ME*u-b$^^5ZQRe7C( csgT|mnCi?G)RV7i^)0?9{)nG3gJ1Fc|KlqY^Z)<= literal 2690 zcmai$>3Z8l6ox+)8n?7%sSb2+Ln);cVnIq+3uQ}4A*H2e-(`6cDUmEy8runL*q4jo zLioW2a8W#*Id&9V8iRkl8tXeVXU;NX|NYOOe*sv)?+q+Dn7NjAda-ixnu}!@S6#gB z;tdxoF0K*YBwQ!lAiPDmNoWz?CcHy}M&;d6pdXcGcL zhoA_ngf&7)hzRS14MI#v2wg%-$OyLxIiVnELXXfV3<#TqEy5RsF9}}}z9xJ__?ECu z_>S;>13xtIV*@`m@N)ydH1KN!zd1ONNJMi{cQtizEX~)Ne&z?EYG!HFEP~wEL74d+ z2m9CkzTa&7g>rDXV#l@)4vIlX6&pIu92^SLBuTqPGx2qJ$-&zOco#s4-Du;JD2o2z%WP7HgplGFvG8b{NXh z>S9JIvOKZGVWc4K_EpY1ouZG$S*wbf-z!wk-KFATUrkim=p(I`qf+xCZjdv!UCUHY zZ)M7sq(QRk$;cG~(Ea zbKOj|g^@-PUzn#OfTZy$h}s~K3ZWq*mXBwv6qum=E_@ctt^$ZN+;(klh}#LymvM6*VIkb zg*)wn}*r-|V*kN(eir=H$2k0y+_0f+z33_lL`@Yg?Zn|z(Y?b~Ls7qiS6GekqU zPq<&WfIH-QKzLAiNO-64F5%t6dxVFDu8@TH3hxsh5grvD6CM|y5S|pC5}p>G5zY$l z7oHV9AUr30P|8bHb+36Fw$g#51xCOY#3*Wn6}Uc^hxm+=Z$=T$8J3)xEa9RL6T diff --git a/src/multimodule/scratchpad/test9/module-info.java b/src/multimodule/scratchpad/test9/module-info.java index 2aaef57a0a..e3472062ea 100644 --- a/src/multimodule/scratchpad/test9/module-info.java +++ b/src/multimodule/scratchpad/test9/module-info.java @@ -76,13 +76,14 @@ module org.apache.poi.scratchpad { // test specific exports - requires junit; + requires org.junit.jupiter.api; + requires org.junit.jupiter.params; requires org.mockito; - exports org.apache.poi.hemf.hemfplus.extractor to junit; - exports org.apache.poi.hslf to junit; - exports org.apache.poi.hwmf to junit; - exports org.apache.poi.hwpf.util to junit; + exports org.apache.poi.hemf.hemfplus.extractor to org.junit.platform.commons; + exports org.apache.poi.hslf to org.junit.platform.commons; + exports org.apache.poi.hwmf to org.junit.platform.commons; + exports org.apache.poi.hwpf.util to org.junit.platform.commons; opens org.apache.poi.hwpf.model to org.mockito; opens org.apache.poi.hwpf.model.types to org.mockito; diff --git a/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java b/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java index 1a4940c051..1ef26afca2 100644 --- a/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java +++ b/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java @@ -17,13 +17,12 @@ package org.apache.poi.extractor.ooxml; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.File; import java.io.FileInputStream; @@ -31,7 +30,6 @@ import java.io.IOException; import java.util.Locale; import org.apache.poi.POIDataSamples; -import org.apache.poi.UnsupportedFileFormatException; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.POIOLE2TextExtractor; import org.apache.poi.extractor.POITextExtractor; @@ -39,6 +37,7 @@ import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.extractor.EventBasedExcelExtractor; import org.apache.poi.hssf.extractor.ExcelExtractor; import org.apache.poi.ooxml.extractor.POIXMLExtractorFactory; +import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -47,7 +46,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; import org.apache.poi.xssf.extractor.XSSFExcelExtractor; import org.apache.xmlbeans.XmlException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test that the extractor factory plays nicely @@ -86,17 +85,17 @@ public class TestExtractorFactory { private static final File vsd = getFileAndCheck(dgTests, "Test_Visio-Some_Random_Text.vsd"); private static final File vsdx = getFileAndCheck(dgTests, "test.vsdx"); - private static POIDataSamples pubTests = POIDataSamples.getPublisherInstance(); - private static File pub = getFileAndCheck(pubTests, "Simple.pub"); + private static final POIDataSamples pubTests = POIDataSamples.getPublisherInstance(); + private static final File pub = getFileAndCheck(pubTests, "Simple.pub"); private static final POIXMLExtractorFactory xmlFactory = new POIXMLExtractorFactory(); private static File getFileAndCheck(POIDataSamples samples, String name) { File file = samples.getFile(name); - assertNotNull("Did not get a file for " + name, file); - assertTrue("Did not get a type file for " + name, file.isFile()); - assertTrue("File did not exist: " + name, file.exists()); + assertNotNull(file, "Did not get a file for " + name); + assertTrue(file.isFile(), "Did not get a type file for " + name); + assertTrue(file.exists(), "File did not exist: " + name); return file; } @@ -127,6 +126,7 @@ public class TestExtractorFactory { R apply(T t) throws IOException, OpenXML4JException, XmlException; } + @SuppressWarnings("ConstantConditions") @Test public void testFile() throws Exception { for (int i = 0; i < TEST_SET.length; i += 4) { @@ -172,6 +172,7 @@ public class TestExtractorFactory { assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0")); } + @SuppressWarnings("ConstantConditions") private void testStream(final FunctionEx poifsIS, final boolean loadOOXML) throws IOException, OpenXML4JException, XmlException { for (int i = 0; i < TEST_SET.length; i += 4) { @@ -182,22 +183,21 @@ public class TestExtractorFactory { try (FileInputStream fis = new FileInputStream(testFile); POITextExtractor ext = poifsIS.apply(fis)) { testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]); - } catch (IllegalArgumentException e) { - fail("failed to process "+testFile); } } } private void testExtractor(final POITextExtractor ext, final String testcase, final String extrClass, final Integer minLength) { - assertEquals("invalid extractor for " + testcase, extrClass, ext.getClass().getSimpleName()); + assertEquals(extrClass, ext.getClass().getSimpleName(), "invalid extractor for " + testcase); final String actual = ext.getText(); if (minLength == -1) { assertContains(actual.toLowerCase(Locale.ROOT), "test"); } else { - assertTrue("extracted content too short for " + testcase, actual.length() > minLength); + assertTrue(actual.length() > minLength, "extracted content too short for " + testcase); } } + @SuppressWarnings("ConstantConditions") @Test public void testPackage() throws Exception { for (int i = 0; i < TEST_SET.length; i += 4) { @@ -208,19 +208,17 @@ public class TestExtractorFactory { try (final OPCPackage pkg = OPCPackage.open(testFile, PackageAccess.READ); final POITextExtractor ext = xmlFactory.create(pkg)) { + assertNotNull(ext); testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]); pkg.revert(); } } } - @Test(expected = UnsupportedFileFormatException.class) - public void testPackageInvalid() throws Exception { + @Test + public void testPackageInvalid() { // Text - try (final OPCPackage pkg = OPCPackage.open(txt, PackageAccess.READ); - final POITextExtractor ignored = xmlFactory.create(pkg)) { - fail("extracting from invalid package"); - } + assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(txt, PackageAccess.READ)); } @Test @@ -334,7 +332,7 @@ public class TestExtractorFactory { final String actual = embeds.length+"-"+numWord+"-"+numXls+"-"+numPpt+"-"+numMsg+"-"+numWordX; final String expected = (String)testObj[i+2]; - assertEquals("invalid number of embeddings - "+testObj[i], expected, actual); + assertEquals(expected, actual, "invalid number of embeddings - "+testObj[i]); } } @@ -445,28 +443,31 @@ public class TestExtractorFactory { * #59074 - Excel 95 files should give a helpful message, not just * "No supported documents found in the OLE2 stream" */ + @Test public void bug59074() throws Exception { try (POITextExtractor extractor = ExtractorFactory.createExtractor(POIDataSamples.getSpreadSheetInstance().getFile("59074.xls"))) { String text = extractor.getText(); - assertContains(text, "testdoc"); + assertContains(text, "Exotic warrant"); } } - @Test(expected = IllegalStateException.class) - public void testGetEmbeddedFromXMLExtractor() throws IOException { + @Test + public void testGetEmbeddedFromXMLExtractor() { // currently not implemented - ExtractorFactory.getEmbeddedDocsTextExtractors(null); + assertThrows(IllegalStateException.class, () -> ExtractorFactory.getEmbeddedDocsTextExtractors(null)); } // This bug is currently open. This test will fail with "expected error not thrown" when the bug has been fixed. // When this happens, change this from @Test(expected=...) to @Test // bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor - @Test(expected=AssertionError.class) + @Test public void test45565() throws Exception { try (POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("45565.xls"))) { String text = extractor.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); + assertThrows(AssertionError.class, () -> { + assertContains(text, "testdoc"); + assertContains(text, "test phrase"); + }); } } } diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java index 6ab773d37b..32bd2df2f9 100644 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java +++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.ooxml; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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 java.io.ByteArrayInputStream; import java.io.IOException; @@ -30,7 +30,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; import org.apache.poi.poifs.filesystem.FileMagic; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test that HXF correctly detects OOXML @@ -52,15 +52,14 @@ public class TestDetectAsOOXML { }; for (Object[] fm : fileAndMagic) { - InputStream is = HSSFTestDataSamples.openSampleFileStream((String)fm[0]); - is = FileMagic.prepareToCheckMagic(is); - FileMagic act = FileMagic.valueOf(is); + try (InputStream is = FileMagic.prepareToCheckMagic(HSSFTestDataSamples.openSampleFileStream((String)fm[0]))) { + FileMagic act = FileMagic.valueOf(is); - assertEquals("OOXML files should be detected, others not", - act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is)); + assertEquals(act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is), + "OOXML files should be detected, others not"); - assertEquals("file magic failed for "+fm[0], fm[1], act); - is.close(); + assertEquals(fm[1], act, "file magic failed for " + fm[0]); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java index f7bd526170..5000c9956a 100644 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java +++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java @@ -19,9 +19,9 @@ package org.apache.poi.ooxml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.openxml4j.opc.OPCPackage; @@ -30,7 +30,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.xslf.usermodel.XSLFSlideShow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test that we handle embeded bits in OOXML files properly diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java index 20d8834845..a50561c6dd 100644 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java +++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java @@ -17,13 +17,17 @@ package org.apache.poi.ooxml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -47,7 +51,8 @@ import org.apache.poi.util.TempFile; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; /** * Test recursive read and write of OPC packages @@ -110,110 +115,88 @@ public final class TestPOIXMLDocument { traverse(p, context); } else { POIXMLDocumentPart prev = context.get(uri); - assertSame("Duplicate POIXMLDocumentPart instance for targetURI=" + uri, prev, p.getDocumentPart()); + assertSame(prev, p.getDocumentPart(), "Duplicate POIXMLDocumentPart instance for targetURI=" + uri); } } } - public void assertReadWrite(OPCPackage pkg1) throws Exception { + private void assertReadWrite(POIDataSamples samples, String filename) throws Exception { + try (InputStream is = samples.openResourceAsStream(filename); + OPCPackage pkg1 = PackageHelper.open(is)){ + File tmp = TempFile.createTempFile("poi-ooxml", ".tmp"); + try (FileOutputStream out = new FileOutputStream(tmp); + OPCParser doc = new OPCParser(pkg1)) { + doc.parse(new TestFactory()); + traverse(doc); + doc.write(out); + out.close(); - OPCParser doc = new OPCParser(pkg1); - doc.parse(new TestFactory()); + // Should not be able to write to an output stream that has been closed + // FIXME: A better exception class (IOException?) and message should be raised + // indicating that the document could not be written because the output stream is closed. + // see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)} + OpenXML4JRuntimeException e = assertThrows(OpenXML4JRuntimeException.class, () -> doc.write(out), + "Should not be able to write to an output stream that has been closed."); + assertTrue(e.getMessage().matches("Fail to save: an error occurs while saving the package : " + + "The part .+ failed to be saved in the stream with marshaller .+")); - traverse(doc); + // Should not be able to write a document that has been closed + doc.close(); + IOException e2 = assertThrows(IOException.class, () -> doc.write(new NullOutputStream()), + "Should not be able to write a document that has been closed."); + assertEquals("Cannot write data, document seems to have been closed already", e2.getMessage()); - File tmp = TempFile.createTempFile("poi-ooxml", ".tmp"); - FileOutputStream out = new FileOutputStream(tmp); - doc.write(out); - out.close(); - - // Should not be able to write to an output stream that has been closed - try { - doc.write(out); - fail("Should not be able to write to an output stream that has been closed."); - } catch (final OpenXML4JRuntimeException e) { - // FIXME: A better exception class (IOException?) and message should be raised - // indicating that the document could not be written because the output stream is closed. - // see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)} - if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) { - // expected - } else { - throw e; + // Should be able to close a document multiple times, though subsequent closes will have no effect. } - } - - // Should not be able to write a document that has been closed - doc.close(); - try { - doc.write(new NullOutputStream()); - fail("Should not be able to write a document that has been closed."); - } catch (final IOException e) { - if (e.getMessage().equals("Cannot write data, document seems to have been closed already")) { - // expected - } else { - throw e; - } - } - - // Should be able to close a document multiple times, though subsequent closes will have no effect. - doc.close(); - @SuppressWarnings("resource") - OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath()); - doc = new OPCParser(pkg1); - try { - doc.parse(new TestFactory()); - traverse(doc); + try (OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath()); + OPCParser doc = new OPCParser(pkg1)) { + doc.parse(new TestFactory()); + traverse(doc); - assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size()); + assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size()); - ArrayList l1 = pkg1.getParts(); - ArrayList l2 = pkg2.getParts(); + ArrayList l1 = pkg1.getParts(); + ArrayList l2 = pkg2.getParts(); - assertEquals(l1.size(), l2.size()); - for (int i=0; i < l1.size(); i++){ - PackagePart p1 = l1.get(i); - PackagePart p2 = l2.get(i); + assertEquals(l1.size(), l2.size()); + for (int i = 0; i < l1.size(); i++) { + PackagePart p1 = l1.get(i); + PackagePart p2 = l2.get(i); - assertEquals(p1.getContentType(), p2.getContentType()); - assertEquals(p1.hasRelationships(), p2.hasRelationships()); - if(p1.hasRelationships()){ - assertEquals(p1.getRelationships().size(), p2.getRelationships().size()); + assertEquals(p1.getContentType(), p2.getContentType()); + assertEquals(p1.hasRelationships(), p2.hasRelationships()); + if (p1.hasRelationships()) { + assertEquals(p1.getRelationships().size(), p2.getRelationships().size()); + } + assertEquals(p1.getPartName(), p2.getPartName()); } - assertEquals(p1.getPartName(), p2.getPartName()); } - } finally { - doc.close(); - pkg1.close(); - pkg2.close(); } } @Test public void testPPTX() throws Exception { - POIDataSamples pds = POIDataSamples.getSlideShowInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("PPTWithAttachments.pptm"))); + assertReadWrite(POIDataSamples.getSlideShowInstance(), "PPTWithAttachments.pptm"); } @Test public void testXLSX() throws Exception { - POIDataSamples pds = POIDataSamples.getSpreadSheetInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("ExcelWithAttachments.xlsm"))); + assertReadWrite(POIDataSamples.getSpreadSheetInstance(), "ExcelWithAttachments.xlsm"); } @Test public void testDOCX() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"))); + assertReadWrite(POIDataSamples.getDocumentInstance(), "WordWithAttachments.docx"); } @Test public void testRelationOrder() throws Exception { POIDataSamples pds = POIDataSamples.getDocumentInstance(); - @SuppressWarnings("resource") - OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")); - try (OPCParser doc = new OPCParser(pkg)) { + try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx"); + OPCPackage pkg = PackageHelper.open(is); + OPCParser doc = new OPCParser(pkg)) { doc.parse(new TestFactory()); for (POIXMLDocumentPart rel : doc.getRelations()) { @@ -226,9 +209,9 @@ public final class TestPOIXMLDocument { @Test public void testGetNextPartNumber() throws Exception { POIDataSamples pds = POIDataSamples.getDocumentInstance(); - @SuppressWarnings("resource") - OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")); - try (OPCParser doc = new OPCParser(pkg)) { + try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx"); + OPCPackage pkg = PackageHelper.open(is); + OPCParser doc = new OPCParser(pkg)) { doc.parse(new TestFactory()); // Non-indexed parts: Word is taken, Excel is not @@ -272,34 +255,32 @@ public final class TestPOIXMLDocument { @Test public void testVSDX() throws Exception { POIDataSamples pds = POIDataSamples.getDiagramInstance(); - @SuppressWarnings("resource") - OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx")); - POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - part.close(); + try (InputStream is = pds.openResourceAsStream("test.vsdx"); + OPCPackage open = PackageHelper.open(is); + POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT)) { + assertNotNull(part); + assertEquals(0, part.getRelationCounter()); + } } @Test public void testVSDXPart() throws IOException { POIDataSamples pds = POIDataSamples.getDiagramInstance(); - OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx")); + try (InputStream is = pds.openResourceAsStream("test.vsdx"); + OPCPackage open = PackageHelper.open(is)) { - POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); + POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - - open.close(); + assertNotNull(part); + assertEquals(0, part.getRelationCounter()); + } } - @Test(expected=POIXMLException.class) + @Test public void testInvalidCoreRel() throws IOException { POIDataSamples pds = POIDataSamples.getDiagramInstance(); - try (OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"))) { - new POIXMLDocumentPart(open, "somethingillegal"); + assertThrows(POIXMLException.class, () -> new POIXMLDocumentPart(open, "somethingillegal")); } } @@ -316,23 +297,20 @@ public final class TestPOIXMLDocument { } @Test - public void testOSGIClassLoading() { + public void testOSGIClassLoading() throws IOException { + byte[] data; + try (InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx")) { + data = IOUtils.toByteArray(is); + } + // the schema type loader is cached per thread in POIXMLTypeLoader. // So create a new Thread and change the context class loader (which would normally be used) // to not contain the OOXML classes - Runnable run = () -> { - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx"); - XMLSlideShow ppt = null; - try { - ppt = new XMLSlideShow(is); - ppt.getSlides().get(0).getShapes(); - } catch (IOException e) { - fail("failed to load XMLSlideShow"); - } finally { - IOUtils.closeQuietly(ppt); - IOUtils.closeQuietly(is); - } - }; + Runnable run = () -> assertDoesNotThrow(() -> { + try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(data))) { + assertNotNull(ppt.getSlides().get(0).getShapes()); + }} + ); ClassLoader cl = getClass().getClassLoader(); UncaughtHandler uh = new UncaughtHandler(); @@ -347,14 +325,10 @@ public final class TestPOIXMLDocument { ta[i].start(); } for (Thread thread : ta) { - try { - thread.join(); - } catch (InterruptedException e) { - fail("failed to join thread"); - } + assertDoesNotThrow((Executable) thread::join, "failed to join thread"); } } - assertFalse("Should not have an exception now, but had " + uh.e, uh.hasException()); + assertFalse(uh.hasException(), "Should not have an exception now, but had " + uh.e); } private static class UncaughtHandler implements UncaughtExceptionHandler { @@ -362,7 +336,6 @@ public final class TestPOIXMLDocument { public synchronized void uncaughtException(Thread t, Throwable e) { this.e = e; - } public synchronized boolean hasException() { diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java index ba0acca5c8..55441a03df 100644 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java +++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java @@ -17,36 +17,33 @@ package org.apache.poi.ooxml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 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.util.Calendar; import java.util.Date; import java.util.Optional; import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 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.WorkbookFactory; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Test setting extended and custom OOXML properties @@ -57,7 +54,7 @@ public final class TestPOIXMLProperties { private POIXMLProperties _props; private CoreProperties _coreProperties; - @Before + @BeforeEach public void setUp() throws IOException { sampleDoc = XWPFTestDataSamples.openSampleDocument("documentProperties.docx"); sampleNoThumb = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); @@ -68,7 +65,7 @@ public final class TestPOIXMLProperties { assertNotNull(_props); } - @After + @AfterEach public void closeResources() throws Exception { sampleDoc.close(); sampleNoThumb.close(); @@ -158,53 +155,48 @@ public final class TestPOIXMLProperties { */ @Test public void testCustomProperties() throws Exception { - POIXMLDocument wb1 = new XSSFWorkbook(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties(); - customProps.addProperty("test-1", "string val"); - customProps.addProperty("test-2", 1974); - customProps.addProperty("test-3", 36.6); - //adding a duplicate - try { + POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties(); + customProps.addProperty("test-1", "string val"); + customProps.addProperty("test-2", 1974); customProps.addProperty("test-3", 36.6); - fail("expected exception"); - } catch(IllegalArgumentException e){ + //adding a duplicate + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> customProps.addProperty("test-3", 36.6)); assertEquals("A property with this name already exists in the custom properties", e.getMessage()); + customProps.addProperty("test-4", true); + + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps = + wb2.getProperties().getCustomProperties().getUnderlyingProperties(); + assertEquals(4, ctProps.sizeOfPropertyArray()); + org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p; + + p = ctProps.getPropertyArray(0); + assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); + assertEquals("test-1", p.getName()); + assertEquals("string val", p.getLpwstr()); + assertEquals(2, p.getPid()); + + p = ctProps.getPropertyArray(1); + assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); + assertEquals("test-2", p.getName()); + assertEquals(1974, p.getI4()); + assertEquals(3, p.getPid()); + + p = ctProps.getPropertyArray(2); + assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); + assertEquals("test-3", p.getName()); + assertEquals(36.6, p.getR8(), 0); + assertEquals(4, p.getPid()); + + p = ctProps.getPropertyArray(3); + assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); + assertEquals("test-4", p.getName()); + assertTrue(p.getBool()); + assertEquals(5, p.getPid()); + } } - customProps.addProperty("test-4", true); - - POIXMLDocument wb2 = XSSFTestDataSamples.writeOutAndReadBack((XSSFWorkbook)wb1); - wb1.close(); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps = - wb2.getProperties().getCustomProperties().getUnderlyingProperties(); - assertEquals(4, ctProps.sizeOfPropertyArray()); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p; - - p = ctProps.getPropertyArray(0); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-1", p.getName()); - assertEquals("string val", p.getLpwstr()); - assertEquals(2, p.getPid()); - - p = ctProps.getPropertyArray(1); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-2", p.getName()); - assertEquals(1974, p.getI4()); - assertEquals(3, p.getPid()); - - p = ctProps.getPropertyArray(2); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-3", p.getName()); - assertEquals(36.6, p.getR8(), 0); - assertEquals(4, p.getPid()); - - p = ctProps.getPropertyArray(3); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-4", p.getName()); - assertTrue(p.getBool()); - assertEquals(5, p.getPid()); - - wb2.close(); } @Test @@ -246,7 +238,7 @@ public final class TestPOIXMLProperties { @Test public void testGetSetRevision() { String revision = _coreProperties.getRevision(); - assertTrue("Revision number is 1", Integer.parseInt(revision) > 1); + assertTrue(Integer.parseInt(revision) > 1, "Revision number is 1"); _coreProperties.setRevision("20"); assertEquals("20", _coreProperties.getRevision()); _coreProperties.setRevision("20xx"); @@ -264,17 +256,17 @@ public final class TestPOIXMLProperties { public static boolean dateTimeEqualToUTCString(Date dateTime, String utcString) { Calendar utcCalendar = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); utcCalendar.setTimeInMillis(dateTime.getTime()); - String dateTimeUtcString = utcCalendar.get(Calendar.YEAR) + "-" + - zeroPad((utcCalendar.get(Calendar.MONTH)+1)) + "-" + - zeroPad(utcCalendar.get(Calendar.DAY_OF_MONTH)) + "T" + + String dateTimeUtcString = utcCalendar.get(Calendar.YEAR) + "-" + + zeroPad((utcCalendar.get(Calendar.MONTH)+1)) + "-" + + zeroPad(utcCalendar.get(Calendar.DAY_OF_MONTH)) + "T" + zeroPad(utcCalendar.get(Calendar.HOUR_OF_DAY)) + ":" + - zeroPad(utcCalendar.get(Calendar.MINUTE)) + ":" + + zeroPad(utcCalendar.get(Calendar.MINUTE)) + ":" + zeroPad(utcCalendar.get(Calendar.SECOND)) + "Z"; return utcString.equals(dateTimeUtcString); } - @Ignore("Fails to add some of the thumbnails, needs more investigation") + @Disabled("Fails to add some of the thumbnails, needs more investigation") @Test public void testThumbnails() throws Exception { POIXMLProperties noThumbProps = sampleNoThumb.getProperties(); @@ -329,7 +321,7 @@ public final class TestPOIXMLProperties { @Test public void testBug60977() throws IOException { - + try (final XSSFWorkbook workbook = new XSSFWorkbook()) { final Sheet sheet = workbook.createSheet("sheet"); final Row row = sheet.createRow(0); @@ -346,24 +338,24 @@ public final class TestPOIXMLProperties { XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertNotNull(wbBack); // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull("First writeOutAndReadBack", wbBack.getProperties()); - assertEquals("First prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr()); + assertNotNull(wbBack.getProperties(), "First writeOutAndReadBack"); + assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "First prop check"); customProperties.addProperty(propName + "1", propValue); wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertNotNull(wbBack); // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull("Second writeOutAndReadBack", wbBack.getProperties()); - assertEquals("Second prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr()); - assertEquals("Second prop check1", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr()); + assertNotNull(wbBack.getProperties(), "Second writeOutAndReadBack"); + assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Second prop check"); + assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Second prop check1"); wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertNotNull(wbBack); // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull("Third writeOutAndReadBack", wbBack.getProperties()); - assertEquals("Third prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr()); - assertEquals("Third prop check1", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr()); - + assertNotNull(wbBack.getProperties(), "Third writeOutAndReadBack"); + assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Third prop check"); + assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Third prop check1"); + /* Manual test to write out the file more than once: File test1 = File.createTempFile("test1", ".xlsx", new File("C:\\temp")); File test2 = File.createTempFile("test2", ".xlsx", new File("C:\\temp")); @@ -379,7 +371,7 @@ public final class TestPOIXMLProperties { try (final java.io.FileOutputStream fs = new java.io.FileOutputStream(test2)) { workbook.write(fs); } - + try (final XSSFWorkbook wb = new XSSFWorkbook(test2)) { assertNotNull(wb.getProperties()); } catch (InvalidFormatException e) { diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java index 6a8091cf8e..7913bfa283 100644 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java @@ -17,9 +17,9 @@ package org.apache.poi.ooxml; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.POIDataSamples; import org.apache.poi.ooxml.extractor.POIXMLPropertiesTextExtractor; @@ -28,7 +28,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xslf.usermodel.XSLFSlideShow; import org.apache.poi.xssf.extractor.XSSFExcelExtractor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXMLPropertiesTextExtractor { private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java deleted file mode 100644 index 7b98afd972..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestContentType.class - , TestFileHelper.class - , TestListParts.class - , TestPackage.class - , TestPackageCoreProperties.class - , TestPackagePartName.class - , TestPackageThumbnail.class - , TestPackagingURIHelper.class - , TestRelationships.class -}) -public final class AllOpenXML4JTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java index 4995fcb2ef..6a725b3d47 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java @@ -17,11 +17,11 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.io.InputStream; @@ -30,7 +30,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.internal.ContentType; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for content type (ContentType class). @@ -81,12 +81,8 @@ public final class TestContentType { "te{xt/xml", "tex}t/xml", "te xt/xml", "text" + (char) 9 + "/xml", "text xml", " text/xml "}; for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); + assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), + "Must have fail for content type: '" + contentType + "' !"); } } @@ -120,12 +116,8 @@ public final class TestContentType { "text/\u0080" // characters above ASCII are not allowed }; for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); + assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), + "Must have fail for content type: '" + contentType + "' !"); } } @@ -138,12 +130,8 @@ public final class TestContentType { public void testContentTypeCommentFailure() { String[] contentTypesToTest = new String[]{"text/xml(comment)"}; for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); + assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), + "Must have fail for content type: '" + contentType + "' !"); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java index d15281b2d3..f32286dc71 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java @@ -17,13 +17,13 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.util.TreeMap; import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test TestFileHelper class. diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java index 88d45f75de..7f0b1fdeb8 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java @@ -17,8 +17,8 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -28,8 +28,8 @@ import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestListParts { private static final POILogger logger = POILogFactory.getLogger(TestListParts.class); @@ -38,7 +38,7 @@ public final class TestListParts { private TreeMap values; - @Before + @BeforeEach public void setUp() throws Exception { values = new TreeMap<>(); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java index 5f95abd1ca..aaff77ecbb 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java @@ -22,13 +22,14 @@ import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -70,12 +71,12 @@ import org.apache.poi.openxml4j.exceptions.InvalidOperationException; import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException; import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; import org.apache.poi.openxml4j.opc.internal.FileHelper; import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; import org.apache.poi.openxml4j.opc.internal.ZipHelper; import org.apache.poi.openxml4j.util.ZipSecureFile; +import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; @@ -88,10 +89,9 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.xmlbeans.XmlException; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -288,7 +288,7 @@ public final class TestPackage { for (int i = 0; i < nodeCount; i++) { Element element = (Element) nodeList.item(i); String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME); - assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/'); + assertTrue(value.charAt(0) != '/', "Root target must not start with a leading slash ('/'): " + value); } } @@ -340,11 +340,7 @@ public final class TestPackage { StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); // Save and close - try { - pkg.close(); - } catch (IOException e) { - fail(); - } + assertDoesNotThrow(pkg::close); ZipFileAssert.assertEquals(expectedFile, targetFile); assertTrue(targetFile.delete()); @@ -406,7 +402,7 @@ public final class TestPackage { * TODO: fix and enable */ @Test - @Ignore + @Disabled public void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException { String originalFile = getSampleFileName("TestPackageCommon.docx"); File targetFile = getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); @@ -519,12 +515,8 @@ public final class TestPackage { FileHelper.copyFile(origFile, tempFile); try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { // Save it to the same file - not allowed - try { - p.save(tempFile); - fail("You shouldn't be able to call save(File) to overwrite the current file"); - } catch(InvalidOperationException e) { - // expected here - } + assertThrows(InvalidOperationException.class, () -> p.save(tempFile), + "You shouldn't be able to call save(File) to overwrite the current file"); } // Delete it assertTrue(tempFile.delete()); @@ -668,12 +660,12 @@ public final class TestPackage { private void handleNonOOXML(String file, Class exception, String... messageParts) throws IOException { try (InputStream stream = xlsSamples.openResourceAsStream(file)) { - ThrowingRunnable[] trs = { + Executable[] trs = { () -> OPCPackage.open(stream), () -> OPCPackage.open(xlsSamples.getFile(file)) }; - for (ThrowingRunnable tr : trs) { - Exception ex = assertThrows("Shouldn't be able to open "+file, exception, tr); + for (Executable tr : trs) { + Exception ex = assertThrows(exception, tr, "Shouldn't be able to open "+file); Stream.of(messageParts).forEach(mp -> assertTrue(ex.getMessage().contains(mp))); } } @@ -792,7 +784,7 @@ public final class TestPackage { return false; } - private void openXmlBombFile(String file) throws IOException, OpenXML4JException, XmlException { + private void openXmlBombFile(String file) throws IOException { final double minInf = ZipSecureFile.getMinInflateRatio(); ZipSecureFile.setMinInflateRatio(0.002); try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) { @@ -827,7 +819,7 @@ public final class TestPackage { } @Test - public void zipBombCheckSizesSizeTooBig() throws IOException, EncryptedDocumentException { + public void zipBombCheckSizesSizeTooBig() throws EncryptedDocumentException { POIXMLException ex = assertThrows( POIXMLException.class, () -> getZipStatsAndConsume((max_size, min_ratio) -> { @@ -896,10 +888,10 @@ public final class TestPackage { } // bug 60128 - @Test(expected=NotOfficeXmlFileException.class) - public void testCorruptFile() throws InvalidFormatException { + @Test + public void testCorruptFile() { File file = getSampleFile("invalid.xlsx"); - OPCPackage.open(file, PackageAccess.READ); + assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(file, PackageAccess.READ)); } private interface CountingStream { @@ -944,16 +936,19 @@ public final class TestPackage { break; } } - assertTrue("Core not found in " + p.getParts(), foundCoreProps); - assertFalse("Document should not be found in " + p.getParts(), foundDocument); - assertFalse("Theme1 should not found in " + p.getParts(), foundTheme1); + assertTrue(foundCoreProps, "Core not found in " + p.getParts()); + assertFalse(foundDocument, "Document should not be found in " + p.getParts()); + assertFalse(foundTheme1, "Theme1 should not found in " + p.getParts()); } } @Test public void unparseableCentralDirectory() throws IOException { File f = getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); - SlideShowFactory.create(f, null, true).close(); + try (SlideShow ppt = SlideShowFactory.create(f, null, true)) { + assertNotNull(ppt); + assertNotNull(ppt.getSlides().get(0)); + } } @Test @@ -967,15 +962,13 @@ public final class TestPackage { } // feed the corrupted zip file to OPCPackage - try { - OPCPackage.open(tmp, PackageAccess.READ); - } catch (Exception e) { - // expected: the zip file is invalid - // this test does not care if open() throws an exception or not. - } + // expected: the zip file is invalid + // this test does not care if open() throws an exception or not. + assertThrows(Exception.class, () -> OPCPackage.open(tmp, PackageAccess.READ)); + // If the stream is not closed on exception, it will keep a file descriptor to tmp, // and requests to the OS to delete the file will fail. - assertTrue("Can't delete tmp file", tmp.delete()); + assertTrue(tmp.delete(), "Can't delete tmp file"); } /** @@ -984,30 +977,31 @@ public final class TestPackage { * stream / file the broken file is being read from. * See bug #60128 for more */ - @Test(expected = NotOfficeXmlFileException.class) + @Test public void testTidyStreamOnInvalidFile1() throws Exception { openInvalidFile("SampleSS.ods", false); } - @Test(expected = NotOfficeXmlFileException.class) + @Test public void testTidyStreamOnInvalidFile2() throws Exception { openInvalidFile("SampleSS.ods", true); } - @Test(expected = NotOfficeXmlFileException.class) + @Test public void testTidyStreamOnInvalidFile3() throws Exception { openInvalidFile("SampleSS.txt", false); } - @Test(expected = NotOfficeXmlFileException.class) + @Test public void testTidyStreamOnInvalidFile4() throws Exception { openInvalidFile("SampleSS.txt", true); } - @Test(expected = InvalidFormatException.class) + @Test public void testBug62592() throws Exception { - InputStream is = openSampleStream("62592.thmx"); - /*OPCPackage p =*/ OPCPackage.open(is); + try (InputStream is = openSampleStream("62592.thmx")) { + assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); + } } @Test @@ -1049,20 +1043,23 @@ public final class TestPackage { - private static void openInvalidFile(final String name, final boolean useStream) throws IOException, InvalidFormatException { - ZipPackage pkgTest = null; + private static void openInvalidFile(final String name, final boolean useStream) throws IOException { + ZipPackage[] pkgTest = { null }; try (final InputStream is = (useStream) ? xlsSamples.openResourceAsStream(name) : null) { - try (final ZipPackage pkg = (useStream) ? new ZipPackage(is, PackageAccess.READ) : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) { - pkgTest = pkg; - assertNotNull(pkg.getZipArchive()); - assertFalse(pkg.getZipArchive().isClosed()); - pkg.getParts(); - fail("Shouldn't work"); - } + assertThrows(NotOfficeXmlFileException.class, () -> { + try (final ZipPackage pkg = (useStream) + ? new ZipPackage(is, PackageAccess.READ) + : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) { + pkgTest[0] = pkg; + assertNotNull(pkg.getZipArchive()); + assertFalse(pkg.getZipArchive().isClosed()); + pkg.getParts(); + } + }); } finally { - if (pkgTest != null) { - assertNotNull(pkgTest.getZipArchive()); - assertTrue(pkgTest.getZipArchive().isClosed()); + if (pkgTest[0] != null) { + assertNotNull(pkgTest[0].getZipArchive()); + assertTrue(pkgTest[0].getZipArchive().isClosed()); } } } @@ -1075,7 +1072,7 @@ public final class TestPackage { Files.copy(testFile, tmpFile); int numPartsBefore = 0; - String md5Before = Files.hash(tmpFile, Hashing.md5()).toString(); + String md5Before = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); RuntimeException ex = null; try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)) @@ -1091,11 +1088,11 @@ public final class TestPackage { ex = e; } // verify there was an exception while closing the file - assertNotNull("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex); + assertNotNull(ex, "Fail to save: an error occurs while saving the package : Bugzilla 63029"); assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage()); // assert that md5 after closing is the same, i.e. the source is left intact - String md5After = Files.hash(tmpFile, Hashing.md5()).toString(); + String md5After = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); assertEquals(md5Before, md5After); // try to read the source file once again diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java index 7f726d63c4..441f24d9ad 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java @@ -33,11 +33,11 @@ import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public final class TestPackageCoreProperties { /** @@ -204,7 +204,7 @@ public final class TestPackageCoreProperties { props.setModifiedProperty(strDate); assertEquals(strDate, props.getModifiedPropertyString()); assertEquals(date, props.getModifiedProperty().get()); - + // Tidy pkg.close(); } @@ -229,57 +229,55 @@ public final class TestPackageCoreProperties { @Test public void testEntitiesInCoreProps_56164() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is); - is.close(); + try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml"); + OPCPackage p = OPCPackage.open(is)) { - // Should have 3 root relationships - boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; - for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; + // Should have 3 root relationships + boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; + for (PackageRelationship pr : p.getRelationships()) { + if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) + foundDocRel = true; + if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) + foundCorePropRel = true; + if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) + foundExtPropRel = true; + } + assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships()); + assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships()); + assertTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships()); + + // Get the Core Properties + PackagePropertiesPart props = (PackagePropertiesPart) p.getPackageProperties(); + + // used to resolve a value but now we ignore DTD entities for security reasons + assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent()); } - assertTrue("Core/Doc Relationship not found in " + p.getRelationships(), foundDocRel); - assertTrue("Core Props Relationship not found in " + p.getRelationships(), foundCorePropRel); - assertTrue("Ext Props Relationship not found in " + p.getRelationships(), foundExtPropRel); - - // Get the Core Properties - PackagePropertiesPart props = (PackagePropertiesPart)p.getPackageProperties(); - - // used to resolve a value but now we ignore DTD entities for security reasons - assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent()); - - p.close(); } - + @Test public void testListOfCustomProperties() throws Exception { File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm"); OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); XSSFWorkbook wb = new XSSFWorkbook(pkg); - + assertNotNull(wb.getProperties()); assertNotNull(wb.getProperties().getCustomProperties()); - + for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) { assertNotNull(prop); } - + wb.close(); pkg.close(); } - + @Test public void testAlternateCorePropertyTimezones() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx"); OPCPackage pkg = OPCPackage.open(is); PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); is.close(); - + // We need predictable dates for testing! SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); df.setTimeZone(LocaleUtil.TIMEZONE_UTC); @@ -287,37 +285,37 @@ public final class TestPackageCoreProperties { // Check text properties first assertEquals("Lorem Ipsum", props.getTitleProperty().get()); assertEquals("Apache POI", props.getCreatorProperty().get()); - + // Created at has a +3 timezone and milliseconds // 2006-10-13T18:06:00.123+03:00 // = 2006-10-13T15:06:00.123+00:00 assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString()); assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().get())); - + // Modified at has a -13 timezone but no milliseconds // 2007-06-20T07:59:00-13:00 // = 2007-06-20T20:59:00-13:00 assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString()); assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().get())); - - + + // Ensure we can change them with other timezones and still read back OK props.setCreatedProperty("2007-06-20T20:57:00+13:00"); props.setModifiedProperty("2007-06-20T20:59:00.123-13:00"); - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); pkg.save(baos); pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray())); - + // Check text properties first - should be unchanged assertEquals("Lorem Ipsum", props.getTitleProperty().get()); assertEquals("Apache POI", props.getCreatorProperty().get()); - + // Check the updated times // 2007-06-20T20:57:00+13:00 // = 2007-06-20T07:57:00Z assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().get())); - + // 2007-06-20T20:59:00.123-13:00 // = 2007-06-21T09:59:00.123Z assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get())); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java index bb900b1e5c..78fe47a4ca 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java @@ -17,9 +17,9 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestPackagePartName { diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java index e9295970cd..81a0afdf44 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java @@ -17,13 +17,14 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test the addition of thumbnail in a package. @@ -42,25 +43,19 @@ public final class TestPackageThumbnail { File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); // Open package - OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); - try { + try (OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE)) { p.addThumbnail(imagePath); // Save the package in the output directory p.save(outputFile); // Open the newly created file to check core properties saved values. - OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); - try { - if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) - .size() == 0) - fail("Thumbnail not added to the package !"); - } finally { - p2.revert(); - p2.close(); + try (OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ)) { + assertNotEquals(0, p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL).size(), + "Thumbnail not added to the package !"); + p2.revert(); } - } finally { - p.revert(); - assertTrue(outputFile.delete()); + p.revert(); } + assertTrue(outputFile.delete()); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java index 3bbce458cb..71689cc200 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.net.URI; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestPackagingURIHelper { @@ -92,8 +92,7 @@ public class TestPackagingURIHelper { // Relative part name PackagePartName relativeName = PackagingURIHelper.createPartName( "media/image1.gif", partBase); - assertEquals("The part name must be equal to " - + partNameToValid.getName(), partNameToValid, relativeName); + assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName()); pkg.revert(); } @@ -113,8 +112,7 @@ public class TestPackagingURIHelper { // Relative part name PackagePartName relativeName = PackagingURIHelper.createPartName( new URI("media/image1.gif"), partBase); - assertEquals("The part name must be equal to " - + partNameToValid.getName(), partNameToValid, relativeName); + assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName()); pkg.revert(); } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java index 843c049ca7..4c681e8623 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -19,10 +19,10 @@ package org.apache.poi.openxml4j.opc; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayOutputStream; @@ -33,7 +33,7 @@ import java.util.regex.Pattern; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestRelationships { @@ -66,7 +66,7 @@ public class TestRelationships { assertNotNull(rel); PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); PackagePart sheetPart = pkg.getPart(relName); - assertEquals("Number of relationships1 for " + sheetPart.getPartName(), 1, sheetPart.getRelationships().size()); + assertEquals(1, sheetPart.getRelationships().size(), "Number of relationships1 for " + sheetPart.getPartName()); } } } @@ -430,16 +430,13 @@ public class TestRelationships { // Should have 3 root relationships boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; + foundDocRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT); + foundCorePropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES); + foundExtPropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES); } - assertEquals("Core/Doc Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundDocRel); - assertEquals("Core Props Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundCorePropRel); - assertEquals("Ext Props Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundExtPropRel); + assertEquals(isOldXercesActive(), foundDocRel, "Core Doc Relationship not found in " + p.getRelationships()); + assertEquals(isOldXercesActive(), foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships()); + assertEquals(isOldXercesActive(), foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships()); } } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java index 3a17b79851..fcc6e3cff8 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java @@ -17,11 +17,12 @@ package org.apache.poi.openxml4j.opc; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +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.BufferedInputStream; import java.io.ByteArrayOutputStream; @@ -34,7 +35,7 @@ import java.util.TreeMap; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.poi.util.IOUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.Comparison; @@ -55,14 +56,14 @@ public final class ZipFileAssert { TreeMap file1, TreeMap file2) { Set listFile1 = file1.keySet(); - Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size()); + Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:"); for (String fileName : listFile1) { // extract the contents for both ByteArrayOutputStream contain1 = file1.get(fileName); ByteArrayOutputStream contain2 = file2.get(fileName); - assertNotNull(fileName + " not found in 2nd zip", contain2); + assertNotNull(contain2, fileName + " not found in 2nd zip"); // no need to check for contain1. The key come from it if (fileName.matches(".*\\.(xml|rels)$")) { @@ -75,11 +76,11 @@ public final class ZipFileAssert { withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()). withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)). build(); - assertFalse(fileName+": "+diff.toString(), diff.hasDifferences()); + assertFalse(diff.hasDifferences(), fileName+": "+diff.toString()); } else { // not xml, may be an image or other binary format - Assert.assertEquals(fileName + " does not have the same size in both zip:", contain1.size(), contain2.size()); - assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray()); + Assertions.assertEquals(contain1.size(), contain2.size(), fileName + " does not have the same size in both zip:"); + assertArrayEquals(contain1.toByteArray(), contain2.toByteArray(), "contents differ"); } } } @@ -126,21 +127,12 @@ public final class ZipFileAssert { assertNotNull(expected); assertNotNull(actual); - assertTrue("File does not exist [" + expected.getAbsolutePath() - + "]", expected.exists()); - assertTrue("File does not exist [" + actual.getAbsolutePath() - + "]", actual.exists()); + assertTrue(expected.exists(), "File does not exist [" + expected.getAbsolutePath() + "]"); + assertTrue(actual.exists(), "File does not exist [" + actual.getAbsolutePath() + "]"); + assertTrue(expected.canRead(), "Expected file not readable"); + assertTrue(actual.canRead(), "Actual file not readable"); - assertTrue("Expected file not readable", expected.canRead()); - assertTrue("Actual file not readable", actual.canRead()); - - try { - TreeMap file1 = decompress(expected); - TreeMap file2 = decompress(actual); - equals(file1, file2); - } catch (IOException e) { - fail(e.toString()); - } + assertDoesNotThrow(() -> equals(decompress(expected), decompress(actual))); } private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator { diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java index 216d577beb..b0a7630255 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java @@ -19,11 +19,12 @@ package org.apache.poi.openxml4j.opc.compliance; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -44,7 +45,7 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test core properties Open Packaging Convention compliance. @@ -90,20 +91,12 @@ public final class TestOPCComplianceCoreProperties { pkg.revert(); } - private static String extractInvalidFormatMessage(String sampleNameSuffix) { - InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix); - OPCPackage pkg; - try { - pkg = OPCPackage.open(is); - } catch (InvalidFormatException e) { - // no longer required for successful test + private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException { + try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) { + InvalidFormatException e = assertThrows(InvalidFormatException.class, + () -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown"); return e.getMessage(); - } catch (IOException e) { - throw new RuntimeException(e); } - pkg.revert(); - fail("expected OPC compliance exception was not thrown"); - return null; } /** @@ -112,12 +105,12 @@ public final class TestOPCComplianceCoreProperties { @Test public void testOnlyOneCorePropertiesPart() throws Exception { // We have relaxed this check, so we can read the file anyway - try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_" + "OnlyOneCorePropertiesPartFAIL.docx"); - OPCPackage pkg = OPCPackage.open(is)) { - assertNotNull(pkg); - } catch (Exception e) { - fail("M4.1 should be being relaxed"); - } + assertDoesNotThrow(() -> { + try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx"); + OPCPackage pkg = OPCPackage.open(is)) { + assertNotNull(pkg); + } + }, "M4.1 should be being relaxed"); // We will use the first core properties, and ignore the others @@ -148,55 +141,41 @@ public final class TestOPCComplianceCoreProperties { * Test M4.1 rule. */ @Test - public void testOnlyOneCorePropertiesPart_AddRelationship() { - InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); - OPCPackage pkg; - try { - pkg = OPCPackage.open(is); - } catch (InvalidFormatException | IOException e) { - throw new RuntimeException(e); - } - URI partUri = createURI("/docProps/core2.xml"); - try { - pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_PROPERTIES); - // no longer fail on compliance error - //fail("expected OPC compliance exception was not thrown"); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } catch (InvalidOperationException e) { - // expected during successful test + public void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException { + try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { + OPCPackage pkg = OPCPackage.open(is); + URI partUri = createURI("/docProps/core2.xml"); + InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> + pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES), + "expected OPC compliance exception was not thrown" + ); assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage()); + pkg.revert(); } - pkg.revert(); } /** * Test M4.1 rule. */ @Test - public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException { + public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException { String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"; - OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); + try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { - URI partUri = createURI("/docProps/core2.xml"); - try { - pkg.createPart(PackagingURIHelper.createPartName(partUri), - ContentTypes.CORE_PROPERTIES_PART); - // no longer fail on compliance error - //fail("expected OPC compliance exception was not thrown"); - } catch (InvalidOperationException e) { - // expected during successful test + URI partUri = createURI("/docProps/core2.xml"); + InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> + pkg.createPart(PackagingURIHelper.createPartName(partUri), ContentTypes.CORE_PROPERTIES_PART), + "expected OPC compliance exception was not thrown"); assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage()); + pkg.revert(); } - pkg.revert(); } /** * Test M4.2 rule. */ @Test - public void testDoNotUseCompatibilityMarkup() { + public void testDoNotUseCompatibilityMarkup() throws IOException { String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx"); assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg); } @@ -205,7 +184,7 @@ public final class TestOPCComplianceCoreProperties { * Test M4.3 rule. */ @Test - public void testDCTermsNamespaceLimitedUse() { + public void testDCTermsNamespaceLimitedUse() throws IOException { String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx"); assertEquals("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: and Consumers shall consider a document element that violates this constraint to be an error.", msg); } @@ -214,7 +193,7 @@ public final class TestOPCComplianceCoreProperties { * Test M4.4 rule. */ @Test - public void testUnauthorizedXMLLangAttribute() { + public void testUnauthorizedXMLLangAttribute() throws IOException { String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx"); assertEquals("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg); } @@ -223,7 +202,7 @@ public final class TestOPCComplianceCoreProperties { * Test M4.5 rule. */ @Test - public void testLimitedXSITypeAttribute_NotPresent() { + public void testLimitedXSITypeAttribute_NotPresent() throws IOException { String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx"); assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg); } @@ -232,7 +211,7 @@ public final class TestOPCComplianceCoreProperties { * Test M4.5 rule. */ @Test - public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() { + public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() throws IOException { String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx"); assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg); } @@ -244,45 +223,43 @@ public final class TestOPCComplianceCoreProperties { @Test public void testNoCoreProperties_saveNew() throws Exception { String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); - - // Verify it has empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Save and re-load ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg.revert(); - pkg = OPCPackage.open(bais); + try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { + // Verify it has empty properties + assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + assertNotNull(pkg.getPackageProperties()); + assertNotNull(pkg.getPackageProperties().getLanguageProperty()); + assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - pkg.close(); + // Save and re-load + pkg.save(baos); + pkg.revert(); + } + + try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { + // An Empty Properties part has been added in the save/load + assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + assertNotNull(pkg.getPackageProperties()); + assertNotNull(pkg.getPackageProperties().getLanguageProperty()); + assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); + } // Open a new copy of it - pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); + try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { + // Save and re-load, without having touched the properties yet + baos.reset(); + pkg.save(baos); + pkg.revert(); + } - // Save and re-load, without having touched the properties yet - baos = new ByteArrayOutputStream(); - pkg.save(baos); - pkg.revert(); - - bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - // Check that this too added empty properties without error - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); + try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { + // Check that this too added empty properties without error + assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + assertNotNull(pkg.getPackageProperties()); + assertNotNull(pkg.getPackageProperties().getLanguageProperty()); + assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); + } } /** @@ -295,37 +272,34 @@ public final class TestOPCComplianceCoreProperties { // Copy this into a temp file, so we can play with it File tmp = TempFile.createTempFile("poi-test", ".opc"); - FileOutputStream out = new FileOutputStream(tmp); - InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName); - IOUtils.copy( - in, - out); - out.close(); - in.close(); + try (FileOutputStream out = new FileOutputStream(tmp); + InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) { + IOUtils.copy(in, out); + } // Open it from that temp file - OPCPackage pkg = OPCPackage.open(tmp); + try (OPCPackage pkg = OPCPackage.open(tmp)) { - // Empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); + // Empty properties + assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + assertNotNull(pkg.getPackageProperties()); + assertNotNull(pkg.getPackageProperties().getLanguageProperty()); + assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - // Save and close - pkg.close(); + // Save and close + } // Re-open and check - pkg = OPCPackage.open(tmp); + try (OPCPackage pkg = OPCPackage.open(tmp)) { + // An Empty Properties part has been added in the save/load + assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + assertNotNull(pkg.getPackageProperties()); + assertNotNull(pkg.getPackageProperties().getLanguageProperty()); + assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Finish and tidy - pkg.revert(); + // Finish and tidy + pkg.revert(); + } assertTrue(tmp.delete()); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java index 7cf9e4b95e..5eba3cf2bf 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java @@ -17,8 +17,10 @@ package org.apache.poi.openxml4j.opc.compliance; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; import java.io.IOException; import org.apache.poi.POIDataSamples; @@ -31,42 +33,31 @@ import org.apache.poi.openxml4j.opc.PackagePartName; import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.TargetMode; -import org.junit.Test; +import org.apache.poi.util.TempFile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test Open Packaging Convention package model compliance. * * M1.11 : A package implementer shall neither create nor recognize a part with * a part name derived from another part name by appending segments to it. - * - * @author Julien Chable */ public class TestOPCCompliancePackageModel { - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - @Test - public void testPartNameDerivationAdditionFailure() { - OPCPackage pkg = OPCPackage.create("TODELETEIFEXIST.docx"); - try { - PackagePartName name = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePartName nameDerived = PackagingURIHelper - .createPartName("/word/document.xml/image1.gif"); - pkg.createPart(name, ContentTypes.XML); - pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF); - } catch (InvalidOperationException e) { - pkg.revert(); - return; - } catch (InvalidFormatException e) { - fail(e.getMessage()); + private static File TESTFILE; + + @BeforeAll + public static void setup() throws IOException { + TESTFILE = TempFile.createTempFile("TODELETEIFEXIST", ".docx"); + } + + @BeforeEach + public void tearDown() { + if (TESTFILE.exists()) { + assertTrue(TESTFILE.delete()); } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); } /** @@ -75,16 +66,32 @@ public class TestOPCCompliancePackageModel { * [M1.11] */ @Test - public void testPartNameDerivationReadingFailure() throws IOException { - String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; - try { - OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)); - } catch (InvalidFormatException e) { - return; + public void testPartNameDerivationAdditionFailure() throws InvalidFormatException, IOException { + try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { + PackagePartName name = PackagingURIHelper.createPartName("/word/document.xml"); + PackagePartName nameDerived = PackagingURIHelper.createPartName("/word/document.xml/image1.gif"); + pkg.createPart(name, ContentTypes.XML); + + assertThrows(InvalidOperationException.class, () -> pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF), + "A package implementer shall neither create nor recognize a part with a part name derived from another " + + "part name by appending segments to it. [M1.11]"); + pkg.revert(); } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); + } + + /** + * A package implementer shall neither create nor recognize a part with a + * part name derived from another part name by appending segments to it. + * [M1.11] + */ + @Test + public void testPartNameDerivationReadingFailure() { + String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; + assertThrows(InvalidFormatException.class, () -> + OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)), + "A package implementer shall neither create nor recognize a part with a part name derived from another" + + " part name by appending segments to it. [M1.11]" + ); } /** @@ -94,22 +101,17 @@ public class TestOPCCompliancePackageModel { */ @Test public void testAddPackageAlreadyAddFailure() throws Exception { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - PackagePartName name2 = null; - try { - name1 = PackagingURIHelper.createPartName("/word/document.xml"); - name2 = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); + try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { + PackagePartName name1 = PackagingURIHelper.createPartName("/word/document.xml"); + PackagePartName name2 = PackagingURIHelper.createPartName("/word/document.xml"); + + pkg.createPart(name1, ContentTypes.XML); + assertThrows(PartAlreadyExistsException.class, () -> pkg.createPart(name2, ContentTypes.XML), + "Packages shall not contain equivalent part names and package implementers shall neither create nor " + + "recognize packages with equivalent part names. [M1.12]" + ); + pkg.revert(); } - pkg.createPart(name1, ContentTypes.XML); - try { - pkg.createPart(name2, ContentTypes.XML); - } catch (PartAlreadyExistsException e) { - return; - } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); } /** @@ -119,20 +121,15 @@ public class TestOPCCompliancePackageModel { */ @Test public void testAddPackageAlreadyAddFailure2() throws Exception { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName partName = null; - try { - partName = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); - } - pkg.createPart(partName, ContentTypes.XML); - try { + try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { + PackagePartName partName = PackagingURIHelper.createPartName("/word/document.xml"); pkg.createPart(partName, ContentTypes.XML); - } catch (InvalidOperationException e) { - return; + assertThrows(InvalidOperationException.class, () -> pkg.createPart(partName, ContentTypes.XML), + "Packages shall not contain equivalent part names and package implementers shall neither create nor " + + "recognize packages with equivalent part names. [M1.12]" + ); + pkg.revert(); } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); } /** @@ -144,22 +141,15 @@ public class TestOPCCompliancePackageModel { * relationship as invalid. */ @Test - public void testAddRelationshipRelationshipsPartFailure() { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - try { - name1 = PackagingURIHelper - .createPartName("/test/_rels/document.xml.rels"); - } catch (InvalidFormatException e) { - fail("This exception should never happen !"); - } + public void testAddRelationshipRelationshipsPartFailure() throws IOException, InvalidFormatException { + try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { + PackagePartName name1 = PackagingURIHelper.createPartName("/test/_rels/document.xml.rels"); - try { - pkg.addRelationship(name1, TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_DOCUMENT); - } catch (InvalidOperationException e) { - return; + assertThrows(InvalidOperationException.class, + () -> pkg.addRelationship(name1, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT), + "The Relationships part shall not have relationships to any other part [M1.25]" + ); + pkg.revert(); } - fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java index 05e297f6d7..781d3b4f30 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java @@ -17,19 +17,20 @@ package org.apache.poi.openxml4j.opc.compliance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName; +import static org.apache.poi.openxml4j.opc.PackagingURIHelper.isValidPartName; +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.net.URI; import java.net.URISyntaxException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test part name Open Packaging Convention compliance. @@ -100,8 +101,7 @@ public final class TestOPCCompliancePartName { assertEquals("[Content_Types].xml", s); continue; } - assertFalse("This part name SHOULD NOT be valid: " + s, - PackagingURIHelper.isValidPartName(uri)); + assertFalse(isValidPartName(uri), "This part name SHOULD NOT be valid: " + s); } } @@ -110,24 +110,19 @@ public final class TestOPCCompliancePartName { */ @Test public void testValidPartNames() throws URISyntaxException { - String[] validNames = { "/xml/item1.xml", "/document.xml", - "/a/%D1%86.xml" }; - for (String s : validNames) - assertTrue("This part name SHOULD be valid: " + s, - PackagingURIHelper.isValidPartName(new URI(s))); + String[] validNames = { "/xml/item1.xml", "/document.xml", "/a/%D1%86.xml" }; + for (String s : validNames) { + assertTrue(isValidPartName(new URI(s)), "This part name SHOULD be valid: " + s); + } } /** * A part name shall not be empty. [M1.1] */ @Test - public void testEmptyPartNameFailure() throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("")); - fail("A part name shall not be empty. [M1.1]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } + public void testEmptyPartNameFailure() { + assertThrows(InvalidFormatException.class, () -> createPartName(new URI("")), + "A part name shall not be empty. [M1.1]"); } /** @@ -138,18 +133,13 @@ public final class TestOPCCompliancePartName { * A segment shall include at least one non-dot character. [M1.10] */ @Test - public void testPartNameWithInvalidSegmentsFailure() { + public void testPartNameWithInvalidSegmentsFailure() throws URISyntaxException { String[] invalidNames = { "//document.xml", "//word/document.xml", "/word//document.rels", "/word//rels//document.rels", "/xml./doc.xml", "/document.", "/./document.xml", "/word/./doc.rels", "/%2F/document.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A part name shall not have empty segments. [M1.3]", - PackagingURIHelper.isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); + for (String s : invalidNames) { + assertFalse(isValidPartName(new URI(s)), "A part name shall not have empty segments. [M1.3]"); } } @@ -158,16 +148,11 @@ public final class TestOPCCompliancePartName { * [M1.6]. */ @Test - public void testPartNameWithNonPCharCharacters() { + public void testPartNameWithNonPCharCharacters() throws URISyntaxException { String[] validNames = { "/doc&.xml" }; - try { - for (String s : validNames) - assertTrue( - "A segment shall not contain non pchar characters [M1.6] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); + for (String s : validNames) { + assertTrue(isValidPartName(new URI(s)), + "A segment shall not contain non pchar characters [M1.6] : " + s); } } @@ -175,16 +160,10 @@ public final class TestOPCCompliancePartName { * A segment shall not contain percent-encoded unreserved characters [M1.8]. */ @Test - public void testPartNameWithUnreservedEncodedCharactersFailure() { + public void testPartNameWithUnreservedEncodedCharactersFailure() throws URISyntaxException { String[] invalidNames = { "/a/docum%65nt.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A segment shall not contain percent-encoded unreserved characters [M1.8] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); + for (String s : invalidNames) { + assertFalse(isValidPartName(new URI(s)), "A segment shall not contain percent-encoded unreserved characters [M1.8] : " + s); } } @@ -192,28 +171,18 @@ public final class TestOPCCompliancePartName { * A part name shall start with a forward slash ('/') character. [M1.4] */ @Test - public void testPartNameStartsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("document.xml")); - fail("A part name shall start with a forward slash ('/') character. [M1.4]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } + public void testPartNameStartsWithAForwardSlashFailure() { + assertThrows(InvalidFormatException.class, () -> createPartName(new URI("document.xml")), + "A part name shall start with a forward slash ('/') character. [M1.4]"); } /** * A part name shall not have a forward slash as the last character. [M1.5] */ @Test - public void testPartNameEndsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("/document.xml/")); - fail("A part name shall not have a forward slash as the last character. [M1.5]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } + public void testPartNameEndsWithAForwardSlashFailure() { + assertThrows(InvalidFormatException.class, () -> createPartName(new URI("/document.xml/")), + "A part name shall not have a forward slash as the last character. [M1.5]"); } /** @@ -225,8 +194,8 @@ public final class TestOPCCompliancePartName { String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" }; for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]); + PackagePartName p1 = createPartName(partName1[i]); + PackagePartName p2 = createPartName(partName2[i]); assertEquals(p1, p2); assertEquals(0, p1.compareTo(p2)); assertEquals(p1.hashCode(), p2.hashCode()); @@ -244,8 +213,8 @@ public final class TestOPCCompliancePartName { String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" }; for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]); + PackagePartName p1 = createPartName(partName1[i]); + PackagePartName p2 = createPartName(partName2[i]); assertNotEquals(p1, p2); assertNotEquals(0, p1.compareTo(p2)); assertNotEquals(p1.hashCode(), p2.hashCode()); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java index 49dba1a091..89b3696372 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java @@ -17,9 +17,8 @@ package org.apache.poi.openxml4j.opc.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -47,8 +46,8 @@ import org.apache.poi.xssf.usermodel.XSSFPictureData; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; @@ -127,11 +126,10 @@ public final class TestContentTypeManager { /** * Test the addition then removal of content types in a package. */ - @Ignore + @Disabled @Test public void testContentTypeRemovalPackage() { // TODO - fail("test not written"); } protected byte[] toByteArray(Workbook wb) { diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java index 30fabfc1f3..31fde8f5d1 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java @@ -18,7 +18,8 @@ package org.apache.poi.openxml4j.opc.internal.marshallers; import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -27,40 +28,45 @@ import java.io.OutputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.openxml4j.opc.PackagePartName; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestZipPackagePropertiesMarshaller { - private PartMarshaller marshaller = new ZipPackagePropertiesMarshaller(); + private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller(); - @Test(expected=IllegalArgumentException.class) - public void nonZipOutputStream() throws OpenXML4JException { + private boolean marshall() throws OpenXML4JException { + return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream())); + } + + private boolean marshall(OutputStream zos) throws OpenXML4JException { + PackagePartName rootUri = PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI); + PackagePropertiesPart part = new PackagePropertiesPart(null, rootUri); + return marshaller.marshall(part, zos); + } + + + @Test + public void nonZipOutputStream() { OutputStream notAZipOutputStream = new ByteArrayOutputStream(0); - marshaller.marshall(null, notAZipOutputStream); + assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream)); } @Test public void withZipOutputStream() throws Exception { - assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipArchiveOutputStream(new ByteArrayOutputStream()))); + assertTrue(marshall()); } @Test - public void writingFails() throws Exception { - assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipArchiveOutputStream(new ByteArrayOutputStream()))); - } - - @Test(expected=OpenXML4JException.class) public void ioException() throws Exception { - marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipArchiveOutputStream(new ByteArrayOutputStream()) { - @Override - public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { - throw new IOException("TestException"); - } - }); + ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) { + @Override + public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { + throw new IOException("TestException"); + } + }; + assertThrows(OpenXML4JException.class, () -> marshall(zos)); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java b/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java index f2a3d77eef..a4d2d7b8c3 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java @@ -20,12 +20,12 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.InputStream; import java.util.Enumeration; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestZipSecureFile { @Test diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java index fd6ffbeb62..96fe630e90 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java @@ -16,26 +16,26 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.dsig; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.Base64; import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestSignatureConfig { - + @Test - @Ignore("failing in automated builds, due to issues loading security classes") + @Disabled("failing in automated builds, due to issues loading security classes") public void testDigestAlgo() throws Exception { SignatureConfig sc = new SignatureConfig(); assertEquals(HashAlgorithm.sha256, sc.getDigestAlgo()); sc.setDigestAlgo(HashAlgorithm.sha1); assertEquals(HashAlgorithm.sha1, sc.getDigestAlgo()); } - + @Test public void testHashOids() throws IOException { final String[][] checks = { @@ -53,7 +53,7 @@ public class TestSignatureConfig { final HashAlgorithm ha = HashAlgorithm.valueOf(check[0]); try (final DigestOutputStream dos = new DigestOutputStream(ha, null)) { final String magic = Base64.getEncoder().encodeToString(dos.getHashMagic()); - assertEquals("hash digest magic mismatches", check[1], magic); + assertEquals(check[1], magic, "hash digest magic mismatches"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java index 258c90497c..528bc8aa24 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java @@ -23,11 +23,12 @@ ================================================================= */ package org.apache.poi.poifs.crypt.dsig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +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.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -152,11 +153,10 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.etsi.uri.x01903.v13.DigestAlgAndValueType; import org.etsi.uri.x01903.v13.QualifyingPropertiesType; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.w3.x2000.x09.xmldsig.ReferenceType; import org.w3.x2000.x09.xmldsig.SignatureDocument; import org.w3c.dom.Document; @@ -169,12 +169,12 @@ public class TestSignatureInfo { private KeyPair keyPair; private X509Certificate x509; - @AfterClass + @AfterAll public static void removeUserLocale() { LocaleUtil.resetUserLocale(); } - @BeforeClass + @BeforeAll public static void initBouncy() { CryptoFunctions.registerBouncyCastle(); @@ -189,8 +189,8 @@ public class TestSignatureInfo { // in the xmlsec jar file String additionalJar = System.getProperty("additionaljar"); //System.out.println("Having: " + additionalJar); - Assume.assumeTrue("Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar, - additionalJar == null || additionalJar.trim().length() == 0); + assumeTrue(additionalJar == null || additionalJar.trim().length() == 0, + "Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar); System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); @@ -198,7 +198,7 @@ public class TestSignatureInfo { // System.setProperty("line.separator", "\n"); } - @Ignore("This test is very sensitive, it breaks with every little change to the produced XML") + @Disabled("This test is very sensitive, it breaks with every little change to the produced XML") @Test public void bug61182() throws Exception { final String pfxInput = @@ -277,7 +277,7 @@ public class TestSignatureInfo { // separator set to the various system configurations String sep = SystemProperties.getProperty("line.separator"); String signExp; - assumeTrue("Hashes only known for Windows/Unix/Mac", sep == null || "\n".equals(sep) || "\r\n".equals(sep) || "\r".equals(sep)); + assumeTrue(sep == null || "\n".equals(sep) || "\r\n".equals(sep) || "\r".equals(sep), "Hashes only known for Windows/Unix/Mac"); signExp = (sep == null || "\n".equals(sep)) ? unixSignExp : ("\r\n".equals(sep)) ? winSignExp : macSignExp; String signAct = si.getSignatureParts().iterator().next(). @@ -355,12 +355,12 @@ public class TestSignatureInfo { } assertNotNull(result); - assertEquals("test-file: " + testFile, 1, result.size()); + assertEquals(1, result.size(), "test-file: " + testFile); X509Certificate signer = result.get(0); LOG.log(POILogger.DEBUG, "signer: ", signer.getSubjectX500Principal()); boolean b = si.verifySignature(); - assertTrue("test-file: " + testFile, b); + assertTrue(b, "test-file: " + testFile); pkg.revert(); } } @@ -382,14 +382,14 @@ public class TestSignatureInfo { } assertNotNull(result); - assertEquals("test-file: " + testFile, 2, result.size()); + assertEquals(2, result.size(), "test-file: " + testFile); X509Certificate signer1 = result.get(0); X509Certificate signer2 = result.get(1); LOG.log(POILogger.DEBUG, "signer 1: ", signer1.getSubjectX500Principal()); LOG.log(POILogger.DEBUG, "signer 2: ", signer2.getSubjectX500Principal()); boolean b = si.verifySignature(); - assertTrue("test-file: " + testFile, b); + assertTrue(b, "test-file: " + testFile); pkg.revert(); } } @@ -433,7 +433,7 @@ public class TestSignatureInfo { si.setOpcPackage(pkg); si.setSignatureConfig(sic); boolean b = si.verifySignature(); - assertFalse("signature should be broken", b); + assertFalse(b, "signature should be broken"); } } } @@ -555,21 +555,21 @@ public class TestSignatureInfo { throw e; } if ((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) { - Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e, - e.getCause().getMessage().contains("timed out")); + assumeFalse(e.getCause().getMessage().contains("timed out"), + "Only allowing ConnectException with 'timed out' as message here, but had: " + e); } else if (e.getCause() instanceof IOException) { - Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e, - e.getCause().getMessage().contains("Error contacting TSP server")); + assumeFalse(e.getCause().getMessage().contains("Error contacting TSP server"), + "Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e); } else if (e.getCause() instanceof RuntimeException) { - Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e, - e.getCause().getMessage().contains("This site is cur")); + assumeFalse(e.getCause().getMessage().contains("This site is cur"), + "Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e); } throw e; } // verify Iterator spIter = si.getSignatureParts().iterator(); - assertTrue("Had: " + pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN), spIter.hasNext()); + assertTrue(spIter.hasNext(), "Had: " + pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN)); SignaturePart sp = spIter.next(); boolean valid = sp.validate(); assertTrue(valid); @@ -697,9 +697,9 @@ public class TestSignatureInfo { si.confirmSignature(); for (SignaturePart sp : si.getSignatureParts()) { - assertTrue("Could not validate", sp.validate()); + assertTrue(sp.validate(), "Could not validate"); X509Certificate signer = sp.getSigner(); - assertNotNull("signer undefined?!", signer); + assertNotNull(signer, "signer undefined?!"); List certChainRes = sp.getCertChain(); // IBM JDK is still buggy, even after fix for APAR IJ21985 @@ -731,9 +731,9 @@ public class TestSignatureInfo { si.confirmSignature(); boolean b = si.verifySignature(); - assertTrue("Signature not correctly calculated for " + ha, b); + assertTrue(b, "Signature not correctly calculated for " + ha); } catch (EncryptedDocumentException e) { - Assume.assumeTrue(e.getMessage().startsWith("Export Restrictions")); + assumeTrue(e.getMessage().startsWith("Export Restrictions")); } } } @@ -758,7 +758,7 @@ public class TestSignatureInfo { si.setOpcPackage(pkg); si.setSignatureConfig(signatureConfig); si.confirmSignature(); - assertTrue("invalid signature", si.verifySignature()); + assertTrue(si.verifySignature(), "invalid signature"); } } } @@ -1087,7 +1087,7 @@ public class TestSignatureInfo { // in the Sonar Maven runs where we are at a different source directory File buildDir = new File("build"); if(!buildDir.exists()) { - assertTrue("Failed to create " + buildDir.getAbsolutePath(), buildDir.mkdirs()); + assertTrue(buildDir.mkdirs(), "Failed to create " + buildDir.getAbsolutePath()); } File tmpFile = new File(buildDir, "sigtest"+extension); diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/AllPOIFSCryptoTests.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/AllPOIFSCryptoTests.java deleted file mode 100644 index 1e3fb4208f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/AllPOIFSCryptoTests.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.poifs.crypt.tests; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -/** - * Tests for org.apache.poi.poifs.crypt - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEncryptionInfo.class - , TestDecryptor.class - , TestEncryptor.class - , TestAgileEncryptionParameters.class -}) -public final class AllPOIFSCryptoTests { -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java index a892b9b550..a05f6f6dcf 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java @@ -16,16 +16,17 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.tests; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.InputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import javax.crypto.Cipher; @@ -39,55 +40,44 @@ import org.apache.poi.poifs.crypt.Encryptor; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TestAgileEncryptionParameters { static byte[] testData; - @Parameter(value = 0) - public CipherAlgorithm ca; - @Parameter(value = 1) - public HashAlgorithm ha; - @Parameter(value = 2) - public ChainingMode cm; - - @Parameters(name="{0} {1} {2}") - public static Collection data() { + public static Stream data() { CipherAlgorithm[] caList = {CipherAlgorithm.aes128, CipherAlgorithm.aes192, CipherAlgorithm.aes256, CipherAlgorithm.rc2, CipherAlgorithm.des, CipherAlgorithm.des3}; HashAlgorithm[] haList = {HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.md5}; ChainingMode[] cmList = {ChainingMode.cbc, ChainingMode.cfb}; - List data = new ArrayList<>(); + List data = new ArrayList<>(); for (CipherAlgorithm ca : caList) { for (HashAlgorithm ha : haList) { for (ChainingMode cm : cmList) { - data.add(new Object[]{ca,ha,cm}); + data.add(Arguments.of(ca,ha,cm)); } } } - return data; + return data.stream(); } - @BeforeClass + @BeforeAll public static void initTestData() throws Exception { InputStream testFile = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.docx"); testData = IOUtils.toByteArray(testFile); testFile.close(); } - @Test - public void testAgileEncryptionModes() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testAgileEncryptionModes(CipherAlgorithm ca, HashAlgorithm ha, ChainingMode cm) throws Exception { int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files", maxKeyLen >= ca.defaultKeySize); + assumeTrue(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -111,6 +101,6 @@ public class TestAgileEncryptionParameters { byte[] actualData = IOUtils.toByteArray(is); is.close(); fsDec.close(); - assertArrayEquals("Failed roundtrip - "+ca+"-"+ha+"-"+cm, testData, actualData); + assertArrayEquals(testData, actualData, "Failed roundtrip - "+ca+"-"+ha+"-"+cm); } } diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java index 7c06982b71..83d1136b8a 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java @@ -16,10 +16,10 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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.Assumptions.assumeTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -27,7 +27,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; -import java.util.stream.IntStream; import javax.crypto.Cipher; @@ -39,8 +38,7 @@ import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestDecryptor { private static final POIDataSamples samples = POIDataSamples.getPOIFSInstance(); @@ -94,7 +92,7 @@ public class TestDecryptor { byte[] buf = new byte[10]; int readBytes = zin.read(buf); // zin.available() doesn't work for entries - assertEquals("size failed for " + entry.getName(), 1, readBytes); + assertEquals(1, readBytes, "size failed for " + entry.getName()); } } } @@ -142,17 +140,14 @@ public class TestDecryptor { final ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); try (final ZipArchiveInputStream zis = new ZipArchiveInputStream(d.getDataStream(fs))) { - IntStream.of(3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910).forEach(size -> { - try { - final ZipArchiveEntry ze = zis.getNextZipEntry(); - assertNotNull(ze); - IOUtils.copy(zis, bos); - assertEquals(size, bos.size()); - bos.reset(); - } catch (IOException e) { - fail(e.getMessage()); - } - }); + int[] sizes = { 3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910 }; + for (int size : sizes) { + final ZipArchiveEntry ze = zis.getNextZipEntry(); + assertNotNull(ze); + IOUtils.copy(zis, bos); + assertEquals(size, bos.size()); + bos.reset(); + } } } } @@ -170,7 +165,7 @@ public class TestDecryptor { @Test public void bug60320() throws IOException, GeneralSecurityException { int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); + assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); try (InputStream is = samples.openResourceAsStream("60320-protected.xlsx"); POIFSFileSystem fs = new POIFSFileSystem(is)) { diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java index bbdad4d9c1..16c4b47adc 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.tests; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -26,8 +26,7 @@ import org.apache.poi.poifs.crypt.CipherProvider; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEncryptionInfo { @Test @@ -39,11 +38,11 @@ public class TestEncryptionInfo { assertEquals(3, info.getVersionMajor()); assertEquals(2, info.getVersionMinor()); - Assert.assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); - Assert.assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); + assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); + assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); assertEquals(128, info.getHeader().getKeySize()); assertEquals(32, info.getVerifier().getEncryptedVerifierHash().length); - Assert.assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); + assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName()); fs.close(); diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java index bcf60b90c9..423497fc1e 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java @@ -17,11 +17,12 @@ package org.apache.poi.poifs.crypt.tests; import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -62,9 +63,8 @@ import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.TempFile; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestEncryptor { @Test @@ -146,7 +146,7 @@ public class TestEncryptor { @Test public void agileEncryption() throws Exception { int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); + assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx"); String pass = "pass"; @@ -162,7 +162,7 @@ public class TestEncryptor { infoExpected = new EncryptionInfo(nfs); decExpected = Decryptor.getInstance(infoExpected); boolean passed = decExpected.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); + assertTrue(passed, "Unable to process: document is encrypted"); // extract the payload try (InputStream is = decExpected.getDataStream(nfs)) { @@ -217,7 +217,7 @@ public class TestEncryptor { infoActual2 = new EncryptionInfo(nfs.getRoot()); Decryptor decActual = Decryptor.getInstance(infoActual2); boolean passed = decActual.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); + assertTrue(passed, "Unable to process: document is encrypted"); // extract the payload try (InputStream is = decActual.getDataStream(nfs)) { @@ -256,7 +256,7 @@ public class TestEncryptor { infoExpected = new EncryptionInfo(nfs); d = Decryptor.getInstance(infoExpected); boolean passed = d.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); + assertTrue(passed, "Unable to process: document is encrypted"); // extract the payload try (InputStream is = d.getDataStream(nfs)) { @@ -317,7 +317,7 @@ public class TestEncryptor { try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) { final EncryptionInfo ei = new EncryptionInfo(nfs); Decryptor d2 = Decryptor.getInstance(ei); - assertTrue("Unable to process: document is encrypted", d2.verifyPassword(pass)); + assertTrue(d2.verifyPassword(pass), "Unable to process: document is encrypted"); try (InputStream is = d2.getDataStream(nfs)) { payloadActual = IOUtils.toByteArray(is); @@ -383,7 +383,7 @@ public class TestEncryptor { } @Test - @Ignore + @Disabled public void inPlaceRewrite() throws Exception { File f = TempFile.createTempFile("protected_agile", ".docx"); @@ -462,7 +462,7 @@ public class TestEncryptor { @Test public void bug60320CustomEncrypt() throws Exception { int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); + assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); // --- src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (revision 1766745) // +++ src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (working copy) diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java index a687045645..65b2a51ccb 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java @@ -20,18 +20,17 @@ package org.apache.poi.poifs.crypt.tests; import static org.apache.poi.POIDataSamples.getDocumentInstance; import static org.apache.poi.POIDataSamples.getSlideShowInstance; import static org.apache.poi.POIDataSamples.getSpreadSheetInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; +import java.util.stream.Stream; import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; @@ -41,28 +40,12 @@ import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TestHxxFEncryption { - @Parameter - public POIDataSamples sampleDir; - - @Parameter(value = 1) - public String file; - - @Parameter(value = 2) - public String password; - - @Parameter(value = 3) - public String expected; - - @Parameters(name="{1}") - public static Collection data() throws IOException { + public static Stream data() throws IOException { final String base64 = "H4sIAAAAAAAAAF1Uu24bMRDs/RULVwkgCUhSpHaZwkDgpHJH8fZ0G/Nx4ZI6y13yG/mRfIb9R5mlZFlIpdPtcnZmdnjPf57/vvx6+f3h6obuv3"+ "ylbY5bEiVHe1fEpUp5pOgkrK0iabehm7FyoZi1ks8xcvHiQu8h5bLnorTlnUvkJ/YPOHKsLVInAqCs91KakuaxLq4w3g00SgCo9Xou1UnCmSBe"+ @@ -74,22 +57,23 @@ public class TestHxxFEncryption { "VZw8Pm6vn0afh4fvr0D5P/+cMuBAAA"; final String x = new String(RawDataUtil.decompress(base64), StandardCharsets.UTF_8); - return Arrays.asList( + return Stream.of( // binary rc4 - new Object[]{ getDocumentInstance(), "password_tika_binaryrc4.doc", "tika", "This is an encrypted Word 2007 File." }, + Arguments.of( getDocumentInstance(), "password_tika_binaryrc4.doc", "tika", "This is an encrypted Word 2007 File." ), // cryptoapi - new Object[]{ getDocumentInstance(), "password_password_cryptoapi.doc", "password", "This is a test" }, + Arguments.of( getDocumentInstance(), "password_password_cryptoapi.doc", "password", "This is a test" ), // binary rc4 - new Object[]{ getSpreadSheetInstance(), "password.xls", "password", x }, + Arguments.of( getSpreadSheetInstance(), "password.xls", "password", x ), // cryptoapi - new Object[]{ getSpreadSheetInstance(), "35897-type4.xls", "freedom", "Sheet1\nhello there!" }, + Arguments.of( getSpreadSheetInstance(), "35897-type4.xls", "freedom", "Sheet1\nhello there!" ), // cryptoapi (PPT only supports cryptoapi...) - new Object[]{ getSlideShowInstance(), "cryptoapi-proc2356.ppt", "crypto", "Dominic Salemno" } + Arguments.of( getSlideShowInstance(), "cryptoapi-proc2356.ppt", "crypto", "Dominic Salemno" ) ); } - @Test - public void extract() throws IOException { + @ParameterizedTest + @MethodSource("data") + public void extract(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { File f = sampleDir.getFile(file); Biff8EncryptionKey.setCurrentUserPassword(password); try (POITextExtractor te = ExtractorFactory.createExtractor(f)) { @@ -100,17 +84,19 @@ public class TestHxxFEncryption { } } - @Test - public void changePassword() throws IOException { - newPassword("test"); + @ParameterizedTest + @MethodSource("data") + public void changePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { + newPassword("test", sampleDir, file, password, expected); } - @Test - public void removePassword() throws IOException { - newPassword(null); + @ParameterizedTest + @MethodSource("data") + public void removePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { + newPassword(null, sampleDir, file, password, expected); } - private void newPassword(String newPass) throws IOException { + private void newPassword(String newPass, POIDataSamples sampleDir, String file, String password, String expected) throws IOException { File f = sampleDir.getFile(file); Biff8EncryptionKey.setCurrentUserPassword(password); try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) { @@ -130,8 +116,9 @@ public class TestHxxFEncryption { } /** changing the encryption mode and key size in poor mans style - see comments below */ - @Test - public void changeEncryption() throws IOException { + @ParameterizedTest + @MethodSource("data") + public void changeEncryption(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { File f = sampleDir.getFile(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Biff8EncryptionKey.setCurrentUserPassword(password); @@ -156,11 +143,8 @@ public class TestHxxFEncryption { // need to cache data (i.e. read all data) before changing the key size Class clazz = doc.getClass(); if ("HSLFSlideShow".equals(clazz.getSimpleName())) { - try { - clazz.getDeclaredMethod("getPictureData").invoke(doc); - } catch (ReflectiveOperationException e) { - fail("either scratchpad jar is included and this should work or the clazz should be != HSLFSlideShowImpl"); - } + assertDoesNotThrow(() -> clazz.getDeclaredMethod("getPictureData").invoke(doc), + "either scratchpad jar is included and this should work or the clazz should be != HSLFSlideShowImpl"); doc.getDocumentSummaryInformation(); } EncryptionInfo ei = doc.getEncryptionInfo(); diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java index f939257997..f9b94cf061 100644 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java +++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java @@ -17,8 +17,9 @@ package org.apache.poi.poifs.crypt.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.io.FileInputStream; @@ -40,8 +41,7 @@ import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.xmlbeans.XmlException; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSecureTempZip { @@ -95,8 +95,7 @@ public class TestSecureTempZip { //The test file requires that JCE unlimited be installed. //If it isn't installed, skip this test. int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", - maxKeyLen == 2147483647); + assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsb"); FileInputStream fis = new FileInputStream(tikaProt); diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java index 28a958c8af..dce5e2a8e3 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java @@ -18,8 +18,8 @@ package org.apache.poi.sl.tests; import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.Color; import java.awt.Dimension; @@ -46,8 +46,8 @@ import org.apache.poi.sl.usermodel.TextBox; import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** @@ -69,7 +69,7 @@ public class TestFonts { private static final String[] INIT_FONTS = {"mona.ttf"}; - @BeforeClass + @BeforeAll public static void initGE() throws FontFormatException, IOException { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); for (String s : INIT_FONTS) { diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java index ceb65d6881..4ffd446c46 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java @@ -20,8 +20,8 @@ package org.apache.poi.sl.tests; import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.List; @@ -31,7 +31,7 @@ import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextShape; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestHeadersFooters { @Test diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java index 061b628f33..13811ebfa5 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java @@ -23,10 +23,10 @@ import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.EXCEL_V8; import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.PDF; import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V12; import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V8; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; @@ -37,13 +37,11 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; +import java.util.stream.Stream; import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.sl.usermodel.ObjectMetaData; import org.apache.poi.sl.usermodel.ObjectShape; @@ -58,14 +56,11 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TestOleShape { private static final String PDF_SAMPLE = "H4sIAAAAAAAAAJWUezRUWxzHe+o2FXncVtxLpxi3FPOeKYspjMdM5J1S4TTOaDIzxzpzJo9CUrnrSiUxIeT" + @@ -98,42 +93,35 @@ public class TestOleShape { enum Api { HSLF, XSLF } - @Parameter(value = 0) - public Api api; - @Parameter(value = 1) - public ObjectMetaData.Application app; - - private static File pictureFile; - @BeforeClass + @BeforeAll public static void initPicture() { pictureFile = POIDataSamples.getSlideShowInstance().getFile("wrench.emf"); } - - @Parameters(name="{0} {1}") - public static Collection data() { - return Arrays.asList(new Object[][] { - { Api.HSLF, EXCEL_V8 }, - { Api.HSLF, WORD_V8 }, - { Api.HSLF, PDF }, - { Api.XSLF, EXCEL_V12 }, - { Api.XSLF, WORD_V12 }, - { Api.XSLF, PDF }, - }); + public static Stream data() { + return Stream.of( + Arguments.of( Api.HSLF, EXCEL_V8 ), + Arguments.of( Api.HSLF, WORD_V8 ), + Arguments.of( Api.HSLF, PDF ), + Arguments.of( Api.XSLF, EXCEL_V12 ), + Arguments.of( Api.XSLF, WORD_V12 ), + Arguments.of( Api.XSLF, PDF ) + ); } - @Test - public void embedData() throws IOException, InvalidFormatException, ReflectiveOperationException { + @ParameterizedTest + @MethodSource("data") + public void embedData(Api api, ObjectMetaData.Application app) throws IOException, ReflectiveOperationException { final ByteArrayInputStream pptBytes; - try (SlideShow ppt = createSlideShow()) { + try (SlideShow ppt = createSlideShow(api)) { final PictureData picData = ppt.addPicture(pictureFile, PictureType.EMF); final Slide slide = ppt.createSlide(); final ObjectShape oleShape = slide.createOleShape(picData); oleShape.setAnchor(new Rectangle2D.Double(100,100,100,100)); try (OutputStream os = oleShape.updateObjectData(app, null)) { - fillOleData(os); + fillOleData(app, os); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); ppt.write(bos); @@ -142,12 +130,12 @@ public class TestOleShape { try (SlideShow ppt = SlideShowFactory.create(pptBytes)) { final ObjectShape oleShape = (ObjectShape)ppt.getSlides().get(0).getShapes().get(0); try (InputStream bis = oleShape.readObjectData()) { - validateOleData(bis); + validateOleData(app, bis); } } } - private SlideShow createSlideShow() throws IOException { + private SlideShow createSlideShow(Api api) throws IOException { if (api == Api.XSLF) { return new XMLSlideShow(); } else { @@ -157,7 +145,7 @@ public class TestOleShape { } - private void fillOleData(final OutputStream out) throws IOException { + private void fillOleData(ObjectMetaData.Application app, final OutputStream out) throws IOException { switch (app) { case EXCEL_V8: case EXCEL_V12: @@ -187,7 +175,7 @@ public class TestOleShape { } } - private void validateOleData(final InputStream in) throws IOException, ReflectiveOperationException { + private void validateOleData(ObjectMetaData.Application app, final InputStream in) throws IOException, ReflectiveOperationException { switch (app) { case EXCEL_V8: case EXCEL_V12: diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java index 19b8ab38b1..77f2121a6f 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java @@ -20,9 +20,9 @@ package org.apache.poi.sl.tests; import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -33,7 +33,7 @@ import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSlide { diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java index 2ab404b030..ace5ef0d82 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java @@ -21,12 +21,12 @@ package org.apache.poi.sl.tests; import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow; import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +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 static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; @@ -41,7 +41,7 @@ import org.apache.poi.sl.usermodel.TableCell; import org.apache.poi.sl.usermodel.TableShape; import org.apache.poi.sl.usermodel.TextShape.TextDirection; import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestTable { @@ -80,17 +80,15 @@ public class TestTable { int colsx = tableB.getNumberOfColumns(); int rowsx = tableB.getNumberOfRows(); - assertEquals("tables should have same number of columns", cols, colsx); - assertEquals("tables should have same number of rows", rows, rowsx); + assertEquals(cols, colsx, "tables should have same number of columns"); + assertEquals(rows, rowsx, "tables should have same number of rows"); for (int i=0; i hssf - wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (Workbook wb = WorkbookFactory.create( + new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)) + )) { + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + } - wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)).getRoot() - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (Workbook wb = WorkbookFactory.create( + new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)).getRoot() + )) { + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + } // Package -> xssf - wb = XSSFWorkbookFactory.createWorkbook( - OPCPackage.open( - HSSFTestDataSamples.openSampleFileStream(xlsx)) - ); - assertNotNull(wb); - //noinspection ConstantConditions - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); + try (Workbook wb = XSSFWorkbookFactory.createWorkbook( + OPCPackage.open(HSSFTestDataSamples.openSampleFileStream(xlsx)) + )) { + assertNotNull(wb); + //noinspection ConstantConditions + assertTrue(wb instanceof XSSFWorkbook); + } } @Test public void testCreateReadOnly() throws Exception { - Workbook wb; - // POIFS -> hssf - wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true)) { + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + assertCloseDoesNotModifyFile(xls, wb); + } // Package -> xssf - wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true)) { + assertNotNull(wb); + assertTrue(wb instanceof XSSFWorkbook); + assertCloseDoesNotModifyFile(xlsx, wb); + } } /** * Creates the appropriate kind of Workbook, but - * checking the mime magic at the start of the - * InputStream, then creating what's required. + * checking the mime magic at the start of the + * InputStream, then creating what's required. */ @Test public void testCreateGeneric() throws Exception { - Workbook wb; - // InputStream -> either - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xls))) { + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + } - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx) - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xlsx))) { + assertNotNull(wb); + assertTrue(wb instanceof XSSFWorkbook); + } // File -> either - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls))) { + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + assertCloseDoesNotModifyFile(xls, wb); + } - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx) - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); + try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx))) { + assertNotNull(wb); + assertTrue(wb instanceof XSSFWorkbook); + assertCloseDoesNotModifyFile(xlsx, wb); + } // Invalid type -> exception final byte[] before = HSSFTestDataSamples.getTestDataFileContent(txt); - try { - try (InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt)) { - wb = WorkbookFactory.create(stream); - assertNotNull(wb); - } - fail(); - } catch(IOException e) { - // Good - } + assertThrows(IOException.class, () -> WorkbookFactory.create(new File(txt))); final byte[] after = HSSFTestDataSamples.getTestDataFileContent(txt); - assertArrayEquals("Invalid type file was modified after trying to open the file as a spreadsheet", - before, after); + assertArrayEquals(before, after, "Invalid type file was modified after trying to open the file as a spreadsheet"); + } + + public static Stream workbookPass() { + return Stream.of( + // Unprotected, no password given, opens normally + Arguments.of(xls, null, false, HSSFWorkbook.class), + Arguments.of(xlsx, null, false, XSSFWorkbook.class), + // Unprotected, wrong password, opens normally + Arguments.of(xls, "wrong", false, HSSFWorkbook.class), + Arguments.of(xlsx, "wrong", false, XSSFWorkbook.class), + // Protected, correct password, opens fine + Arguments.of(xls_protected[0], xls_protected[1], false, HSSFWorkbook.class), + Arguments.of(xlsx_protected[0], xlsx_protected[1], false, XSSFWorkbook.class), + // Protected, wrong password, throws Exception + Arguments.of(xls_protected[0], "wrong", true, HSSFWorkbook.class), + Arguments.of(xlsx_protected[0], "wrong", true, XSSFWorkbook.class) + ); } /** * Check that the overloaded stream methods which take passwords work properly */ - @Test - public void testCreateWithPasswordFromStream() throws Exception { - Workbook wb; - - // Unprotected, no password given, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls), null - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx), null - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - - // Unprotected, wrong password, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - - // Protected, correct password, opens fine - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), xls_protected[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls_protected[0], wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), xlsx_protected[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx_protected[0], wb); - - - // Protected, wrong password, throws Exception - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xls_protected[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here - } - - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xlsx_protected[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here + @ParameterizedTest + @MethodSource("workbookPass") + public void testCreateWithPasswordFromStream(String file, String pass, boolean fails, Class clazz) throws Exception { + try (InputStream is = HSSFTestDataSamples.openSampleFileStream(file)) { + if (fails) { + assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(is, pass), + "Shouldn't be able to open with the wrong password"); + } else { + try (Workbook wb = WorkbookFactory.create(is, pass)) { + assertNotNull(wb); + assertTrue(clazz.isInstance(wb)); + } + } } } /** * Check that the overloaded file methods which take passwords work properly */ - @Test - public void testCreateWithPasswordFromFile() throws Exception { - Workbook wb; - - // Unprotected, no password given, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls), null - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx), null - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // Unprotected, wrong password, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // Protected, correct password, opens fine - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls_protected[0]), xls_protected[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls_protected[0], wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), xlsx_protected[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertTrue(wb.getNumberOfSheets() > 0); - assertNotNull(wb.getSheetAt(0)); - assertNotNull(wb.getSheetAt(0).getRow(0)); - assertCloseDoesNotModifyFile(xlsx_protected[0], wb); - - // Protected, wrong password, throws Exception - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls_protected[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xls_protected[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here - } finally { - wb.close(); - } - - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xlsx_protected[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here + @ParameterizedTest + @MethodSource("workbookPass") + public void testCreateWithPasswordFromFile(String fileName, String pass, boolean fails, Class clazz) throws Exception { + File file = HSSFTestDataSamples.getSampleFile(fileName); + if (fails) { + assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(file, pass), + "Shouldn't be able to open with the wrong password"); + } else { + try (Workbook wb = WorkbookFactory.create(file, pass)) { + assertNotNull(wb); + assertTrue(clazz.isInstance(wb)); + assertCloseDoesNotModifyFile(fileName, wb); + } } } /** * Check that a helpful exception is given on an empty input stream */ - @Test(expected = EmptyFileException.class) - public void testEmptyInputStream() throws Exception { + @Test + public void testEmptyInputStream() { InputStream emptyStream = new ByteArrayInputStream(new byte[0]); - WorkbookFactory.create(emptyStream); + assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyStream)); } /** * Check that a helpful exception is given on an empty file */ - @Test(expected = EmptyFileException.class) + @Test public void testEmptyFile() throws Exception { File emptyFile = TempFile.createTempFile("empty", ".poi"); - try { - WorkbookFactory.create(emptyFile); - fail("Shouldn't be able to create for an empty file"); - } finally { - assertTrue(emptyFile.delete()); - } + assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyFile), + "Shouldn't be able to create for an empty file"); + assertTrue(emptyFile.delete()); } /** - * Check that a helpful exception is raised on a non-existing file - */ - @Test(expected = FileNotFoundException.class) - public void testNonExistingFile() throws Exception { + * Check that a helpful exception is raised on a non-existing file + */ + @Test + public void testNonExistingFile() { File nonExistingFile = new File("notExistingFile"); assertFalse(nonExistingFile.exists()); - WorkbookFactory.create(nonExistingFile, "password", true); + assertThrows(FileNotFoundException.class, () -> WorkbookFactory.create(nonExistingFile, "password", true)); } /** * See Bugzilla bug #62831 - #WorkbookFactory.create(File) needs - * to work for sub-classes of File too, eg JFileChooser + * to work for sub-classes of File too, eg JFileChooser */ @Test public void testFileSubclass() throws Exception { @@ -444,30 +323,32 @@ public final class TestWorkbookFactory { public void testOpenManyHSSF() throws Exception { final int size = 1000; ExecutorService executorService = Executors.newFixedThreadPool(10); - ArrayList> futures = new ArrayList(size); + ArrayList> futures = new ArrayList<>(size); for (int i = 0; i < size; i++) { - futures.add(executorService.submit(() -> openHSSFFile())); + futures.add(executorService.submit(this::openHSSFFile)); } - for (Future future: futures) { + for (Future future : futures) { assertTrue(future.get()); } } - @Test(expected = IOException.class) + @Test public void testInvalidFormatException() throws IOException { String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; - WorkbookFactory.create(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)); + try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)) { + assertThrows(IOException.class, () -> WorkbookFactory.create(is)); + } } private boolean openHSSFFile() { try { // POIFS -> hssf - Workbook wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); + try (InputStream is = HSSFTestDataSamples.openSampleFileStream(xls)) { + Workbook wb = WorkbookFactory.create(new POIFSFileSystem(is)); + assertNotNull(wb); + assertTrue(wb instanceof HSSFWorkbook); + assertCloseDoesNotModifyFile(xls, wb); + } return true; } catch (Exception e) { return false; diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java b/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java index d5d0c47623..ae7eaefa3e 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.tests.extractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -38,7 +38,7 @@ import org.apache.poi.ss.extractor.EmbeddedExtractor; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEmbeddedExtractor { private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java b/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java index 824fe4ba15..e4f9ff80b2 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.tests.format; import static java.awt.Color.ORANGE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.awt.Color; import java.io.IOException; @@ -39,9 +39,9 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Class for spreadsheet-based tests, such as are used for cell formatting. @@ -63,13 +63,13 @@ public class TestCellFormatPart { - @BeforeClass + @BeforeAll public static void setLocale() { userLocale = LocaleUtil.getUserLocale(); LocaleUtil.setUserLocale(Locale.UK); } - @AfterClass + @AfterAll public static void unsetLocale() { LocaleUtil.setUserLocale(userLocale); } @@ -80,8 +80,7 @@ public class TestCellFormatPart { Object getValue(Cell cell); default void equivalent(String expected, String actual, CellFormatPart format) { - assertEquals("format \"" + format + "\"", '"' + expected + '"', - '"' + actual + '"'); + assertEquals('"' + expected + '"', '"' + actual + '"', "format \"" + format + "\""); } } @@ -120,8 +119,7 @@ public class TestCellFormatPart { double actualVal = extractNumber(actual); // equal within 1% double delta = expectedVal / 100; - assertEquals("format \"" + format + "\"," + expected + " ~= " + - actual, expectedVal, actualVal, delta); + assertEquals(expectedVal, actualVal, delta, "format \"" + format + "\"," + expected + " ~= " + actual); } }); } @@ -204,7 +202,7 @@ public class TestCellFormatPart { String actualText = label.getText(); Color actualColor = label.getForeground(); valueGetter.equivalent(expectedText, actualText, cellFormatPart); - assertEquals("no color", expectedColor, actualColor); + assertEquals(expectedColor, actualColor, "no color"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java index 01c2f13ff0..3314754906 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java @@ -18,10 +18,10 @@ */ package org.apache.poi.ss.tests.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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.hssf.usermodel.HSSFEvaluationWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -38,7 +38,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test {@link FormulaParser}'s handling of row numbers at the edge of the @@ -51,13 +51,8 @@ public class TestFormulaParser { @Test public void testHSSFFailsForOver65536() { FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(new HSSFWorkbook()); - try { - FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0); - fail("Expected exception"); - } - catch (FormulaParseException expected) { - // expected here - } + assertThrows(FormulaParseException.class, () -> + FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0)); } private static void checkHSSFFormula(String formula) { @@ -90,13 +85,8 @@ public class TestFormulaParser { @Test public void testXSSFFailCase() { FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(new XSSFWorkbook()); - try { - FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0); // one more than max rows. - fail("Expected exception"); - } - catch (FormulaParseException expected) { - // expected here - } + assertThrows(FormulaParseException.class, () -> + FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0), "one more than max rows"); } // copied from org.apache.poi.hssf.model.TestFormulaParser @@ -175,13 +165,9 @@ public class TestFormulaParser { /** confirm formula has invalid syntax and parsing the formula results in FormulaParseException */ private static void parseExpectedException(String formula, FormulaParsingWorkbook wb) { - try { - FormulaParser.parse(formula, wb, FormulaType.CELL, -1); - fail("Expected FormulaParseException: " + formula); - } catch (final FormulaParseException e) { - // expected during successful test - assertNotNull(e.getMessage()); - } + FormulaParseException e = assertThrows(FormulaParseException.class, () -> + FormulaParser.parse(formula, wb, FormulaType.CELL, -1)); + assertNotNull(e.getMessage()); } // trivial case for bug 60219: FormulaParser can't parse external references when sheet name is quoted @@ -191,13 +177,13 @@ public class TestFormulaParser { XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); Ptg[] ptgs = FormulaParser.parse("[1]Sheet1!A1", fpwb, FormulaType.CELL, -1); // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals("Ptgs length", 1, ptgs.length); - assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg); + assertEquals(1, ptgs.length, "Ptgs length"); + assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class"); Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber()); - assertEquals("Sheet name", "Sheet1", pxg.getSheetName()); - assertEquals("Row", 0, pxg.getRow()); - assertEquals("Column", 0, pxg.getColumn()); + assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number"); + assertEquals("Sheet1", pxg.getSheetName(), "Sheet name"); + assertEquals(0, pxg.getRow(), "Row"); + assertEquals(0, pxg.getColumn(), "Column"); wb.close(); } @@ -208,13 +194,13 @@ public class TestFormulaParser { XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); Ptg[] ptgs = FormulaParser.parse("'[1]Sheet 1'!A1", fpwb, FormulaType.CELL, -1); // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals("Ptgs length", 1, ptgs.length); - assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg); + assertEquals(1, ptgs.length, "Ptgs length"); + assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class"); Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber()); - assertEquals("Sheet name", "Sheet 1", pxg.getSheetName()); - assertEquals("Row", 0, pxg.getRow()); - assertEquals("Column", 0, pxg.getColumn()); + assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number"); + assertEquals("Sheet 1", pxg.getSheetName(), "Sheet name"); + assertEquals(0, pxg.getRow(), "Row"); + assertEquals(0, pxg.getColumn(), "Column"); wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java index aa239a19b2..f5d3de2b1e 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java @@ -17,10 +17,9 @@ package org.apache.poi.ss.tests.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; @@ -35,7 +34,7 @@ import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFTable; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests Excel Table expressions (structured references) @@ -50,16 +49,16 @@ public class TestStructuredReferences { */ @Test public void testTableExpressionSyntax() { - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("abc[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_abc[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[#This Row]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches()); + assertTrue(Table.isStructuredReference.matcher("abc[col1]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("_abc[col1]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("_[col1]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("\\[#This Row]").matches(), "Valid structured reference syntax didn't match expression"); + assertTrue(Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches(), "Valid structured reference syntax didn't match expression"); // can't have a space between the table name and open bracket - assertFalse("Invalid structured reference syntax didn't fail expression", Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches()); + assertFalse(Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches(), "Invalid structured reference syntax didn't fail expression"); } @Test @@ -109,18 +108,14 @@ public class TestStructuredReferences { private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) { fe.clearAllCachedResultValues(); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.NUMERIC) { - fail("expected numeric cell type but got " + cv.formatAsString()); - } + 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 expectedResult) { fe.clearAllCachedResultValues(); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.STRING) { - fail("expected String cell type but got " + cv.formatAsString()); - } + assertEquals(CellType.STRING, cv.getCellType(), "expected String cell type but got " + cv.formatAsString()); assertEquals(expectedResult, cv.getStringValue()); } } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/CountifsTests.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/CountifsTests.java index 45318e4b0e..103c6814b5 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/CountifsTests.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/CountifsTests.java @@ -18,8 +18,8 @@ package org.apache.poi.ss.tests.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; @@ -32,9 +32,9 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.SheetUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test the COUNTIFS() function @@ -46,7 +46,7 @@ public class CountifsTests { /** * initialize a workbook */ - @Before + @BeforeEach public void before() { // not sure why we allow this, COUNTIFS() is only available // in OOXML, it was introduced with Office 2007 @@ -56,7 +56,7 @@ public class CountifsTests { /** * Close the workbook if needed */ - @After + @AfterEach public void after() { IOUtils.closeQuietly(workbook); } @@ -108,14 +108,13 @@ public class CountifsTests { /** * the bug returned the wrong count, this verifies the fix - * @throws Exception if the file can't be read */ @Test - public void testBug56822() throws Exception { + public void testBug56822() { workbook = XSSFTestDataSamples.openSampleWorkbook("56822-Countifs.xlsx"); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); Cell cell = SheetUtil.getCell(workbook.getSheetAt(0), 0, 3); - assertNotNull("Test workbook missing cell D1", cell); + assertNotNull(cell, "Test workbook missing cell D1"); CellValue evaluate = evaluator.evaluate(cell); assertEquals(2.0d, evaluate.getNumberValue(), 0.00000000000001); } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java index 963fda3d01..2dde03663f 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.tests.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -33,7 +33,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestProper { private Cell cell11; @@ -93,7 +93,7 @@ public final class TestProper { cell11.setCellFormula(formulaText); evaluator.clearAllCachedResultValues(); CellValue cv = evaluator.evaluate(cell11); - assertEquals("Wrong result type", CellType.STRING, cv.getCellType()); + assertEquals(CellType.STRING, cv.getCellType(), "Wrong result type"); String actualValue = cv.getStringValue(); assertEquals(expectedResult, actualValue); } @@ -120,7 +120,7 @@ public final class TestProper { @Test public void testMicroBenchmark() { ValueEval strArg = new StringEval("some longer text that needs a number of replacements to check for runtime of different implementations"); - long start = System.currentTimeMillis(); + // long start = System.currentTimeMillis(); for(int i = 0;i < 300000;i++) { final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0); assertEquals("Some Longer Text That Needs A Number Of Replacements To Check For Runtime Of Different Implementations", ((StringEval)ret).getStringValue()); diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java index 4963148ffd..e0783bf778 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java @@ -19,7 +19,7 @@ package org.apache.poi.ss.tests.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -28,7 +28,7 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java index 34bc8501cf..e6b7d73794 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.tests.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.IOException; @@ -32,7 +32,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test the VLOOKUP function @@ -44,10 +44,10 @@ public class TestVlookup { try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("VLookupFullColumn.xlsx")) { FormulaEvaluator feval = wb.getCreationHelper().createFormulaEvaluator(); feval.evaluateAll(); - assertEquals("Wrong lookup value", "Value1", - feval.evaluate(wb.getSheetAt(0).getRow(3).getCell(1)).getStringValue()); - assertEquals("Lookup should return #N/A", - CellType.ERROR, feval.evaluate(wb.getSheetAt(0).getRow(4).getCell(1)).getCellType()); + assertEquals("Value1", feval.evaluate(wb.getSheetAt(0).getRow(3).getCell(1)).getStringValue(), + "Wrong lookup value"); + assertEquals(CellType.ERROR, feval.evaluate(wb.getSheetAt(0).getRow(4).getCell(1)).getCellType(), + "Lookup should return #N/A"); } } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java index f3eb74475e..294f14337a 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.tests.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -30,7 +30,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.usermodel.XSSFCell; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class for combined testing of XML-specific functionality of diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java index b4f2bef2e8..c0f57156d7 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java @@ -23,7 +23,7 @@ import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.usermodel.XSSFRow; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class for combined testing of XML-specific functionality of diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/ConditionalFormattingEvalTest.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/ConditionalFormattingEvalTest.java index e4e859bb36..71847270ef 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/ConditionalFormattingEvalTest.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/ConditionalFormattingEvalTest.java @@ -18,11 +18,10 @@ package org.apache.poi.ss.tests.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; +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 java.io.IOException; import java.util.Date; import java.util.List; @@ -32,13 +31,14 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Color; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellReference; +import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ConditionalFormattingEvalTest { @@ -49,25 +49,20 @@ public class ConditionalFormattingEvalTest { private CellReference ref; private List rules; - @Before + @BeforeEach public void openWB() { wb = XSSFTestDataSamples.openSampleWorkbook("ConditionalFormattingSamples.xlsx"); formulaEval = new XSSFFormulaEvaluator(wb); cfe = new ConditionalFormattingEvaluator(wb, formulaEval); } - @After + @AfterEach public void closeWB() { formulaEval = null; cfe = null; ref = null; rules = null; - try { - if (wb != null) wb.close(); - } catch (IOException e) { - // keep going, this shouldn't cancel things - e.printStackTrace(); - } + IOUtils.closeQuietly(wb); } @Test @@ -75,25 +70,25 @@ public class ConditionalFormattingEvalTest { sheet = wb.getSheet("Products1"); getRulesFor(12, 1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); - assertFalse("should not be italic " + ref, rules.get(0).getRule().getFontFormatting().isItalic()); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); + assertFalse(rules.get(0).getRule().getFontFormatting().isItalic(), "should not be italic " + ref); getRulesFor(16, 3); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref); getRulesFor(12, 3); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); sheet = wb.getSheet("Products2"); getRulesFor(15,1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); getRulesFor(20,3); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); // now change a cell value that's an input for the rules Cell cell = sheet.getRow(1).getCell(6); @@ -107,103 +102,103 @@ public class ConditionalFormattingEvalTest { // test that the conditional validation evaluations changed getRulesFor(15,1); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); getRulesFor(20,3); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref); getRulesFor(20,1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); sheet = wb.getSheet("Book tour"); getRulesFor(8,2); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); sheet = wb.getSheet("Compare to totals"); getRulesFor(3, 2); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong fg color for " + ref, "FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor())); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref); getRulesFor(3, 3); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); getRulesFor(15, 4); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); getRulesFor(16, 1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong fg color for " + ref, "FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor())); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); + assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref); sheet = wb.getSheet("Products3"); sheet.getRow(8).getCell(0).setCellValue(new Date()); getRulesFor(8, 0); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); getRulesFor(8, 3); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); + assertEquals(1, rules.size(), "wrong # of rules for " + ref); sheet = wb.getSheet("Customers2"); getRulesFor(3, 0); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); + assertEquals(0, rules.size(), "wrong # of rules for " + ref); } @Test - public void testFormattingOnUndefinedCell() throws Exception { + public void testFormattingOnUndefinedCell() { wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_with_formula_on_second_sheet.xlsx"); formulaEval = new XSSFFormulaEvaluator(wb); cfe = new ConditionalFormattingEvaluator(wb, formulaEval); sheet = wb.getSheet("Sales Plan"); getRulesFor(9,2); - assertNotEquals("No rules for " + ref, 0, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFFF00", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); + assertNotEquals(0, rules.size(), "No rules for " + ref); + assertEquals("FFFFFF00", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); } @Test - public void testRepeatedEval() throws Exception { + public void testRepeatedEval() { wb = XSSFTestDataSamples.openSampleWorkbook("test_conditional_formatting.xlsx"); formulaEval = new XSSFFormulaEvaluator(wb); cfe = new ConditionalFormattingEvaluator(wb, formulaEval); sheet = wb.getSheetAt(0); - assertEquals("no rules should apply", 0, getRulesFor(2, 1).size()); + assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply"); - assertEquals("no rules should apply", 0, getRulesFor(2, 1).size()); + assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply"); } @Test - public void testCellValueIsWrongType() throws Exception { + public void testCellValueIsWrongType() { wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_cell_is.xlsx"); formulaEval = new XSSFFormulaEvaluator(wb); cfe = new ConditionalFormattingEvaluator(wb, formulaEval); sheet = wb.getSheetAt(1); - assertEquals("wrong # of matching rules", 1, getRulesFor(3, 1).size()); + assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules"); } @Test - public void testRangeCondition() throws Exception { + public void testRangeCondition() { wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_multiple_ranges.xlsx"); formulaEval = new XSSFFormulaEvaluator(wb); cfe = new ConditionalFormattingEvaluator(wb, formulaEval); sheet = wb.getSheetAt(0); - assertEquals("wrong # of matching rules", 0, getRulesFor(0, 0).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(1, 0).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(2, 0).size()); - assertEquals("wrong # of matching rules", 1, getRulesFor(3, 0).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(0, 1).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(1, 1).size()); - assertEquals("wrong # of matching rules", 1, getRulesFor(2, 1).size()); - assertEquals("wrong # of matching rules", 1, getRulesFor(3, 1).size()); - assertEquals("wrong # of matching rules", 1, getRulesFor(0, 3).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(1, 3).size()); - assertEquals("wrong # of matching rules", 1, getRulesFor(2, 3).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(0, 6).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(3, 6).size()); - assertEquals("wrong # of matching rules", 0, getRulesFor(2, 6).size()); + assertEquals(0, getRulesFor(0, 0).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(1, 0).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(2, 0).size(), "wrong # of matching rules"); + assertEquals(1, getRulesFor(3, 0).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(0, 1).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(1, 1).size(), "wrong # of matching rules"); + assertEquals(1, getRulesFor(2, 1).size(), "wrong # of matching rules"); + assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules"); + assertEquals(1, getRulesFor(0, 3).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(1, 3).size(), "wrong # of matching rules"); + assertEquals(1, getRulesFor(2, 3).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(0, 6).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(3, 6).size(), "wrong # of matching rules"); + assertEquals(0, getRulesFor(2, 6).size(), "wrong # of matching rules"); } private List getRulesFor(int row, int col) { diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java index 28c1bcc06a..ab93e123b9 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java @@ -18,10 +18,10 @@ package org.apache.poi.ss.tests.usermodel; import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +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 static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -62,15 +62,15 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFObjectData; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestEmbedOLEPackage { private static byte[] samplePPT, samplePPTX, samplePNG; private static final POIDataSamples ssamples = POIDataSamples.getSpreadSheetInstance(); - @BeforeClass + @BeforeAll public static void init() throws IOException { samplePPT = getSamplePPT(false); samplePPTX = getSamplePPT(true); diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java index 858014e6ed..6e690ba2bd 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java @@ -19,7 +19,7 @@ package org.apache.poi.ss.tests.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -31,9 +31,9 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFRangeCopier; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFRangeCopier extends BaseTestRangeCopier { public TestXSSFRangeCopier() { @@ -42,7 +42,7 @@ public class TestXSSFRangeCopier extends BaseTestRangeCopier { testDataProvider = XSSFITestDataProvider.instance; } - @Before + @BeforeEach public void init() { workbook = XSSFTestDataSamples.openSampleWorkbook("tile-range-test.xlsx"); initSheets(); @@ -50,7 +50,7 @@ public class TestXSSFRangeCopier extends BaseTestRangeCopier { transSheetRangeCopier = new XSSFRangeCopier(sheet1, sheet2); } - @After + @AfterEach public void shutdown() throws IOException { workbook.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java b/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java index 36d0e5b9bd..40897394aa 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.tests.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; import java.io.IOException; @@ -33,7 +33,7 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.PropertyTemplate; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFPropertyTemplate { diff --git a/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java b/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java index 86973654d1..aac5a2acf5 100644 --- a/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java +++ b/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java @@ -16,15 +16,15 @@ ==================================================================== */ package org.apache.poi.util.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.ooxml.util.IdentifierManager; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestIdentifierManager { @Test @@ -43,8 +43,8 @@ public class TestIdentifierManager { long min = IdentifierManager.MIN_ID; long max = IdentifierManager.MAX_ID; IdentifierManager manager = new IdentifierManager(min,max); - assertTrue("Limits lead to a long variable overflow", max - min + 1 > 0); - assertTrue("Limits lead to a long variable overflow", manager.getRemainingIdentifiers() > 0); + assertTrue(max - min + 1 > 0, "Limits lead to a long variable overflow"); + assertTrue(manager.getRemainingIdentifiers() > 0, "Limits lead to a long variable overflow"); assertEquals(min,manager.reserveNew()); assertEquals(max,manager.reserve(max)); assertEquals(max - min -1, manager.getRemainingIdentifiers()); @@ -54,37 +54,22 @@ public class TestIdentifierManager { @Test public void testReserve() { - IdentifierManager manager = new IdentifierManager(10L,30L); - assertEquals(12L,manager.reserve(12L)); - long reserve = manager.reserve(12L); - assertNotEquals("Same id must be reserved twice!", 12L, reserve); - assertTrue(manager.release(12L)); - assertTrue(manager.release(reserve)); - assertFalse(manager.release(12L)); - assertFalse(manager.release(reserve)); + IdentifierManager manager1 = new IdentifierManager(10L, 30L); + assertEquals(12L, manager1.reserve(12L)); + long reserve = manager1.reserve(12L); + assertNotEquals(12L, reserve, "Same id must be reserved twice!"); + assertTrue(manager1.release(12L)); + assertTrue(manager1.release(reserve)); + assertFalse(manager1.release(12L)); + assertFalse(manager1.release(reserve)); - manager = new IdentifierManager(0L,2L); - assertEquals(0L,manager.reserve(0L)); - assertEquals(1L,manager.reserve(1L)); - assertEquals(2L,manager.reserve(2L)); - try { - manager.reserve(0L); - fail("Exception expected"); - } catch(IllegalStateException e) { - // expected - } - try { - manager.reserve(1L); - fail("Exception expected"); - } catch(IllegalStateException e) { - // expected - } - try { - manager.reserve(2L); - fail("Exception expected"); - } catch(IllegalStateException e) { - // expected - } + IdentifierManager manager2 = new IdentifierManager(0L, 2L); + assertEquals(0L, manager2.reserve(0L)); + assertEquals(1L, manager2.reserve(1L)); + assertEquals(2L, manager2.reserve(2L)); + assertThrows(IllegalStateException.class, () -> manager2.reserve(0L)); + assertThrows(IllegalStateException.class, () -> manager2.reserve(1L)); + assertThrows(IllegalStateException.class, () -> manager2.reserve(2L)); } @Test @@ -93,12 +78,7 @@ public class TestIdentifierManager { assertSame(10L,manager.reserveNew()); assertSame(11L,manager.reserveNew()); assertSame(12L,manager.reserveNew()); - try { - manager.reserveNew(); - fail("IllegalStateException expected"); - } catch (IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, manager::reserveNew); } @Test diff --git a/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java b/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java index 57837d13cd..b4e26b6cb7 100644 --- a/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java +++ b/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java @@ -18,7 +18,7 @@ package org.apache.poi.util.tests; import static org.apache.poi.util.DefaultTempFileCreationStrategy.POIFILES; import static org.apache.poi.util.TempFile.JAVA_IO_TMPDIR; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.FileOutputStream; @@ -36,9 +36,9 @@ import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFileCreationStrategy; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestTempFileThreaded { private static final int NUMBER_OF_THREADS = 10; @@ -72,7 +72,7 @@ public class TestTempFileThreaded { }; } - @BeforeClass + @BeforeAll public static void setUpClass() throws IOException { String tmpDir = System.getProperty(JAVA_IO_TMPDIR); if (tmpDir == null) { @@ -82,7 +82,7 @@ public class TestTempFileThreaded { TempFile.setTempFileCreationStrategy(createTempFileCreationStrategy(new File(new File(tmpDir, POIFILES), "TestTempFileThreaded"))); } - @Before + @BeforeEach public void setUp() { // Initialize array to allow to summarize afterwards executions = new int[NUMBER_OF_THREADS]; @@ -111,9 +111,7 @@ public class TestTempFileThreaded { // make sure the resulting number of executions is correct for (int i = 0; i < NUMBER_OF_THREADS; i++) { // check if enough items were performed - assertEquals("Thread " + i - + " did not execute all iterations", NUMBER_OF_TESTS, - executions[i]); + assertEquals(NUMBER_OF_TESTS, executions[i], "Thread " + i + " did not execute all iterations"); } } @@ -155,10 +153,6 @@ public class TestTempFileThreaded { } files.get(threadNum).add(file); - - if (iter % 30 == 0) { - // System.out.println("thread: " + threadNum + ", iter: " + iter + ": " + file); - } } } } diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java index f2b7731714..f318f998d5 100644 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java +++ b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java @@ -17,12 +17,14 @@ package org.apache.poi.xddf.usermodel; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.apache.poi.xddf.usermodel.chart.ErrorBarType; import org.apache.poi.xddf.usermodel.chart.ErrorDirection; import org.apache.poi.xddf.usermodel.chart.ErrorValueType; import org.apache.poi.xddf.usermodel.chart.XDDFErrorBars; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.chart.*; import org.openxmlformats.schemas.drawingml.x2006.main.*; @@ -32,158 +34,158 @@ public class TestNecessaryOOXMLClasses { @Test public void testProblemClasses() { CTXYAdjustHandle ctxyAdjustHandle = CTXYAdjustHandle.Factory.newInstance(); - Assert.assertNotNull(ctxyAdjustHandle); + assertNotNull(ctxyAdjustHandle); CTPolarAdjustHandle ctPolarAdjustHandle = CTPolarAdjustHandle.Factory.newInstance(); - Assert.assertNotNull(ctPolarAdjustHandle); + assertNotNull(ctPolarAdjustHandle); CTChartLines ctChartLines = CTChartLines.Factory.newInstance(); - Assert.assertNotNull(ctChartLines); + assertNotNull(ctChartLines); CTDashStop ctDashStop = CTDashStop.Factory.newInstance(); - Assert.assertNotNull(ctDashStop); + assertNotNull(ctDashStop); CTSurface ctSurface = CTSurface.Factory.newInstance(); - Assert.assertNotNull(ctSurface); + assertNotNull(ctSurface); CTLegendEntry ctLegendEntry = CTLegendEntry.Factory.newInstance(); - Assert.assertNotNull(ctLegendEntry); + assertNotNull(ctLegendEntry); CTShape3D ctShape3D = CTShape3D.Factory.newInstance(); - Assert.assertNotNull(ctShape3D); + assertNotNull(ctShape3D); CTScene3D ctScene3D = CTScene3D.Factory.newInstance(); - Assert.assertNotNull(ctScene3D); + assertNotNull(ctScene3D); CTEffectContainer ctEffectContainer = CTEffectContainer.Factory.newInstance(); - Assert.assertNotNull(ctEffectContainer); + assertNotNull(ctEffectContainer); CTConnectionSite ctConnectionSite = CTConnectionSite.Factory.newInstance(); - Assert.assertNotNull(ctConnectionSite); + assertNotNull(ctConnectionSite); STLblAlgn stLblAlgn = STLblAlgn.Factory.newInstance(); - Assert.assertNotNull(stLblAlgn); + assertNotNull(stLblAlgn); STBlackWhiteMode stBlackWhiteMode = STBlackWhiteMode.Factory.newInstance(); - Assert.assertNotNull(stBlackWhiteMode); + assertNotNull(stBlackWhiteMode); STRectAlignment stRectAlignment = STRectAlignment.Factory.newInstance(); - Assert.assertNotNull(stRectAlignment); + assertNotNull(stRectAlignment); STTileFlipMode stTileFlipMode = STTileFlipMode.Factory.newInstance(); - Assert.assertNotNull(stTileFlipMode); + assertNotNull(stTileFlipMode); STPresetPatternVal stPresetPatternVal = STPresetPatternVal.Factory.newInstance(); - Assert.assertNotNull(stPresetPatternVal); + assertNotNull(stPresetPatternVal); STOnOffStyleType stOnOffStyleType = STOnOffStyleType.Factory.newInstance(); - Assert.assertNotNull(stOnOffStyleType); + assertNotNull(stOnOffStyleType); CTLineJoinBevel ctLineJoinBevel = CTLineJoinBevel.Factory.newInstance(); - Assert.assertNotNull(ctLineJoinBevel); + assertNotNull(ctLineJoinBevel); CTLineJoinMiterProperties ctLineJoinMiterProperties = CTLineJoinMiterProperties.Factory.newInstance(); - Assert.assertNotNull(ctLineJoinMiterProperties); + assertNotNull(ctLineJoinMiterProperties); CTTileInfoProperties ctTileInfoProperties = CTTileInfoProperties.Factory.newInstance(); - Assert.assertNotNull(ctTileInfoProperties); + assertNotNull(ctTileInfoProperties); CTTableStyleTextStyle ctTableStyleTextStyle = CTTableStyleTextStyle.Factory.newInstance(); - Assert.assertNotNull(ctTableStyleTextStyle); + assertNotNull(ctTableStyleTextStyle); CTHeaderFooter ctHeaderFooter = CTHeaderFooter.Factory.newInstance(); - Assert.assertNotNull(ctHeaderFooter); + assertNotNull(ctHeaderFooter); CTMarkerSize ctMarkerSize = CTMarkerSize.Factory.newInstance(); - Assert.assertNotNull(ctMarkerSize); + assertNotNull(ctMarkerSize); CTDLbls ctdLbls = CTDLbls.Factory.newInstance(); - Assert.assertNotNull(ctdLbls); + assertNotNull(ctdLbls); CTMarker ctMarker = CTMarker.Factory.newInstance(); - Assert.assertNotNull(ctMarker); + assertNotNull(ctMarker); STMarkerStyle stMarkerStyle = STMarkerStyle.Factory.newInstance(); - Assert.assertNotNull(stMarkerStyle); + assertNotNull(stMarkerStyle); CTMarkerStyle ctMarkerStyle = CTMarkerStyle.Factory.newInstance(); - Assert.assertNotNull(ctMarkerStyle); + assertNotNull(ctMarkerStyle); CTExternalData ctExternalData = CTExternalData.Factory.newInstance(); - Assert.assertNotNull(ctExternalData); + assertNotNull(ctExternalData); CTAxisUnit ctAxisUnit = CTAxisUnit.Factory.newInstance(); - Assert.assertNotNull(ctAxisUnit); + assertNotNull(ctAxisUnit); CTLblAlgn ctLblAlgn = CTLblAlgn.Factory.newInstance(); - Assert.assertNotNull(ctLblAlgn); + assertNotNull(ctLblAlgn); CTDashStopList ctDashStopList = CTDashStopList.Factory.newInstance(); - Assert.assertNotNull(ctDashStopList); + assertNotNull(ctDashStopList); STDispBlanksAs stDashBlanksAs = STDispBlanksAs.Factory.newInstance(); - Assert.assertNotNull(stDashBlanksAs); + assertNotNull(stDashBlanksAs); CTDispBlanksAs ctDashBlanksAs = CTDispBlanksAs.Factory.newInstance(); - Assert.assertNotNull(ctDashBlanksAs); + assertNotNull(ctDashBlanksAs); CTAreaChart ctAreaChart = CTAreaChart.Factory.newInstance(); - Assert.assertNotNull(ctAreaChart); + assertNotNull(ctAreaChart); CTArea3DChart ctArea3DChart = CTArea3DChart.Factory.newInstance(); - Assert.assertNotNull(ctArea3DChart); + assertNotNull(ctArea3DChart); CTSurfaceChart ctSurfaceChart = CTSurfaceChart.Factory.newInstance(); - Assert.assertNotNull(ctSurfaceChart); + assertNotNull(ctSurfaceChart); CTDoughnutChart ctDoughnutChart = CTDoughnutChart.Factory.newInstance(); - Assert.assertNotNull(ctDoughnutChart); + assertNotNull(ctDoughnutChart); CTBar3DChart ctBar3DChart = CTBar3DChart.Factory.newInstance(); - Assert.assertNotNull(ctBar3DChart); + assertNotNull(ctBar3DChart); CTLine3DChart ctLine3DChart = CTLine3DChart.Factory.newInstance(); - Assert.assertNotNull(ctLine3DChart); + assertNotNull(ctLine3DChart); CTPie3DChart ctPie3DChart = CTPie3DChart.Factory.newInstance(); - Assert.assertNotNull(ctPie3DChart); + assertNotNull(ctPie3DChart); CTSurface3DChart ctSurface3DChart = CTSurface3DChart.Factory.newInstance(); - Assert.assertNotNull(ctSurface3DChart); + assertNotNull(ctSurface3DChart); CTAreaSer ctAreaSer = CTAreaSer.Factory.newInstance(); - Assert.assertNotNull(ctAreaSer); + assertNotNull(ctAreaSer); CTSurfaceSer ctSurfaceSer = CTSurfaceSer.Factory.newInstance(); - Assert.assertNotNull(ctSurfaceSer); + assertNotNull(ctSurfaceSer); CTView3D ctView3D = CTView3D.Factory.newInstance(); - Assert.assertNotNull(ctView3D); + assertNotNull(ctView3D); STShape stShape = STShape.Factory.newInstance(); - Assert.assertNotNull(stShape); + assertNotNull(stShape); STLblAlgn.Enum e1 = STLblAlgn.Enum.forString("ctr"); - Assert.assertNotNull(e1); + assertNotNull(e1); STBlackWhiteMode.Enum e2 = STBlackWhiteMode.Enum.forString("clr"); - Assert.assertNotNull(e2); + assertNotNull(e2); STRectAlignment.Enum e3 = STRectAlignment.Enum.forString("ctr"); - Assert.assertNotNull(e3); + assertNotNull(e3); STTileFlipMode.Enum e4 = STTileFlipMode.Enum.forString("xy"); - Assert.assertNotNull(e4); + assertNotNull(e4); STPresetPatternVal.Enum e5 = STPresetPatternVal.Enum.forString("horz"); - Assert.assertNotNull(e5); + assertNotNull(e5); STMarkerStyle.Enum e6 = STMarkerStyle.Enum.forString("circle"); - Assert.assertNotNull(e6); + assertNotNull(e6); STDispBlanksAs.Enum e7 = STDispBlanksAs.Enum.forString("span"); - Assert.assertNotNull(e7); + assertNotNull(e7); STShape.Enum e8 = STShape.Enum.forString("cone"); - Assert.assertNotNull(e8); + assertNotNull(e8); CTTextBulletTypefaceFollowText ctTextBulletTypefaceFollowText = CTTextBulletTypefaceFollowText.Factory.newInstance(); - Assert.assertNotNull(ctTextBulletTypefaceFollowText); + assertNotNull(ctTextBulletTypefaceFollowText); CTTextBulletSizeFollowText ctTextBulletSizeFollowText = CTTextBulletSizeFollowText.Factory.newInstance(); - Assert.assertNotNull(ctTextBulletSizeFollowText); + assertNotNull(ctTextBulletSizeFollowText); CTTextBulletColorFollowText ctTextBulletColorFollowText = CTTextBulletColorFollowText.Factory.newInstance(); - Assert.assertNotNull(ctTextBulletColorFollowText); + assertNotNull(ctTextBulletColorFollowText); CTTextBlipBullet ctTextBlipBullet = CTTextBlipBullet.Factory.newInstance(); - Assert.assertNotNull(ctTextBlipBullet); + assertNotNull(ctTextBlipBullet); CTRotX ctRotX = CTRotX.Factory.newInstance(); - Assert.assertNotNull(ctRotX); + assertNotNull(ctRotX); CTRotY ctRotY = CTRotY.Factory.newInstance(); - Assert.assertNotNull(ctRotY); + assertNotNull(ctRotY); CTPerspective ctPerspective = CTPerspective.Factory.newInstance(); - Assert.assertNotNull(ctPerspective); + assertNotNull(ctPerspective); CTDepthPercent ctDepthPercent = CTDepthPercent.Factory.newInstance(); - Assert.assertNotNull(ctDepthPercent); + assertNotNull(ctDepthPercent); CTHPercent ctHPercent = CTHPercent.Factory.newInstance(); - Assert.assertNotNull(ctHPercent); + assertNotNull(ctHPercent); CTShape ctShape = CTShape.Factory.newInstance(); - Assert.assertNotNull(ctShape); + assertNotNull(ctShape); CTOverlap ctOverlap = CTOverlap.Factory.newInstance(); - Assert.assertNotNull(ctOverlap); + assertNotNull(ctOverlap); CTFirstSliceAng ctFirstSliceAng = CTFirstSliceAng.Factory.newInstance(); - Assert.assertNotNull(ctFirstSliceAng); + assertNotNull(ctFirstSliceAng); - Assert.assertNotNull(ErrorBarType.BOTH); - Assert.assertNotNull(ErrorValueType.CUSTOM); - Assert.assertNotNull(ErrorDirection.X); + assertNotNull(ErrorBarType.BOTH); + assertNotNull(ErrorValueType.CUSTOM); + assertNotNull(ErrorDirection.X); XDDFErrorBars xeb = new XDDFErrorBars(); - Assert.assertNotNull(xeb); - Assert.assertNull(xeb.getErrorBarType()); - Assert.assertNull(xeb.getErrorDirection()); - Assert.assertNull(xeb.getErrorValueType()); + assertNotNull(xeb); + assertNull(xeb.getErrorBarType()); + assertNull(xeb.getErrorDirection()); + assertNull(xeb.getErrorValueType()); - Assert.assertNotNull(CTErrBarType.Factory.newInstance()); - Assert.assertNotNull(CTErrValType.Factory.newInstance()); - Assert.assertNotNull(CTErrDir.Factory.newInstance()); + assertNotNull(CTErrBarType.Factory.newInstance()); + assertNotNull(CTErrValType.Factory.newInstance()); + assertNotNull(CTErrDir.Factory.newInstance()); STErrBarType.Enum e9 = STErrBarType.Enum.forString("both"); - Assert.assertNotNull(e9); + assertNotNull(e9); STErrValType.Enum e10 = STErrValType.Enum.forString("percentage"); - Assert.assertNotNull(e10); + assertNotNull(e10); STErrDir.Enum e11 = STErrDir.Enum.forString("x"); - Assert.assertNotNull(e11); + assertNotNull(e11); CTErrBars bars = CTErrBars.Factory.newInstance(); - Assert.assertNotNull(bars); + assertNotNull(bars); } } diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java index ca0775dd2f..fc9f9c0f89 100644 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java +++ b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java @@ -17,14 +17,15 @@ package org.apache.poi.xddf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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.IOException; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFTheme; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; import org.openxmlformats.schemas.drawingml.x2006.main.CTScRgbColor; @@ -45,20 +46,23 @@ public class TestXDDFColor { XSLFTheme theme = ppt.createSlide().getTheme(); XDDFColor color = XDDFColor.forColorContainer(getThemeColor(theme, STSchemeColorVal.ACCENT_2)); + assertNotNull(color); // accent2 in theme1.xml is Diff d1 = DiffBuilder.compare(Input.fromString(" iter = iterable.iterator(); for (String element : expected) { - Assert.assertTrue(iter.hasNext()); - Assert.assertEquals(element, iter.next()); + assertTrue(iter.hasNext()); + assertEquals(element, iter.next()); } - Assert.assertFalse(iter.hasNext()); + assertFalse(iter.hasNext()); } @Test diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java index 15f2813b64..244b511ff0 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java @@ -17,14 +17,14 @@ package org.apache.poi.xslf; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import org.apache.xmlbeans.XmlObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; // aim is to get these classes loaded and included in poi-ooxml-lite.jar public class TestNecessaryOOXMLClasses { diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java index adfa7ed46e..af0eb8581c 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java @@ -20,14 +20,14 @@ import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_HREF; import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL; import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; +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 static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.Color; import java.awt.Dimension; @@ -104,9 +104,9 @@ import org.apache.poi.xslf.usermodel.XSLFTextBox; import org.apache.poi.xslf.usermodel.XSLFTextParagraph; import org.apache.poi.xslf.usermodel.XSLFTextRun; import org.apache.poi.xslf.util.DummyGraphics2d; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; @@ -115,7 +115,7 @@ public class TestXSLFBugs { private static boolean xslfOnly; - @BeforeClass + @BeforeAll public static void checkHslf() { try { Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); @@ -126,14 +126,14 @@ public class TestXSLFBugs { @Test public void bug62929() throws Exception { - try(XMLSlideShow ss1 = openSampleDocument("missing-blip-fill.pptx")) { + try (XMLSlideShow ss1 = openSampleDocument("missing-blip-fill.pptx")) { assertEquals(1, ss1.getSlides().size()); XSLFSlide slide = ss1.getSlides().get(0); assertEquals(slide.getShapes().size(), 1); - XSLFPictureShape picture = (XSLFPictureShape)slide.getShapes().get(0); + XSLFPictureShape picture = (XSLFPictureShape) slide.getShapes().get(0); assertEquals(picture.getShapeId(), 662); assertFalse(picture.isExternalLinkedPicture()); @@ -234,7 +234,7 @@ public class TestXSLFBugs { XSLFSlide slide2 = src.createSlide(); XSLFTextBox shape = slide.createTextBox(); - shape.setAnchor(new Rectangle2D.Double(100,100,400,100)); + shape.setAnchor(new Rectangle2D.Double(100, 100, 400, 100)); XSLFTextParagraph p = shape.addNewTextParagraph(); XSLFTextRun r = p.addNewTextRun(); @@ -247,7 +247,7 @@ public class TestXSLFBugs { r.createHyperlink().linkToSlide(slide2); shape = slide2.createTextBox(); - shape.setAnchor(new Rectangle2D.Double(100,100,400,100)); + shape.setAnchor(new Rectangle2D.Double(100, 100, 400, 100)); shape.setText("slide 2"); dest.createSlide().importContent(slide); @@ -258,7 +258,7 @@ public class TestXSLFBugs { try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { XSLFSlide slide = ppt.getSlides().get(0); - XSLFTextBox shape = (XSLFTextBox)slide.getShapes().get(0); + XSLFTextBox shape = (XSLFTextBox) slide.getShapes().get(0); XSLFTextParagraph p = shape.getTextParagraphs().get(1); XSLFHyperlink h1 = p.getTextRuns().get(0).getHyperlink(); assertNotNull(h1); @@ -276,16 +276,16 @@ public class TestXSLFBugs { public void bug62587() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (XMLSlideShow ppt = new XMLSlideShow()) { - Slide slide = ppt.createSlide(); + Slide slide = ppt.createSlide(); XSLFPictureData pd = ppt.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF); - PictureShape ps = slide.createPicture(pd); - ps.setAnchor(new Rectangle2D.Double(100,100,100,100)); + PictureShape ps = slide.createPicture(pd); + ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); ppt.write(bos); } Object[][] pics = { {"santa.wmf", PictureType.WMF, XSLFRelation.IMAGE_WMF}, - {"tomcat.png",PictureType.PNG, XSLFRelation.IMAGE_PNG}, + {"tomcat.png", PictureType.PNG, XSLFRelation.IMAGE_PNG}, {"clock.jpg", PictureType.JPEG, XSLFRelation.IMAGE_JPEG} }; @@ -296,7 +296,7 @@ public class TestXSLFBugs { XSLFSlide s2 = ppt.createSlide(); s2.importContent(s1); - XSLFPictureData pd = ppt.addPicture(slTests.getFile((String)p[0]), (PictureType)p[1]); + XSLFPictureData pd = ppt.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]); XSLFPictureShape ps = (XSLFPictureShape) s2.getShapes().get(0); Rectangle2D anchor = ps.getAnchor(); s2.removeShape(ps); @@ -340,7 +340,7 @@ public class TestXSLFBugs { assertTrue(shapeToDelete1.isPresent()); slide1.removeShape(shapeToDelete1.get()); assertTrue(slide1.getRelationParts().stream() - .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId()) )); + .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId()))); assertNotNull(ppt1.getPackage().getPart(ppn)); ppt1.close(); @@ -353,7 +353,7 @@ public class TestXSLFBugs { assertTrue(shapeToDelete2.isPresent()); slide2.removeShape(shapeToDelete2.get()); assertTrue(slide2.getRelationParts().stream() - .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId()) )); + .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId()))); assertNotNull(ppt2.getPackage().getPart(ppn)); ppt2.close(); @@ -369,34 +369,34 @@ public class TestXSLFBugs { @Test public void bug51187() throws Exception { - XMLSlideShow ss1 = openSampleDocument("51187.pptx"); + XMLSlideShow ss1 = openSampleDocument("51187.pptx"); - assertEquals(1, ss1.getSlides().size()); + assertEquals(1, ss1.getSlides().size()); - // Check the relations on it - // Note - rId3 is a self reference - XSLFSlide slide0 = ss1.getSlides().get(0); + // Check the relations on it + // Note - rId3 is a self reference + XSLFSlide slide0 = ss1.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); + assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); + assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); + assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); + // Save and re-load + XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); + ss1.close(); + assertEquals(1, ss2.getSlides().size()); - slide0 = ss2.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - // TODO Fix this - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); + slide0 = ss2.getSlides().get(0); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); + assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); + // TODO Fix this + assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); + assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - ss2.close(); + ss2.close(); } private static void assertRelation(XSLFSlide slide, String exp, String rId) { @@ -410,53 +410,47 @@ public class TestXSLFBugs { */ @Test public void tika705() throws Exception { - XMLSlideShow ss = openSampleDocument("with_japanese.pptx"); + XMLSlideShow ss = openSampleDocument("with_japanese.pptx"); - // Should have one slide - assertEquals(1, ss.getSlides().size()); - XSLFSlide slide = ss.getSlides().get(0); + // Should have one slide + assertEquals(1, ss.getSlides().size()); + XSLFSlide slide = ss.getSlides().get(0); - // Check the relations from this - Collection rels = slide.getRelationParts(); + // Check the relations from this + Collection rels = slide.getRelationParts(); - // Should have 6 relations: - // 1 external hyperlink (skipped from list) - // 4 internal hyperlinks - // 1 slide layout - assertEquals(5, rels.size()); - int layouts = 0; - int hyperlinks = 0; - for(RelationPart p : rels) { - if(p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - hyperlinks++; - } else if(p.getDocumentPart() instanceof XSLFSlideLayout) { - layouts++; - } - } - assertEquals(1, layouts); - assertEquals(4, hyperlinks); + // Should have 6 relations: + // 1 external hyperlink (skipped from list) + // 4 internal hyperlinks + // 1 slide layout + assertEquals(5, rels.size()); + int layouts = 0; + int hyperlinks = 0; + for (RelationPart p : rels) { + if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { + hyperlinks++; + } else if (p.getDocumentPart() instanceof XSLFSlideLayout) { + layouts++; + } + } + assertEquals(1, layouts); + assertEquals(4, hyperlinks); - // Hyperlinks should all be to #_ftn1 or #ftnref1 - for(RelationPart p : rels) { - if(p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - URI target = p.getRelationship().getTargetURI(); - - //noinspection StatementWithEmptyBody - if(target.getFragment().equals("_ftn1") || - target.getFragment().equals("_ftnref1")) { - // Good - } else { - fail("Invalid target " + target.getFragment() + " on " + target); - } - } - } - ss.close(); + // Hyperlinks should all be to #_ftn1 or #ftnref1 + for (RelationPart p : rels) { + if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { + URI target = p.getRelationship().getTargetURI(); + String frag = target.getFragment(); + assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target); + } + } + ss.close(); } /** * A slideshow can have more than one rID pointing to a given - * slide, eg presentation.xml rID1 -> slide1.xml, but slide1.xml - * rID2 -> slide3.xml + * slide, eg presentation.xml rID1 -> slide1.xml, but slide1.xml + * rID2 -> slide3.xml */ @Test public void bug54916() throws IOException { @@ -493,12 +487,12 @@ public class TestXSLFBugs { int internalPictures = 0; int externalPictures = 0; - for (XSLFSlide slide : ppt.getSlides()){ - for (XSLFShape shape : slide.getShapes()){ + for (XSLFSlide slide : ppt.getSlides()) { + for (XSLFShape shape : slide.getShapes()) { assertNotNull(shape); if (shape instanceof XSLFPictureShape) { - XSLFPictureShape picture = (XSLFPictureShape)shape; + XSLFPictureShape picture = (XSLFPictureShape) shape; if (picture.isExternalLinkedPicture()) { externalPictures++; @@ -520,7 +514,7 @@ public class TestXSLFBugs { } @Test - @Ignore("Similar to TestFontRendering it doesn't make sense to compare images because of tiny rendering differences in windows/unix") + @Disabled("Similar to TestFontRendering it doesn't make sense to compare images because of tiny rendering differences in windows/unix") public void bug54542() throws Exception { XMLSlideShow ss = openSampleDocument("54542_cropped_bitmap.pptx"); @@ -533,7 +527,7 @@ public class TestXSLFBugs { AffineTransform at = new AffineTransform(); at.setToScale(zoom, zoom); - BufferedImage imgActual = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_3BYTE_BGR); + BufferedImage imgActual = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = imgActual.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); @@ -549,7 +543,7 @@ public class TestXSLFBugs { } private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException { - try (SlideShowExtractor extr = new SlideShowExtractor<>(ppt)) { + try (SlideShowExtractor extr = new SlideShowExtractor<>(ppt)) { // do not auto-close the slideshow extr.setCloseFilesystem(false); extr.setSlidesByDefault(true); @@ -562,38 +556,38 @@ public class TestXSLFBugs { @Test public void bug57250() throws Exception { XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1","Slide2"}) { + for (String s : new String[]{"Slide1", "Slide2"}) { ss.createSlide().createTextBox().setText(s); } - validateSlides(ss, false, "Slide1","Slide2"); + validateSlides(ss, false, "Slide1", "Slide2"); XSLFSlide slide = ss.createSlide(); slide.createTextBox().setText("New slide"); - validateSlides(ss, true, "Slide1","Slide2","New slide"); + validateSlides(ss, true, "Slide1", "Slide2", "New slide"); // Move backward ss.setSlideOrder(slide, 0); - validateSlides(ss, true, "New slide","Slide1","Slide2"); + validateSlides(ss, true, "New slide", "Slide1", "Slide2"); // Move forward ss.setSlideOrder(slide, 1); - validateSlides(ss, true, "Slide1","New slide","Slide2"); + validateSlides(ss, true, "Slide1", "New slide", "Slide2"); // Move to end ss.setSlideOrder(slide, 0); ss.setSlideOrder(slide, 2); - validateSlides(ss, true, "Slide1","Slide2","New slide"); + validateSlides(ss, true, "Slide1", "Slide2", "New slide"); ss.close(); } /** * When working with >9 images, make sure the sorting ensures - * that image10.foo isn't between image1.foo and image2.foo + * that image10.foo isn't between image1.foo and image2.foo */ @Test public void test57552() throws Exception { XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1","Slide2"}) { + for (String s : new String[]{"Slide1", "Slide2"}) { ss.createSlide().createTextBox().setText(s); } @@ -612,7 +606,7 @@ public class TestXSLFBugs { // Some dummy pictures byte[][] pics = new byte[15][3]; - for (int i=0; i ppt = SlideShowFactory.create(slTests.getFile("WithLinks.ppt"))) { - Slide slide = ppt.getSlides().get(0); - TextShape shape = (TextShape) slide.getShapes().get(1); + try (SlideShow ppt = SlideShowFactory.create(slTests.getFile("WithLinks.ppt"))) { + Slide slide = ppt.getSlides().get(0); + TextShape shape = (TextShape) slide.getShapes().get(1); TextRun r = shape.getTextParagraphs().get(1).getTextRuns().get(0); - Hyperlink hlRun = r.getHyperlink(); + Hyperlink hlRun = r.getHyperlink(); assertNotNull(hlRun); assertEquals("http://jakarta.apache.org/poi/", hlRun.getAddress()); assertEquals("http://jakarta.apache.org/poi/", hlRun.getLabel()); @@ -1074,7 +1064,7 @@ public class TestXSLFBugs { if ("Jakarta HSSF".equals(sb.toString())) { // this is a test for a manually modified ppt, for real hyperlink label // one would need to access the screen tip record - Attribute[] obj = { HYPERLINK_HREF, HYPERLINK_LABEL }; + Attribute[] obj = {HYPERLINK_HREF, HYPERLINK_LABEL}; assertNotNull(attributes); Stream.of(obj).map(attributes::get).forEach(strings::add); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java index ab28bae825..c6179fa095 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java @@ -33,25 +33,25 @@ import org.apache.poi.xslf.usermodel.XSLFRelation; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFSlideShow; import org.apache.xmlbeans.XmlException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class TestXSLFSlideShow { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); private OPCPackage pack; - @Before + @BeforeEach public void setUp() throws Exception { pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); } - @After + @AfterEach public void tearDown() throws IOException { pack.close(); } @@ -73,18 +73,18 @@ public class TestXSLFSlideShow { XSLFSlideShow xml = new XSLFSlideShow(pack); // Check the core assertNotNull(xml.getPresentation()); - + // Check it has some slides assertNotEquals(0, xml.getSlideReferences().sizeOfSldIdArray()); assertNotEquals(0, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - + xml.close(); } - + @Test public void testSlideBasics() throws IOException, OpenXML4JException, XmlException { XSLFSlideShow xml = new XSLFSlideShow(pack); - + // Should have 1 master assertEquals(1, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); @@ -98,62 +98,62 @@ public class TestXSLFSlideShow { assertEquals(257, slides[1].getId()); assertEquals("rId2", slides[0].getId2()); assertEquals("rId3", slides[1].getId2()); - + // Now get those objects assertNotNull(xml.getSlide(slides[0])); assertNotNull(xml.getSlide(slides[1])); - + // And check they have notes as expected assertNotNull(xml.getNotes(slides[0])); assertNotNull(xml.getNotes(slides[1])); - + // And again for the master CTSlideMasterIdListEntry[] masters = xml.getSlideMasterReferences().getSldMasterIdArray(); - + // see SlideAtom.USES_MASTER_SLIDE_ID assertEquals(0x80000000L, masters[0].getId()); assertEquals("rId1", masters[0].getId2()); assertNotNull(xml.getSlideMaster(masters[0])); - + xml.close(); } - + @Test public void testMetadataBasics() throws IOException, OpenXML4JException, XmlException { XSLFSlideShow xml = new XSLFSlideShow(pack); - + assertNotNull(xml.getProperties().getCoreProperties()); assertNotNull(xml.getProperties().getExtendedProperties()); - + CTProperties props = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); assertEquals("Microsoft Office PowerPoint", props.getApplication()); assertEquals(0, props.getCharacters()); assertEquals(0, props.getLines()); - + CoreProperties cprops = xml.getProperties().getCoreProperties(); assertNull(cprops.getTitle()); assertFalse(cprops.getUnderlyingProperties().getSubjectProperty().isPresent()); - + xml.close(); } - + @Test public void testMasterBackground() throws IOException { XMLSlideShow ppt = new XMLSlideShow(); XSLFBackground b = ppt.getSlideMasters().get(0).getBackground(); b.setFillColor(Color.RED); - + XSLFSlide sl = ppt.createSlide(); XSLFAutoShape as = sl.createAutoShape(); as.setAnchor(new Rectangle2D.Double(100,100,100,100)); as.setShapeType(ShapeType.CLOUD); - + XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); ppt.close(); - + XSLFBackground b2 = ppt2.getSlideMasters().get(0).getBackground(); assertEquals(Color.RED, b2.getFillColor()); - + ppt2.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java b/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java index eb86a217f2..f8459a89c5 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java @@ -19,10 +19,10 @@ package org.apache.poi.xslf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertNotContained; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.File; import java.io.IOException; @@ -34,7 +34,7 @@ import org.apache.poi.sl.extractor.SlideShowExtractor; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFTextParagraph; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSLFPowerPointExtractor @@ -245,11 +245,11 @@ public class TestXSLFPowerPointExtractor { String text = extractor.getText(); if (extension.equals("thmx")) { // Theme file doesn't have any textual content - assertEquals(filename, 0, text.length()); + assertEquals(0, text.length(), filename); continue; } - assertTrue(filename, text.length() > 0); + assertTrue(text.length() > 0, filename); assertContains(filename, text, "Attachment Test"); assertContains(filename, text, "This is a test file data with the same content"); assertContains(filename, text, "content parsing"); @@ -267,7 +267,7 @@ public class TestXSLFPowerPointExtractor { try (final SlideShowExtractor extr = (SlideShowExtractor) ExtractorFactory.createExtractor(headerFile)) { String text = extr.getText(); assertNotNull(text); - assertFalse("Had: " + text, text.contains("testdoc")); + assertFalse(text.contains("testdoc"), "Had: " + text); extr.setSlidesByDefault(false); extr.setNotesByDefault(true); diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java index 043a8e1209..586a528634 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java @@ -20,32 +20,27 @@ package org.apache.poi.xslf.usermodel; import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.function.Function; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.poi.POIDataSamples; import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Test class for testing PPTX2PNG utility which renders .ppt and .pptx slideshows */ @SuppressWarnings("ConstantConditions") -@RunWith(Parameterized.class) public class TestPPTX2PNG { private static boolean xslfOnly; private static final POIDataSamples samples = POIDataSamples.getSlideShowInstance(); @@ -63,7 +58,7 @@ public class TestPPTX2PNG { private static final String pdfFiles = "alterman_security.ppt"; - @BeforeClass + @BeforeAll public static void checkHslf() { try { Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); @@ -72,33 +67,29 @@ public class TestPPTX2PNG { } } - // use filename instead of File object to omit full pathname in test name - @Parameter - public String pptFile; + public static Stream data() { + Function> fun = (basedir == null) + ? (f) -> Stream.of(Arguments.of(f)) + : (f) -> Stream.of(basedir.listFiles(p -> p.getName().matches(f))).map(File::getName).map(Arguments::of); - - - @Parameters(name="{0}") - public static Collection data() { - Function> fun = (basedir == null) ? Stream::of : - (f) -> Stream.of(basedir.listFiles(p -> p.getName().matches(f))).map(File::getName); - - return Stream.of(files.split(", ?")).flatMap(fun).collect(Collectors.toList()); + return Stream.of(files.split(", ?")).flatMap(fun); } - @Test - public void render() throws Exception { - assumeFalse("ignore HSLF (.ppt) / HEMF (.emf) / HWMF (.wmf) files in no-scratchpad run", xslfOnly && pptFile.matches(".*\\.(ppt|emf|wmf)$")); - PPTX2PNG.main(getArgs("null")); + // use filename instead of File object to omit full pathname in test name + @ParameterizedTest + @MethodSource("data") + public void render(String pptFile) throws Exception { + assumeFalse(xslfOnly && pptFile.matches(".*\\.(ppt|emf|wmf)$"), "ignore HSLF (.ppt) / HEMF (.emf) / HWMF (.wmf) files in no-scratchpad run"); + PPTX2PNG.main(getArgs(pptFile, "null")); if (svgFiles.contains(pptFile)) { - PPTX2PNG.main(getArgs("svg")); + PPTX2PNG.main(getArgs(pptFile, "svg")); } if (pdfFiles.contains(pptFile)) { - PPTX2PNG.main(getArgs("pdf")); + PPTX2PNG.main(getArgs(pptFile, "pdf")); } } - private String[] getArgs(String format) throws IOException { + private String[] getArgs(String pptFile, String format) throws IOException { File tmpDir = new File("build/tmp/"); // fix maven build errors diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java index 715daa47c8..3e529ed96e 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java @@ -16,12 +16,11 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -31,177 +30,172 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.sl.usermodel.BaseTestSlideShow; import org.apache.poi.sl.usermodel.SlideShow; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMasterIdListEntry; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; -public class TestXMLSlideShow extends BaseTestSlideShow { - private OPCPackage pack; +public class TestXMLSlideShow extends BaseTestSlideShow { + private OPCPackage pack; - @Override - public XMLSlideShow createSlideShow() { - return new XMLSlideShow(); - } + @Override + public XMLSlideShow createSlideShow() { + return new XMLSlideShow(); + } - @Before - public void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } + @BeforeEach + public void setUp() throws Exception { + pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); + } - @After - public void tearDown() { - pack.revert(); - } + @AfterEach + public void tearDown() { + pack.revert(); + } - @Test - public void testContainsMainContentType() throws Exception { - boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } + @Test + public void testContainsMainContentType() throws Exception { + boolean found = false; + for (PackagePart part : pack.getParts()) { + if (part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { + found = true; + } + } + assertTrue(found); + } - @Test - public void testOpen() throws Exception { - // With the finalised uri, should be fine - XMLSlideShow xml = new XMLSlideShow(pack); - // Check the core - assertNotNull(xml.getCTPresentation()); + @Test + public void testOpen() throws Exception { + // With the finalised uri, should be fine + XMLSlideShow xml = new XMLSlideShow(pack); + // Check the core + assertNotNull(xml.getCTPresentation()); - // Check it has some slides - assertFalse(xml.getSlides().isEmpty()); - assertFalse(xml.getSlideMasters().isEmpty()); + // Check it has some slides + assertFalse(xml.getSlides().isEmpty()); + assertFalse(xml.getSlideMasters().isEmpty()); - xml.close(); - } + xml.close(); + } - @SuppressWarnings("deprecation") - @Test - public void testSlideBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); + @SuppressWarnings("deprecation") + @Test + public void testSlideBasics() throws IOException { + XMLSlideShow xml = new XMLSlideShow(pack); - // Should have 1 master - assertEquals(1, xml.getSlideMasters().size()); + // Should have 1 master + assertEquals(1, xml.getSlideMasters().size()); - // Should have two sheets - assertEquals(2, xml.getSlides().size()); + // Should have two sheets + assertEquals(2, xml.getSlides().size()); - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); + // Check they're as expected + CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); + assertEquals(256, slides[0].getId()); + assertEquals(257, slides[1].getId()); + assertEquals("rId2", slides[0].getId2()); + assertEquals("rId3", slides[1].getId2()); - // Now get those objects - assertNotNull(xml.getSlides().get(0)); - assertNotNull(xml.getSlides().get(1)); + // Now get those objects + assertNotNull(xml.getSlides().get(0)); + assertNotNull(xml.getSlides().get(1)); - // And check they have notes as expected - assertNotNull(xml.getSlides().get(0).getNotes()); - assertNotNull(xml.getSlides().get(1).getNotes()); + // And check they have notes as expected + assertNotNull(xml.getSlides().get(0).getNotes()); + assertNotNull(xml.getSlides().get(1).getNotes()); - // Next up look for the slide master - CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); + // Next up look for the slide master + CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMasters().get(0)); + // see SlideAtom.USES_MASTER_SLIDE_ID + assertEquals(0x80000000L, masters[0].getId()); + assertEquals("rId1", masters[0].getId2()); + assertNotNull(xml.getSlideMasters().get(0)); - // Finally look for the notes master - CTNotesMasterIdListEntry notesMaster = - xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); - assertNotNull(notesMaster); + // Finally look for the notes master + CTNotesMasterIdListEntry notesMaster = + xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); + assertNotNull(notesMaster); - assertNotNull(xml.getNotesMaster()); + assertNotNull(xml.getNotesMaster()); - xml.close(); - } + xml.close(); + } - @Test - public void testMetadataBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); + @Test + public void testMetadataBasics() throws IOException { + XMLSlideShow xml = new XMLSlideShow(pack); - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); + assertNotNull(xml.getProperties().getCoreProperties()); + assertNotNull(xml.getProperties().getExtendedProperties()); - assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); + assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); + assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); + assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - assertNull(xml.getProperties().getCoreProperties().getTitle()); - assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); + assertNull(xml.getProperties().getCoreProperties().getTitle()); + assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); - xml.close(); - } + xml.close(); + } - @Test - public void testComments() throws Exception { - // Default sample file has none - XMLSlideShow xml = new XMLSlideShow(pack); + @Test + public void testComments() throws Exception { + // Default sample file has none + XMLSlideShow xml = new XMLSlideShow(pack); - assertNull(xml.getCommentAuthors()); + assertNull(xml.getCommentAuthors()); - for (XSLFSlide slide : xml.getSlides()) { - assertTrue(slide.getComments().isEmpty()); - } - - // Try another with comments - XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx")); - - // Has one author - assertNotNull(xmlComments.getCommentAuthors()); - assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); - assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); - - // First two slides have comments - int i = -1; - for (XSLFSlide slide : xmlComments.getSlides()) { - i++; - - if(i == 0) { - assertNotNull(slide.getCommentsPart()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else if (i == 1) { - assertNotNull(slide.getComments()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else { - assertNull(slide.getCommentsPart()); + for (XSLFSlide slide : xml.getSlides()) { assertTrue(slide.getComments().isEmpty()); - } - } + } - xmlComments.close(); - xml.close(); - } + // Try another with comments + XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx")); - @Override - public XMLSlideShow reopen(SlideShow show) { - try { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new XMLSlideShow(new ByteArrayInputStream(bos.getBuf())); - } catch (IOException e) { - fail(e.getMessage()); - return null; - } - } + // Has one author + assertNotNull(xmlComments.getCommentAuthors()); + assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); + assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); - private static class BufAccessBAOS extends ByteArrayOutputStream { - byte[] getBuf() { - return buf; - } - } + // First two slides have comments + int i = -1; + for (XSLFSlide slide : xmlComments.getSlides()) { + i++; + + if (i == 0) { + assertNotNull(slide.getCommentsPart()); + assertEquals(1, slide.getCommentsPart().getNumberOfComments()); + assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText()); + assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); + } else if (i == 1) { + assertNotNull(slide.getComments()); + assertEquals(1, slide.getCommentsPart().getNumberOfComments()); + assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText()); + assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); + } else { + assertNull(slide.getCommentsPart()); + assertTrue(slide.getComments().isEmpty()); + } + } + + xmlComments.close(); + xml.close(); + } + + @Override + public XMLSlideShow reopen(SlideShow show) throws IOException { + BufAccessBAOS bos = new BufAccessBAOS(); + show.write(bos); + return new XMLSlideShow(new ByteArrayInputStream(bos.getBuf())); + } + + private static class BufAccessBAOS extends ByteArrayOutputStream { + byte[] getBuf() { + return buf; + } + } } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java index 9c83ae9253..41c0ef83a0 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -31,7 +31,7 @@ import org.apache.poi.sl.usermodel.TextShape.TextAutofit; import org.apache.poi.sl.usermodel.TextShape.TextDirection; import org.apache.poi.sl.usermodel.VerticalAlignment; import org.apache.poi.util.Units; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; import org.openxmlformats.schemas.drawingml.x2006.main.STTextStrikeType; import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java index 1e0467fefd..88c7258e6d 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java @@ -17,14 +17,14 @@ package org.apache.poi.xslf.usermodel; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties; import org.openxmlformats.schemas.presentationml.x2006.main.impl.CTBackgroundImpl; import java.awt.*; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class TestXSLFBackground { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java index 493a0b89df..5cdaf3434a 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java @@ -18,12 +18,12 @@ */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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 java.util.List; @@ -56,7 +56,7 @@ import org.apache.poi.xddf.usermodel.chart.XDDFRadarChartData; import org.apache.poi.xddf.usermodel.chart.XDDFScatterChartData; import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * a modified version from POI-examples diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java index cfadb58cc0..1a870c59ac 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.io.IOException; import org.apache.poi.sl.usermodel.PresetColor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; import org.openxmlformats.schemas.drawingml.x2006.main.CTHslColor; import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; @@ -157,7 +157,7 @@ public class TestXSLFColor { xml = CTColor.Factory.newInstance(); STPresetColorVal.Enum preVal = STPresetColorVal.Enum.forString(pc.ooxmlId); STSystemColorVal.Enum sysVal = STSystemColorVal.Enum.forString(pc.ooxmlId); - assertTrue(pc.ooxmlId, preVal != null || sysVal != null); + assertTrue(preVal != null || sysVal != null, pc.ooxmlId); if (preVal != null) { xml.addNewPrstClr().setVal(preVal); } else { diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java index 03f29859a9..623ab833ef 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; import java.awt.Color; @@ -27,7 +27,7 @@ import java.io.IOException; import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; import org.apache.poi.sl.usermodel.ShapeType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTConnection; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualConnectorProperties; import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndLength; @@ -152,7 +152,7 @@ public class TestXSLFConnectorShape { end.setId(rect2.getShapeId()); // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 end.setIdx(3); - + pptx.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java index dc951a5404..aded0ad6df 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java @@ -34,7 +34,7 @@ import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.sl.usermodel.PictureData; import org.apache.xmlbeans.XmlCursor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; import org.openxmlformats.schemas.presentationml.x2006.main.CTExtension; diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java index 949e1951cb..28055881ce 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java @@ -18,7 +18,7 @@ package org.apache.poi.xslf.usermodel; import org.apache.poi.sl.draw.SLGraphics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; import java.awt.Color; @@ -34,7 +34,7 @@ import java.awt.image.BufferedImage; import java.io.IOException; import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestXSLFFreeformShape { @@ -58,7 +58,7 @@ public class TestXSLFFreeformShape { shape2.setPath(path2); assertEquals(getSpPr(shape1).getCustGeom().toString(), getSpPr(shape2).getCustGeom().toString()); - + ppt.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java index 6363177215..a1b28dd189 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.awt.Dimension; import java.awt.geom.Rectangle2D; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -36,7 +36,7 @@ public class TestXSLFGroupShape { XSLFSlide slide = ppt.createSlide(); ppt.setPageSize(new Dimension(792, 612)); - + XSLFGroupShape group = slide.createGroup(); assertEquals(1, slide.getShapes().size()); @@ -85,7 +85,7 @@ public class TestXSLFGroupShape { group.removeShape(shape1); group.removeShape(shape4); assertTrue(group.getShapes().isEmpty()); - + ppt.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java index 08dfe3913a..734e0e5c3e 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.awt.geom.Rectangle2D; import java.io.IOException; @@ -28,7 +28,7 @@ import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSLFHyperlink { diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java index 6ce747be72..d2b383863f 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java @@ -16,15 +16,15 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.sl.usermodel.Placeholder; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSLFNotes { @@ -51,7 +51,7 @@ public class TestXSLFNotes { } assertNotNull(note); assertEquals("New Note", note); - + ppt.close(); } @@ -74,7 +74,7 @@ public class TestXSLFNotes { } assertNotNull(note); assertEquals("New Note", note); - + ppt.close(); } @@ -100,7 +100,7 @@ public class TestXSLFNotes { assertNotNull(note); assertEquals("New Note", note); } - + ppt.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java index ae901c65db..ff44c00cb6 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; @@ -42,7 +42,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; import org.apache.poi.xslf.XSLFTestDataSamples; import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; public class TestXSLFPictureShape { diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java index 65ad0cace5..502f0eba1e 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java @@ -16,15 +16,15 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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 java.util.List; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; public class TestXSLFShape { @@ -79,7 +79,7 @@ public class TestXSLFShape { assertEquals("Subtitle", paragraphs2.get(0).getTextRuns().get(0).getRawText()); assertTrue(paragraphs2.get(0).getTextRuns().get(0).getRPr(false).getB()); assertEquals("And second line", paragraphs2.get(1).getTextRuns().get(0).getRawText()); - + ppt.close(); } @@ -109,7 +109,7 @@ public class TestXSLFShape { textBox.addNewTextParagraph().addNewTextRun().setText("POI"); assertEquals("Apache\nPOI", textBox.getText()); assertEquals(3, textBox.getTextParagraphs().size()); - + ppt.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java index 5bcca34380..865f95fa4e 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java @@ -18,11 +18,11 @@ */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * test common operations on containers of shapes (sheets and groups of shapes) diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java index b68577acac..a81c3baf9d 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.List; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * test common properties for sheets (slides, masters, layouts, etc.) @@ -30,7 +30,7 @@ import org.junit.Test; * @author Yegor Kozlov */ public class TestXSLFSheet { - + @Test public void testCreateShapes() throws IOException { XMLSlideShow ppt = new XMLSlideShow(); @@ -68,7 +68,7 @@ public class TestXSLFSheet { assertTrue(shapes.get(1) instanceof XSLFTextBox); assertTrue(shapes.get(2) instanceof XSLFConnectorShape); assertTrue(shapes.get(3) instanceof XSLFGroupShape); - + ppt.close(); ppt2.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java index 88ba9a576e..c96c7eecbb 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.io.File; @@ -35,7 +35,7 @@ import org.apache.poi.util.Units; import org.apache.poi.xslf.XSLFTestDataSamples; import org.apache.poi.xslf.util.PPTX2PNG; import org.apache.xmlbeans.XmlObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleItem; import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleList; import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java index 7c4ee09445..b7dbf9f685 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java @@ -17,19 +17,19 @@ package org.apache.poi.xslf.usermodel; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.io.IOException; import java.util.List; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java index 247f8d8799..e9e35bd9b7 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +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.Dimension; import java.io.IOException; @@ -26,7 +26,7 @@ import java.util.List; import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -56,7 +56,7 @@ public class TestXSLFSlideShow { XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); assertEquals(2, ppt2.getSlides().size()); rels = ppt2.getSlides().get(0).getRelations(); - + ppt2.close(); ppt.close(); } @@ -81,7 +81,7 @@ public class TestXSLFSlideShow { XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); assertEquals(1, ppt2.getSlides().size()); - + ppt2.close(); ppt.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java index b4fb08fef0..94bddc9e4f 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java @@ -17,9 +17,9 @@ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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.File; import java.io.FileOutputStream; @@ -36,7 +36,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); @@ -50,11 +50,8 @@ public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { public void testFactoryFromFile() { // Remove thrown.* when bug 58779 is resolved // In the mean time, this function will modify SampleShow.pptx on disk. - AssertionError ex = assertThrows( - "Bug 58779: " + removeExpectedExceptionMsg, - AssertionError.class, - () -> testFactoryFromFile(filename) - ); + AssertionError ex = assertThrows(AssertionError.class, () -> testFactoryFromFile(filename), + "Bug 58779: " + removeExpectedExceptionMsg); assertTrue(ex.getMessage().contains("SampleShow.pptx sample file was modified as a result of closing the slideshow")); } @@ -66,10 +63,8 @@ public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { @Test public void testFactoryFromNative() { // Remove thrown.* when unit test for XSLF SlideShowFactory.create(OPCPackage) is implemented - UnsupportedOperationException ex = assertThrows( - removeExpectedExceptionMsg, - UnsupportedOperationException.class, - () -> testFactoryFromNative(filename) + UnsupportedOperationException ex = assertThrows(UnsupportedOperationException.class, + () -> testFactoryFromNative(filename), removeExpectedExceptionMsg ); assertEquals("Test not implemented", ex.getMessage()); } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java index 99f665493f..abefbaa17a 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.awt.Dimension; @@ -42,7 +42,7 @@ import org.apache.poi.sl.usermodel.VerticalAlignment; import org.apache.poi.util.TempFile; import org.apache.poi.xslf.XSLFTestDataSamples; import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java index 47345133b8..c9338715ca 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java @@ -16,26 +16,26 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.List; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; public class TestXSLFTableRow { - + private static XMLSlideShow ppt; private static XSLFTable tbl; private static XSLFTableRow row; - + /** Copied from {@link TestXSLFTable#testRead()} */ - @Before + @BeforeEach public void setUp() throws IOException { ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); @@ -45,8 +45,8 @@ public class TestXSLFTableRow { List rows = tbl.getRows(); row = rows.get(0); } - - @After + + @AfterEach public void tearDown() throws IOException { ppt.getPackage().revert(); ppt.close(); @@ -59,14 +59,14 @@ public class TestXSLFTableRow { assertSame(row.getXmlObject(), row2.getXmlObject()); assertEquals(row.getHeight(), row2.getHeight(), 1e-16); } - + @Test public void testHeight() { final double h = 10.0; row.setHeight(h); assertEquals(h, row.getHeight(), 1e-16); } - + /** copied from {@link TestXSLFTable#testCreate()} */ @Test public void getCells() { @@ -74,7 +74,7 @@ public class TestXSLFTableRow { assertNotNull(cells); assertEquals(3, cells.size()); } - + @Test public void testIterator() { int i = 0; @@ -84,13 +84,13 @@ public class TestXSLFTableRow { } assertEquals(3, i); } - + /** copied from {@link TestXSLFTable#testCreate()} */ @Test public void addCell() { XSLFTableCell cell = row.addCell(); assertNotNull(cell); - + assertNotNull(cell.getXmlObject()); // by default table cell has no borders CTTableCell tc = (CTTableCell)cell.getXmlObject(); @@ -99,24 +99,20 @@ public class TestXSLFTableRow { assertTrue(tc.getTcPr().getLnL().isSetNoFill()); assertTrue(tc.getTcPr().getLnR().isSetNoFill()); } - + @Test public void mergeCells() { - try { - row.mergeCells(0, 0); - fail("expected IllegalArgumentException when merging fewer than 2 columns"); - } catch (final IllegalArgumentException e) { - // expected - } - + assertThrows(IllegalArgumentException.class, () -> row.mergeCells(0, 0), + "expected IllegalArgumentException when merging fewer than 2 columns"); + row.mergeCells(0, 1); List cells = row.getCells(); //the top-left cell of a merged region is not regarded as merged - assertFalse("top-left cell of merged region", cells.get(0).isMerged()); - assertTrue("inside merged region", cells.get(1).isMerged()); - assertFalse("outside merged region", cells.get(2).isMerged()); + assertFalse(cells.get(0).isMerged(), "top-left cell of merged region"); + assertTrue(cells.get(1).isMerged(), "inside merged region"); + assertFalse(cells.get(2).isMerged(), "outside merged region"); } - + @Test public void getXmlObject() { CTTableRow ctrow = row.getXmlObject(); @@ -134,12 +130,7 @@ public class TestXSLFTableRow { for (XSLFTableRow row : ((XSLFTable) shape).getRows()) { for (XSLFTableCell cell : row.getCells()) { assertNull(cell.getShapeName()); // Do not throw NPE - try { - cell.getShapeId(); - fail("expected getShapeId to fail"); - } catch (IllegalStateException ise) { - // expected - } + assertThrows(IllegalStateException.class, cell::getShapeId); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java index 710363747c..5cf4843db5 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSLFTableStyles { @@ -32,7 +32,7 @@ public class TestXSLFTableStyles { assertNotNull(tblStyles); assertEquals(0, tblStyles.getStyles().size()); - + ppt.close(); } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java index 6edc3bdf21..475f26b17c 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import org.apache.poi.sl.usermodel.Placeholder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; /** @@ -42,7 +42,7 @@ public class TestXSLFTextBox { shape.setPlaceholder(null); assertNull(shape.getTextType()); shape.setText("Apache POI"); - + ppt.close(); } @@ -84,7 +84,7 @@ public class TestXSLFTextBox { pPr.unsetSz(); // Should never be assertNull(r.getFontSize()); - + ppt.close(); } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java index 1a1396bdfe..3ca8b173b6 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java @@ -17,10 +17,12 @@ package org.apache.poi.xslf.usermodel; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.awt.Color; import java.awt.Graphics2D; @@ -34,8 +36,7 @@ import org.apache.poi.sl.draw.DrawTextParagraph; import org.apache.poi.sl.usermodel.AutoNumberingScheme; import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -159,7 +160,7 @@ public class TestXSLFTextParagraph { @Test public void testBreakLines() throws IOException { String os = System.getProperty("os.name"); - Assume.assumeTrue("Skipping testBreakLines(), it is executed only on Windows machines", (os != null && os.contains("Windows"))); + assumeTrue((os != null && os.contains("Windows")), "Skipping testBreakLines(), it is executed only on Windows machines"); XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); @@ -363,7 +364,7 @@ public class TestXSLFTextParagraph { ppt.close(); } - @Test(expected = IllegalStateException.class) + @Test public void testLineBreak() throws IOException { try (XMLSlideShow ppt = new XMLSlideShow()) { XSLFSlide slide = ppt.createSlide(); @@ -385,7 +386,7 @@ public class TestXSLFTextParagraph { assertEquals("Hello,\nWorld!\n", sh.getText()); // "You cannot change text of a line break, it is always '\\n'" - r2.setText("aaa"); + assertThrows(IllegalStateException.class, () -> r2.setText("aaa")); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java index dfa1d572ab..298f8b078d 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java @@ -19,10 +19,10 @@ package org.apache.poi.xslf.usermodel; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.io.IOException; @@ -30,7 +30,7 @@ import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.sl.draw.DrawTextParagraph; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java index e01db97bf1..2b8cc173de 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java @@ -18,13 +18,13 @@ package org.apache.poi.xslf.usermodel; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +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 static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.Color; import java.io.File; @@ -43,8 +43,8 @@ import org.apache.poi.xddf.usermodel.text.XDDFBodyProperties; import org.apache.poi.xddf.usermodel.text.XDDFTextBody; import org.apache.poi.xddf.usermodel.text.XDDFTextParagraph; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; @@ -55,7 +55,7 @@ import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; public class TestXSLFTextShape { private static boolean xslfOnly; - @BeforeClass + @BeforeAll public static void checkHslf() { try { Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java index 12ddf0eabd..38add3136a 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java @@ -17,10 +17,10 @@ package org.apache.poi.xslf.usermodel; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.awt.Color; import java.util.List; @@ -30,7 +30,7 @@ import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * test reading properties from a multi-theme and multi-master document diff --git a/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java b/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java deleted file mode 100644 index e6a61f0afa..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.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.xssf; - -import org.apache.poi.ss.tests.format.TestCellFormatPart; -import org.apache.poi.xssf.extractor.TestXSSFExcelExtractor; -import org.apache.poi.xssf.io.TestLoadSaveXSSF; -import org.apache.poi.xssf.model.TestCommentsTable; -import org.apache.poi.xssf.model.TestSharedStringsTable; -import org.apache.poi.xssf.usermodel.AllXSSFUsermodelTests; -import org.apache.poi.xssf.util.TestCTColComparator; -import org.apache.poi.xssf.util.TestNumericRanges; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.xssf and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllXSSFUsermodelTests.class, - //TestXSSFReader.class, //converted to junit4 - TestXSSFExcelExtractor.class, - TestLoadSaveXSSF.class, - TestCommentsTable.class, - TestSharedStringsTable.class, - //TestStylesTable.class, //converted to junit4 - //TestCellReference.class, //converted to junit4 - TestCTColComparator.class, - TestNumericRanges.class, - TestCellFormatPart.class, - TestXSSFCloneSheet.class -}) -public final class AllXSSFTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java index 9884584e8e..5938498387 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java @@ -17,8 +17,9 @@ package org.apache.poi.xssf; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; @@ -30,7 +31,7 @@ public class TestNecessaryOOXMLClasses { CTRow row = CTRow.Factory.newInstance(); CTSheetData sheetData = CTSheetData.Factory.newInstance(); // need to get the inner class that implements the row list class loaded - Assert.assertTrue(sheetData.getRowList().add(row)); - Assert.assertTrue(sheetData.getRowList().iterator().hasNext()); + assertTrue(sheetData.getRowList().add(row)); + assertTrue(sheetData.getRowList().iterator().hasNext()); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java index bc0269ebe3..23e1e65b4e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java @@ -18,26 +18,26 @@ package org.apache.poi.xssf; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestSheetProtection { private XSSFWorkbook workbook; private XSSFSheet sheet; - - @Before + + @BeforeEach public void setUp() { workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); sheet = workbook.getSheetAt(0); } - @After + @AfterEach public void tearDown() throws IOException { workbook.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java index cc0eb9eab7..8d81d71d90 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java @@ -18,10 +18,10 @@ package org.apache.poi.xssf; import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.io.File; import java.io.FileInputStream; @@ -42,14 +42,14 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestWorkbookProtection { @Test public void workbookAndRevisionPassword() throws Exception { String password = "test"; - + // validate password with an actual office file (Excel 2010) try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection-workbook_password_user_range-2010.xlsx")) { assertTrue(workbook.validateWorkbookPassword(password)); @@ -94,7 +94,7 @@ public class TestWorkbookProtection { assertTrue(workbook.validateRevisionsPassword(password)); } } - + @Test public void shouldReadWorkbookProtection() throws Exception { try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { @@ -181,7 +181,7 @@ public class TestWorkbookProtection { } } } - + @SuppressWarnings("resource") @Test public void testIntegration() throws Exception { @@ -199,7 +199,7 @@ public class TestWorkbookProtection { } } } - + @Test public void testEncryptDecrypt() throws Exception { final String password = "abc123"; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java index de9b1ba26b..fb0404705e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java @@ -17,24 +17,21 @@ package org.apache.poi.xssf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +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.fail; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.ss.usermodel.BaseTestCloneSheet; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.TempFile; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; public class TestXSSFCloneSheet extends BaseTestCloneSheet { public TestXSSFCloneSheet() { @@ -45,10 +42,10 @@ public class TestXSSFCloneSheet extends BaseTestCloneSheet { private static final String VALID_SHEET_NAME = "Sheet01"; private XSSFWorkbook wb; - @Before + @BeforeEach public void setUp() { wb = new XSSFWorkbook(); - wb.createSheet(VALID_SHEET_NAME); + wb.createSheet(VALID_SHEET_NAME); } @Test @@ -57,15 +54,10 @@ public class TestXSSFCloneSheet extends BaseTestCloneSheet { assertEquals(OTHER_SHEET_NAME, cloned.getSheetName()); assertEquals(2, wb.getNumberOfSheets()); } - + @Test public void testCloneSheetIntStringInvalidName() { - try { - wb.cloneSheet(0, VALID_SHEET_NAME); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> wb.cloneSheet(0, VALID_SHEET_NAME)); assertEquals(1, wb.getNumberOfSheets()); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java index 5751e534a8..1ae0a89657 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java @@ -23,9 +23,9 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestXSSFOffset { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFMemoryLeakTests.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFMemoryLeakTests.java index c987e4a91b..385a4593e7 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFMemoryLeakTests.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/XSSFMemoryLeakTests.java @@ -17,17 +17,8 @@ package org.apache.poi.xssf; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.MemoryLeakVerifier; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayOutputStream; import java.io.File; @@ -36,8 +27,17 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import org.apache.poi.ooxml.POIXMLException; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.util.MemoryLeakVerifier; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; /** * A test which uses {@link MemoryLeakVerifier} to ensure that certain @@ -52,9 +52,9 @@ public class XSSFMemoryLeakTests { // verify that they do not keep certain objects in memory, // e.g. nested CT... objects which should be released @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - private List references = new ArrayList<>(); + private final List references = new ArrayList<>(); - @After + @AfterEach public void tearDown() { verifier.assertGarbageCollected(); } @@ -76,10 +76,8 @@ public class XSSFMemoryLeakTests { } CTCell ctCell = cell.getCTCell(); - assertSame("The CTCell should not be replaced", - cell.getCTCell(), ctCell); - assertSame("The CTCell in the row should not be replaced", - row.getCTRow().getCArray(0), ctCell); + assertSame(cell.getCTCell(), ctCell, "The CTCell should not be replaced"); + assertSame(row.getCTRow().getCArray(0), ctCell, "The CTCell in the row should not be replaced"); wb.close(); } @@ -147,23 +145,19 @@ public class XSSFMemoryLeakTests { wb1.close(); } - @Test(expected = POIXMLException.class) - public void testFileLeak() throws IOException, InvalidFormatException { + @Test + public void testFileLeak() { File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); verifier.addObject(file); - try (XSSFWorkbook ignored = new XSSFWorkbook(file)) { - fail("Should catch exception as the file is corrupted"); - } + assertThrows(POIXMLException.class, () -> new XSSFWorkbook(file), "Should catch exception as the file is corrupted"); } - @Test(expected = POIXMLException.class) + @Test public void testFileLeak2() throws IOException, InvalidFormatException { File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); verifier.addObject(file); try (OPCPackage pkg = OPCPackage.open(file)) { - try (XSSFWorkbook ignored = new XSSFWorkbook(pkg)) { - fail("Should catch exception as the file is corrupted"); - } + assertThrows(POIXMLException.class, () -> new XSSFWorkbook(pkg), "Should catch exception as the file is corrupted"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java index 35802f3077..86ee2289fa 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.binary; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.regex.Pattern; @@ -25,7 +25,7 @@ import java.util.regex.Pattern; import org.apache.poi.POIDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFBSharedStringsTable { private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java index 00f9e5984b..d11b8a8cb0 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java @@ -17,8 +17,8 @@ package org.apache.poi.xssf.binary; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.List; @@ -27,7 +27,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.xssf.eventusermodel.XSSFBReader; import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFBSheetHyperlinkManager { private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java index a0be2dbf4a..2a329d83b0 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java @@ -19,7 +19,7 @@ package org.apache.poi.xssf.eventusermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.List; @@ -31,8 +31,7 @@ import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; /** diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java index f51b47a548..2b8676666d 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java @@ -18,8 +18,8 @@ package org.apache.poi.xssf.eventusermodel; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.InputStream; import java.util.ArrayList; @@ -32,7 +32,7 @@ import org.apache.poi.xssf.binary.XSSFBSharedStringsTable; import org.apache.poi.xssf.binary.XSSFBSheetHandler; import org.apache.poi.xssf.binary.XSSFBStylesTable; import org.apache.poi.xssf.usermodel.XSSFComment; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFBReader { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java index b7fef07e9b..f2734134b4 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java @@ -19,12 +19,13 @@ package org.apache.poi.xssf.eventusermodel; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.InputStream; import java.util.HashSet; @@ -43,15 +44,15 @@ import org.apache.poi.xssf.model.CommentsTable; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSimpleShape; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests for {@link XSSFReader} */ public final class TestXSSFReader { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); + private static final POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); @Test public void testGetBits() throws Exception { @@ -231,24 +232,19 @@ public final class TestXSSFReader { @Test public void testBug57914() throws Exception { try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("57914.xlsx")) { - final XSSFReader r; - // for now expect this to fail, when we fix 57699, this one should fail so we know we should adjust // this test as well - try { - r = new XSSFReader(pkg); - fail("This will fail until bug 57699 is fixed"); - } catch (POIXMLException e) { - assertContains(e.getMessage(), "57699"); - return; - } + POIXMLException e = assertThrows(POIXMLException.class, () -> { + final XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - String text = getShapesString(it); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); + String text = getShapesString(it); + assertContains(text, "Line 1"); + assertContains(text, "Line 2"); + assertContains(text, "Line 3"); + }); + assertContains(e.getMessage(), "57699"); } } @@ -322,7 +318,7 @@ public final class TestXSSFReader { } @Test - @Ignore("until we fix issue https://bz.apache.org/bugzilla/show_bug.cgi?id=61701") + @Disabled("until we fix issue https://bz.apache.org/bugzilla/show_bug.cgi?id=61701") public void test61701() throws Exception { try(Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("simple-table-named-range.xlsx")) { Name name = workbook.getName("total"); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java index 025cf49dc8..165b13770e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java @@ -20,11 +20,11 @@ package org.apache.poi.xssf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; import static org.apache.poi.POITestCase.assertEndsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.nio.charset.StandardCharsets; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java index 02505e0bb2..4f1ef18f12 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java @@ -20,10 +20,10 @@ package org.apache.poi.xssf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; import static org.apache.poi.POITestCase.assertEndsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,7 +33,7 @@ import org.apache.poi.ooxml.extractor.POIXMLTextExtractor; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.extractor.ExcelExtractor; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link XSSFEventBasedExcelExtractor} @@ -52,26 +52,26 @@ public class TestXSSFEventBasedExcelExtractor { // a very simple file XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsx"); extractor.getText(); - + String text = extractor.getText(); assertTrue(text.length() > 0); - + // Check sheet names assertStartsWith(text, "Sheet1"); assertEndsWith(text, "Sheet3\n"); - + // Now without, will have text extractor.setIncludeSheetNames(false); text = extractor.getText(); String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + + "Lorem\t111\n" + + "ipsum\t222\n" + + "dolor\t333\n" + + "sit\t444\n" + + "amet\t555\n" + + "consectetuer\t666\n" + + "adipiscing\t777\n" + + "elit\t888\n" + "Nunc\t999\n"; String CHUNK2 = "The quick brown fox jumps over the lazy dog\n" + @@ -80,52 +80,52 @@ public class TestXSSFEventBasedExcelExtractor { "hello, xssf hello, xssf\n" + "hello, xssf hello, xssf\n"; assertEquals( - CHUNK1 + - "at\t4995\n" + + CHUNK1 + + "at\t4995\n" + CHUNK2 , text); - + // Now get formulas not their values extractor.setFormulasNotResults(true); text = extractor.getText(); assertEquals( CHUNK1 + - "at\tSUM(B1:B9)\n" + + "at\tSUM(B1:B9)\n" + CHUNK2, text); - + // With sheet names too extractor.setIncludeSheetNames(true); text = extractor.getText(); assertEquals( "Sheet1\n" + CHUNK1 + - "at\tSUM(B1:B9)\n" + + "at\tSUM(B1:B9)\n" + "rich test\n" + CHUNK2 + "Sheet3\n" , text); - + extractor.close(); } - + @Test public void testGetComplexText() throws Exception { // A fairly complex file XSSFEventBasedExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); extractor.getText(); - + String text = extractor.getText(); assertTrue(text.length() > 0); - + // Might not have all formatting it should do! - assertStartsWith(text, + assertStartsWith(text, "Avgtxfull\n" + - "(iii) AVERAGE TAX RATES ON ANNUAL" + "(iii) AVERAGE TAX RATES ON ANNUAL" ); - + extractor.close(); } - + @Test public void testInlineStrings() throws Exception { XSSFEventBasedExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); @@ -135,7 +135,7 @@ public class TestXSSFEventBasedExcelExtractor { // Numbers assertContains(text, "43"); assertContains(text, "22"); - + // Strings assertContains(text, "ABCDE"); assertContains(text, "Long Text"); @@ -150,7 +150,7 @@ public class TestXSSFEventBasedExcelExtractor { extractor.close(); } - + /** * Test that we return pretty much the same as * ExcelExtractor does, when we're both passed @@ -163,7 +163,7 @@ public class TestXSSFEventBasedExcelExtractor { ExcelExtractor ole2Extractor = new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - + POITextExtractor[] extractors = new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; for (POITextExtractor extractor : extractors) { @@ -171,17 +171,14 @@ public class TestXSSFEventBasedExcelExtractor { assertStartsWith(text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); Matcher m = pattern.matcher(text); - assertTrue(m.matches()); + assertTrue(m.matches()); } - + ole2Extractor.close(); ooxmlExtractor.close(); } - - /** - * Test text extraction from text box using getShapes() - * @throws Exception - */ + + /** Test text extraction from text box using getShapes() */ @Test public void testShapes() throws Exception{ @@ -304,7 +301,7 @@ public class TestXSSFEventBasedExcelExtractor { assertEquals(eventBasedExtractorOutputWithComments, fixture.getText()); } } - + @Test public void testFile56278_normal() throws Exception { // first with normal Text Extractor @@ -313,7 +310,7 @@ public class TestXSSFEventBasedExcelExtractor { assertNotNull(extractor.getText()); } } - + @Test public void testFile56278_event() throws Exception { // then with event based one @@ -349,7 +346,8 @@ public class TestXSSFEventBasedExcelExtractor { XSSFTestDataSamples.openSamplePackage("51519.xlsx")); ex.setConcatenatePhoneticRuns(false); text = ex.getText(); - assertFalse("should not be able to find appended phonetic run", text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3")); + assertFalse(text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"), + "should not be able to find appended phonetic run"); ex.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java index 73ff3992b9..051ee684dd 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java @@ -18,7 +18,7 @@ package org.apache.poi.xssf.extractor; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; public class TestXSSFEventBasedExcelExtractorUsingFactory extends TestXSSFEventBasedExcelExtractor { @@ -28,7 +28,7 @@ public class TestXSSFEventBasedExcelExtractorUsingFactory extends TestXSSFEventB return (XSSFEventBasedExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); } - @After + @AfterEach public void tearDown() { // reset setting to not affect other tests ExtractorFactory.setAllThreadsPreferEventExtractors(null); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java index a68d34f9ac..e0eb4d2f89 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java @@ -21,8 +21,8 @@ import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertEndsWith; import static org.apache.poi.POITestCase.assertNotContained; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.HashMap; @@ -35,7 +35,7 @@ import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.extractor.ExcelExtractor; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link XSSFExcelExtractor} @@ -149,7 +149,7 @@ public class TestXSSFExcelExtractor { assertStartsWith(filename, text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); Matcher m = pattern.matcher(text); - assertTrue(filename, m.matches()); + assertTrue(m.matches(), filename); } ole2Extractor.close(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java index cd1684e5a5..0cd119ae15 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java @@ -19,7 +19,7 @@ package org.apache.poi.xssf.extractor; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; /** * Tests for {@link XSSFExcelExtractor} @@ -36,7 +36,7 @@ public final class TestXSSFExcelExtractorUsingFactory extends TestXSSFExcelExtra } } - @After + @AfterEach public void tearDown() { // reset setting to not affect other tests ExtractorFactory.setAllThreadsPreferEventExtractors(null); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java index e0386b860a..4c79f5f65b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java @@ -17,10 +17,11 @@ package org.apache.poi.xssf.extractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -44,8 +45,8 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.MapInfo; import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; @@ -218,7 +219,7 @@ public final class TestXSSFExportToXML { } @Test - @Ignore(value="Fails, but I don't know if it is ok or not...") + @Disabled(value="Fails, but I don't know if it is ok or not...") public void testExportToXMLSingleAttributeNamespace() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) { @@ -245,7 +246,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(2); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -289,7 +290,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -324,7 +325,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -363,7 +364,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -421,6 +422,7 @@ public final class TestXSSFExportToXML { } } + @SuppressWarnings("EqualsWithItself") @Test public void testXmlExportCompare_Bug_55923() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx")) { @@ -435,7 +437,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(4); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); assertEquals(0, exporter.compare("", "")); @@ -466,7 +468,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(4); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -544,7 +546,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(4); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -575,7 +577,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(4); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -607,7 +609,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); - assertNotNull("XSSFMap is null", map); + assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -657,13 +659,13 @@ public final class TestXSSFExportToXML { } } - @Test(expected = SAXParseException.class) + @Test public void testXXEInSchema() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("xxe_in_schema.xlsx")) { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - exporter.exportToXML(bos, true); + assertThrows(SAXParseException.class, () -> exporter.exportToXML(bos, true)); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java index 13e79a6ffc..84f7e41863 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java @@ -17,10 +17,11 @@ package org.apache.poi.xssf.extractor; +import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.text.DateFormatSymbols; @@ -37,7 +38,8 @@ import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.xml.sax.SAXException; public class TestXSSFImportFromXML { @@ -85,7 +87,8 @@ public class TestXSSFImportFromXML { } } - @Test(timeout=60000) + @Timeout(value = 60, unit = SECONDS) + @Test public void testMultiTable() throws IOException, XPathExpressionException, SAXException{ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { String cellC6 = "c6"; @@ -196,7 +199,7 @@ public class TestXSSFImportFromXML { // Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue()); - assertNull("", rowData.getCell(3)); + assertNull(rowData.getCell(3), ""); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java index 5e9c2452e1..dd01b9a6e6 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java @@ -17,8 +17,8 @@ package org.apache.poi.xssf.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.List; @@ -29,7 +29,7 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFPictureData; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestLoadSaveXSSF { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java index ab74879f07..487a7e6a2e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -26,7 +26,7 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; public final class TestCalculationChain { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java index b6df578c36..f4c630acb1 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java @@ -17,12 +17,12 @@ package org.apache.poi.xssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -40,7 +40,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCommentList; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; @@ -217,7 +217,7 @@ public class TestCommentsTable { final CellAddress addrA1 = new CellAddress("A1"); final CellAddress addrA2 = new CellAddress("A2"); final CellAddress addrA3 = new CellAddress("A3"); - + CommentsTable sheetComments = new CommentsTable(); CTComment a1 = sheetComments.newComment(addrA1); CTComment a2 = sheetComments.newComment(addrA2); @@ -261,28 +261,28 @@ public class TestCommentsTable { //Cell A1 = getCell(sheet, 2, 2); Drawing drawing = sheet.createDrawingPatriarch(); setComment(A1, drawing, "for A1", helper, anchor); - + // find comment in A1 before we set the comment in B2 Comment commentA1 = A1.getCellComment(); - assertNotNull("Should still find the previous comment in A1, but had null", commentA1); - assertEquals("should find correct comment in A1, but had null: " + commentA1, "for A1", commentA1.getString().getString()); - + assertNotNull(commentA1, "Should still find the previous comment in A1, but had null"); + assertEquals("for A1", commentA1.getString().getString(), "should find correct comment in A1, but had null: " + commentA1); + // place comment in B2, according to Bug 54920 this removes the comment in A1! Cell B2 = getCell(sheet, 1, 1); setComment(B2, drawing, "for B2", helper, anchor); // find comment in A1 Comment commentB2 = B2.getCellComment(); - assertEquals("should find correct comment in B2, but had null: " + commentB2, "for B2", commentB2.getString().getString()); - + assertEquals("for B2", commentB2.getString().getString(), "should find correct comment in B2, but had null: " + commentB2); + // find comment in A1 commentA1 = A1.getCellComment(); - assertNotNull("Should still find the previous comment in A1, but had null", commentA1); - assertEquals("should find correct comment in A1, but had null: " + commentA1, "for A1", commentA1.getString().getString()); - + assertNotNull(commentA1, "Should still find the previous comment in A1, but had null"); + assertEquals("for A1", commentA1.getString().getString(), "should find correct comment in A1, but had null: " + commentA1); + workbook.close(); } - + // Set the comment on a sheet // private static void setComment(Cell cell, Drawing drawing, String commentText, CreationHelper helper, ClientAnchor anchor) { @@ -290,7 +290,7 @@ public class TestCommentsTable { anchor.setCol2(cell.getColumnIndex()); anchor.setRow1(cell.getRowIndex()); anchor.setRow2(cell.getRowIndex()); - + // get comment, or create if it does not exist // NOTE - only occurs if getCellComment is called first Comment comment = cell.getCellComment(); @@ -299,12 +299,12 @@ public class TestCommentsTable { comment = drawing.createCellComment(anchor); } comment.setAuthor("Test"); - + // attach the comment to the cell comment.setString(helper.createRichTextString(commentText)); cell.setCellComment(comment); } - + // Get a cell, create as needed // private static Cell getCell(Sheet sheet, int rowIndex, int colIndex) { @@ -312,12 +312,12 @@ public class TestCommentsTable { if (row == null) { row = sheet.createRow(rowIndex); } - + Cell cell = row.getCell(colIndex); if (cell == null) { cell = row.createCell(colIndex); } - + return cell; } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java index 4c76fdf481..3076da6156 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java @@ -17,16 +17,16 @@ package org.apache.poi.xssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.ss.usermodel.Name; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -import java.io.IOException; +import org.junit.jupiter.api.Test; public final class TestExternalLinksTable { @Test @@ -36,7 +36,7 @@ public final class TestExternalLinksTable { assertEquals(0, wb.getExternalLinksTable().size()); } } - + @Test public void basicRead() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx")) { @@ -66,7 +66,7 @@ public final class TestExternalLinksTable { assertEquals("56737.xlsx", links.getLinkedFileName()); } } - + @Test public void basicReadWriteRead() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx")) { @@ -91,7 +91,7 @@ public final class TestExternalLinksTable { assertEquals("$A$1", name.getRefersToFormula()); } } - + @Test public void readWithReferencesToTwoExternalBooks() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref2-56737.xlsx")) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java index 30f0d0a02e..624fe77cca 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java @@ -16,20 +16,20 @@ ==================================================================== */ package org.apache.poi.xssf.model; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; + import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMapInfo; import org.w3c.dom.Node; -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - /** * @author Roberto Manicardi */ diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java index 352b94ba2c..00720aa6ec 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java @@ -17,8 +17,8 @@ package org.apache.poi.xssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -35,7 +35,7 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java index 94435c6019..ff5dd42d69 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java @@ -17,14 +17,15 @@ package org.apache.poi.xssf.model; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Map; @@ -39,8 +40,8 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; public final class TestStylesTable { private static final String testFile = "Formatting.xlsx"; private static final String customDataFormat = "YYYY-mm-dd"; - - @BeforeClass + + @BeforeAll public static void assumeCustomDataFormatIsNotBuiltIn() { assertEquals(-1, BuiltinFormats.getBuiltinFormat(customDataFormat)); } @@ -120,7 +121,7 @@ public final class TestStylesTable { assertNotNull(st.getStyleAt(0)); assertNotNull(st.getStyleAt(1)); assertNotNull(st.getStyleAt(2)); - + assertEquals(0, st.getStyleAt(0).getDataFormat()); assertEquals(14, st.getStyleAt(1).getDataFormat()); assertEquals(0, st.getStyleAt(2).getDataFormat()); @@ -189,7 +190,7 @@ public final class TestStylesTable { assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); } } - + @Test public void exceedNumberFormatLimit() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { @@ -206,14 +207,14 @@ public final class TestStylesTable { } } } - + private static void assertNotContainsKey(Map map, K key) { assertFalse(map.containsKey(key)); } private static void assertNotContainsValue(Map map, V value) { assertFalse(map.containsValue(value)); } - + @Test public void removeNumberFormat() throws IOException { try (XSSFWorkbook wb1 = new XSSFWorkbook()) { @@ -230,14 +231,8 @@ public final class TestStylesTable { assertEquals(fmt, wb1.getStylesSource().getNumberFormatAt(fmtIdx)); // remove the number format from the workbook - assertTrue("The format is removed on first call", - wb1.getStylesSource().removeNumberFormat(fmt)); - try { - wb1.getStylesSource().removeNumberFormat(fmt); - fail("Should fail here"); - } catch (IllegalStateException e) { - // expected here - } + assertTrue(wb1.getStylesSource().removeNumberFormat(fmt), "The format is removed on first call"); + assertThrows(IllegalStateException.class, () -> wb1.getStylesSource().removeNumberFormat(fmt)); // number format in CellStyles should be restored to default number format final short defaultFmtIdx = 0; @@ -272,7 +267,7 @@ public final class TestStylesTable { } } } - + @Test public void maxNumberOfDataFormats() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { @@ -290,17 +285,12 @@ public final class TestStylesTable { assertEquals(n, styles.getMaxNumberOfDataFormats()); // Check negative (illegal) limits - try { - styles.setMaxNumberOfDataFormats(-1); - fail("Expected to get an IllegalArgumentException(\"Maximum Number of Data Formats must be greater than or equal to 0\")"); - } catch (final IllegalArgumentException e) { - if (!e.getMessage().startsWith("Maximum Number of Data Formats must be greater than or equal to 0")) { - throw e; - } - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> styles.setMaxNumberOfDataFormats(-1), + "Expected to get an IllegalArgumentException(\"Maximum Number of Data Formats must be greater than or equal to 0\")"); + assertTrue(e.getMessage().startsWith("Maximum Number of Data Formats must be greater than or equal to 0")); } } - + @Test public void addDataFormatsBeyondUpperLimit() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { @@ -308,17 +298,11 @@ public final class TestStylesTable { styles.setMaxNumberOfDataFormats(0); // Try adding a format beyond the upper limit - try { - styles.putNumberFormat("\"test \"0"); - fail("Expected to raise IllegalStateException"); - } catch (final IllegalStateException e) { - if (!e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")) { - throw e; - } - } + IllegalStateException e = assertThrows(IllegalStateException.class, () -> styles.putNumberFormat("\"test \"0")); + assertTrue(e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")); } } - + @Test public void decreaseUpperLimitBelowCurrentNumDataFormats() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { @@ -326,14 +310,8 @@ public final class TestStylesTable { styles.putNumberFormat(customDataFormat); // Try decreasing the upper limit below the current number of formats - try { - styles.setMaxNumberOfDataFormats(0); - fail("Expected to raise IllegalStateException"); - } catch (final IllegalStateException e) { - if (!e.getMessage().startsWith("Cannot set the maximum number of data formats less than the current quantity.")) { - throw e; - } - } + IllegalStateException e = assertThrows(IllegalStateException.class, () -> styles.setMaxNumberOfDataFormats(0)); + assertTrue(e.getMessage().startsWith("Cannot set the maximum number of data formats less than the current quantity.")); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java index 81bb44b90e..c01bee1cd9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.FileOutputStream; import java.io.IOException; @@ -41,7 +41,7 @@ import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; public class TestThemesTable { @@ -101,17 +101,15 @@ public class TestThemesTable { for (int rn=startRN; rn 0.25) { - fail("check column width: " + - rel_error + ", " + abs_error + ", " + - expectedWidth + ", " + bestFitWidth); - } - + assertTrue(rel_error <= 0.25, "check column width: " + rel_error + ", " + abs_error + ", " + expectedWidth + ", " + bestFitWidth); } - + private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { // autoSize will fail if required fonts are not installed, skip this test then Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); + assumeTrue(SheetUtil.canComputeColumnWidth(font), + "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); } private void createColumnsAndTrackThemAll() { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java index 879a2d4ed6..a171d62bf3 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java @@ -19,12 +19,12 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -38,9 +38,9 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { @@ -48,7 +48,7 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { super(DeferredSXSSFITestDataProvider.instance); } - @After + @AfterEach public void tearDown() { ((DeferredSXSSFITestDataProvider) _testDataProvider).cleanup(); } @@ -59,12 +59,8 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test public void cloneSheet() throws IOException { - try { - super.cloneSheet(); - fail("expected exception"); - } catch (RuntimeException e) { - assertEquals("Not Implemented", e.getMessage()); - } + RuntimeException e = assertThrows(RuntimeException.class, super::cloneSheet); + assertEquals("Not Implemented", e.getMessage()); } /** @@ -73,29 +69,25 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test public void sheetClone() throws IOException { - try { - super.sheetClone(); - fail("expected exception"); - } catch (RuntimeException e) { - assertEquals("Not Implemented", e.getMessage()); - } + RuntimeException e = assertThrows(RuntimeException.class, super::sheetClone); + assertEquals("Not Implemented", e.getMessage()); } /** * Skip this test, as SXSSF doesn't update formulas on sheet name changes. */ @Override - @Ignore("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") + @Disabled("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") @Test public void setSheetName() {} @Override - @Ignore("DeferredSXSSF code disposes rows in a way that breaks this test") + @Disabled("DeferredSXSSF code disposes rows in a way that breaks this test") @Test public void parentReferences() {} @Override - @Ignore("DeferredSXSSF code disposes rows in a way that breaks this test") + @Disabled("DeferredSXSSF code disposes rows in a way that breaks this test") @Test public void unicodeInAll() {} @@ -248,7 +240,7 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { assertEquals("sheet" + i, sh.getSheetName()); for (int j = 0; j < rowNum; j++) { Row row = sh.getRow(j); - assertNotNull("row[" + j + "]", row); + assertNotNull(row, "row[" + j + "]"); Cell cell1 = row.getCell(0); assertEquals(new CellReference(cell1).formatAsString(), cell1.getStringCellValue()); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java index 7ce130d54e..4cca84c00f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java @@ -19,20 +19,19 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestOutlining { @Test @@ -58,7 +57,7 @@ public final class TestOutlining { r = sheet2.getRow(12); assertNull(r.getHidden()); wb2.dispose(); - + wb2.close(); } @@ -76,34 +75,18 @@ public final class TestOutlining { sheet2.groupRow(4, 9); sheet2.groupRow(11, 19); - try { - sheet2.setRowGroupCollapsed(3, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (3)")); - } + IllegalArgumentException e; + e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(3, true)); + assertTrue(e.getMessage().contains("row (3)")); - try { - sheet2.setRowGroupCollapsed(10, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (10)")); - } + e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(10, true)); + assertTrue(e.getMessage().contains("row (10)")); - try { - sheet2.setRowGroupCollapsed(0, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (0)")); - } + e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(0, true)); + assertTrue(e.getMessage().contains("row (0)")); - try { - sheet2.setRowGroupCollapsed(20, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue("Had: " + e.getMessage(), - e.getMessage().contains("Row does not exist")); - } + e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(20, true)); + assertTrue(e.getMessage().contains("Row does not exist"), "Had: " + e.getMessage()); SXSSFRow r = sheet2.getRow(8); assertNotNull(r); @@ -113,10 +96,10 @@ public final class TestOutlining { r = sheet2.getRow(12); assertNull(r.getHidden()); wb2.dispose(); - + wb2.close(); } - + @Test public void testOutlineGettersHSSF() throws IOException { HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); @@ -136,7 +119,7 @@ public final class TestOutlining { assertEquals(0, hssfSheet.getRow(4).getOutlineLevel()); hssfWorkbook.close(); } - + @Test public void testOutlineGettersXSSF() throws IOException { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); @@ -156,18 +139,18 @@ public final class TestOutlining { assertEquals(0, xssfSheet.getRow(4).getOutlineLevel()); xssfWorkbook.close(); } - + @Test public void testOutlineGettersSXSSF() throws IOException { SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - Sheet sxssfSheet = sxssfWorkbook.createSheet(); + SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet(); sxssfSheet.createRow(0); sxssfSheet.createRow(1); sxssfSheet.createRow(2); sxssfSheet.createRow(3); sxssfSheet.createRow(4); sxssfSheet.createRow(5); - + // nothing happens with empty row-area sxssfSheet.groupRow(1, 0); assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); @@ -176,7 +159,7 @@ public final class TestOutlining { assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - + sxssfSheet.groupRow(1, 3); sxssfSheet.groupRow(2, 3); @@ -186,33 +169,33 @@ public final class TestOutlining { assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - + // add tests for direct setting - add row 4 to deepest group - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(4, 2); + sxssfSheet.setRowOutlineLevel(4, 2); assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); assertEquals(1, sxssfSheet.getRow(1).getOutlineLevel()); assertEquals(2, sxssfSheet.getRow(2).getOutlineLevel()); assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - + sxssfWorkbook.dispose(); sxssfWorkbook.close(); } - + @Test public void testOutlineGettersSXSSFSetOutlineLevel() throws IOException { SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - Sheet sxssfSheet = sxssfWorkbook.createSheet(); + SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet(); sxssfSheet.createRow(0); sxssfSheet.createRow(1); sxssfSheet.createRow(2); sxssfSheet.createRow(3); sxssfSheet.createRow(4); sxssfSheet.createRow(5); - + // what happens with level below 1 - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(0, -2); + sxssfSheet.setRowOutlineLevel(0, -2); assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); @@ -221,14 +204,14 @@ public final class TestOutlining { assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); // add tests for direct setting - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(4, 2); + sxssfSheet.setRowOutlineLevel(4, 2); assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - + sxssfWorkbook.dispose(); sxssfWorkbook.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java index 182eb17775..3ab01d05d3 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java @@ -19,10 +19,11 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.mockito.Mockito.spy; import java.io.IOException; @@ -42,9 +43,9 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.xmlbeans.XmlCursor; -import org.junit.AfterClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; /** @@ -57,7 +58,7 @@ public class TestSXSSFCell extends BaseTestXCell { super(SXSSFITestDataProvider.instance); } - @AfterClass + @AfterAll public static void tearDownClass() { SXSSFITestDataProvider.instance.cleanup(); } @@ -87,26 +88,26 @@ public class TestSXSSFCell extends BaseTestXCell { c.toNextToken(); String t = c.getAttributeText(new QName("http://www.w3.org/XML/1998/namespace", "space")); c.dispose(); - assertEquals("expected xml:spaces=\"preserve\" \"" + str + "\"", "preserve", t); + assertEquals( "preserve", t, "expected xml:spaces=\"preserve\" \"" + str + "\"" ); xwb.close(); swb.close(); } } - @Test(expected = IllegalStateException.class) + @Test public void getCachedFormulaResultType_throwsISE_whenNotAFormulaCell() { SXSSFCell instance = new SXSSFCell(null, CellType.BLANK); - instance.getCachedFormulaResultType(); + assertThrows(IllegalStateException.class, instance::getCachedFormulaResultType); } - @Test(expected = IllegalArgumentException.class) + @Test public void setCellValue_withTooLongRichTextString_throwsIAE() { Cell cell = spy(new SXSSFCell(null, CellType.BLANK)); int length = SpreadsheetVersion.EXCEL2007.getMaxTextLength() + 1; String string = new String(new byte[length], StandardCharsets.UTF_8).replace("\0", "x"); RichTextString richTextString = new XSSFRichTextString(string); - cell.setCellValue(richTextString); + assertThrows(IllegalArgumentException.class, () -> cell.setCellValue(richTextString)); } @Test @@ -136,7 +137,7 @@ public class TestSXSSFCell extends BaseTestXCell { * However, this test should be enabled if array formulas are implemented for SXSSF. */ @Override - @Ignore + @Disabled public void setBlank_removesArrayFormula_ifCellIsPartOfAnArrayFormulaGroupContainingOnlyThisCell() { } @@ -145,34 +146,34 @@ public class TestSXSSFCell extends BaseTestXCell { * However, this test should be enabled if array formulas are implemented for SXSSF. */ @Override - @Ignore + @Disabled @Test // <- annotation is necessary to override expected exception public void setBlank_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() { } @Override - @Ignore + @Disabled @Test public void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() { } @Override - @Ignore + @Disabled public void removeFormula_turnsCellToBlank_whenFormulaWasASingleCellArrayFormula() { } @Override - @Ignore + @Disabled public void setCellFormula_onASingleCellArrayFormulaCell_preservesTheValue() { } @Test - @Ignore + @Disabled public void setCellFormula_isExceptionSafe_onBlankCell() { } @Test - @Ignore + @Disabled public void setCellType_FORMULA_onAnArrayFormulaCell_doesNothing() { } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java index 947ff655fd..be8f895ae9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; @@ -27,7 +27,7 @@ import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSXSSFDataValidation extends BaseTestDataValidation { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java index 4ffa081908..2e6ecadcd0 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java @@ -20,7 +20,7 @@ import org.apache.poi.ss.formula.EvaluationSheet; import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import java.io.IOException; import java.util.AbstractMap; @@ -31,7 +31,7 @@ import java.util.Map; public class TestSXSSFEvaluationSheet extends BaseTestXEvaluationSheet { private List workbooksToClose = new ArrayList<>(); - @After + @AfterEach public void closeWorkbooks() throws IOException { for (Workbook workbook : workbooksToClose) { workbook.close(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java index e8f05ccd49..39cd66ae0e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java @@ -19,9 +19,10 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +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.fail; import java.io.IOException; @@ -29,13 +30,15 @@ import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.xssf.SXSSFITestDataProvider; +import org.apache.poi.xssf.streaming.SXSSFFormulaEvaluator.RowFlushedException; +import org.apache.poi.xssf.streaming.SXSSFFormulaEvaluator.SheetsFlushedException; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Formula Evaluation with SXSSF. - * + * * Note that SXSSF can only evaluate formulas where the * cell is in the current window, and all references * from the cell are in the current window @@ -53,76 +56,65 @@ public final class TestSXSSFFormulaEvaluation extends BaseTestFormulaEvaluator */ @Test public void testEvaluateAllFails() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - s.createRow(1).createCell(0).setCellFormula("A21"); - for (int i=2; i<19; i++) { s.createRow(i); } - - // Cells outside window will fail, whether referenced or not - s.createRow(19).createCell(0).setCellFormula("A1+A2"); - s.createRow(20).createCell(0).setCellFormula("A1+A11+100"); - try { - eval.evaluateAll(); - fail("Evaluate All shouldn't work, as some cells outside the window"); - } catch(SXSSFFormulaEvaluator.RowFlushedException e) { - // Expected - } - - - // Inactive sheets will fail - XSSFWorkbook xwb = new XSSFWorkbook(); - xwb.createSheet("Open"); - xwb.createSheet("Closed"); + try (SXSSFWorkbook wb = new SXSSFWorkbook(5)) { + SXSSFSheet s = wb.createSheet(); - wb.close(); - wb = new SXSSFWorkbook(xwb, 5); - s = wb.getSheet("Closed"); - s.flushRows(); - s = wb.getSheet("Open"); - s.createRow(0).createCell(0).setCellFormula("1+2"); - - eval = wb.getCreationHelper().createFormulaEvaluator(); - try { - eval.evaluateAll(); - fail("Evaluate All shouldn't work, as sheets flushed"); - } catch (SXSSFFormulaEvaluator.SheetsFlushedException e) { - // expected here + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); + + s.createRow(0).createCell(0).setCellFormula("1+2"); + s.createRow(1).createCell(0).setCellFormula("A21"); + for (int i = 2; i < 19; i++) { + s.createRow(i); + } + + // Cells outside window will fail, whether referenced or not + s.createRow(19).createCell(0).setCellFormula("A1+A2"); + s.createRow(20).createCell(0).setCellFormula("A1+A11+100"); + assertThrows(RowFlushedException.class, eval::evaluateAll, + "Evaluate All shouldn't work, as some cells outside the window"); + } + + // Inactive sheets will fail + try (XSSFWorkbook xwb = new XSSFWorkbook()) { + xwb.createSheet("Open"); + xwb.createSheet("Closed"); + + try (SXSSFWorkbook wb = new SXSSFWorkbook(xwb, 5)) { + SXSSFSheet s = wb.getSheet("Closed"); + s.flushRows(); + s = wb.getSheet("Open"); + s.createRow(0).createCell(0).setCellFormula("1+2"); + + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); + assertThrows(SheetsFlushedException.class, eval::evaluateAll, "Evaluate All shouldn't work, as sheets flushed"); + } } - - wb.close(); } - + @Test public void testEvaluateRefOutsideWindowFails() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - assertFalse(s.areAllRowsFlushed()); - assertEquals(-1, s.getLastFlushedRowNum()); - - for (int i=1; i<=19; i++) { s.createRow(i); } - Cell c = s.createRow(20).createCell(0); - c.setCellFormula("A1+100"); + try (SXSSFWorkbook wb = new SXSSFWorkbook(5)) { + SXSSFSheet s = wb.createSheet(); - assertFalse(s.areAllRowsFlushed()); - assertEquals(15, s.getLastFlushedRowNum()); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - try { - eval.evaluateFormulaCell(c); - fail("Evaluate shouldn't work, as reference outside the window"); - } catch(SXSSFFormulaEvaluator.RowFlushedException e) { - // Expected + s.createRow(0).createCell(0).setCellFormula("1+2"); + assertFalse(s.areAllRowsFlushed()); + assertEquals(-1, s.getLastFlushedRowNum()); + + for (int i = 1; i <= 19; i++) { + s.createRow(i); + } + Cell c = s.createRow(20).createCell(0); + c.setCellFormula("A1+100"); + + assertFalse(s.areAllRowsFlushed()); + assertEquals(15, s.getLastFlushedRowNum()); + + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); + assertThrows(RowFlushedException.class, () -> eval.evaluateFormulaCell(c), + "Evaluate shouldn't work, as reference outside the window"); } - - wb.close(); } - + /** * If all formula cells + their references are inside the window, * then evaluation works @@ -134,64 +126,64 @@ public final class TestSXSSFFormulaEvaluation extends BaseTestFormulaEvaluator s.createRow(0).createCell(0).setCellFormula("1+2"); s.createRow(1).createCell(1).setCellFormula("A1+10"); s.createRow(2).createCell(2).setCellFormula("B2+100"); - + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); eval.evaluateAll(); - + assertEquals(3, (int)s.getRow(0).getCell(0).getNumericCellValue()); assertEquals(13, (int)s.getRow(1).getCell(1).getNumericCellValue()); assertEquals(113, (int)s.getRow(2).getCell(2).getNumericCellValue()); - + wb.close(); } - + @Test public void testEvaluateRefInsideWindow() throws IOException { SXSSFWorkbook wb = new SXSSFWorkbook(5); SXSSFSheet s = wb.createSheet(); - + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - + SXSSFCell c = s.createRow(0).createCell(0); c.setCellValue(1.5); - + c = s.createRow(1).createCell(0); c.setCellFormula("A1*2"); - + assertEquals(0, (int)c.getNumericCellValue()); eval.evaluateFormulaCell(c); assertEquals(3, (int)c.getNumericCellValue()); - + wb.close(); } - + @Test public void testEvaluateSimple() throws IOException { SXSSFWorkbook wb = new SXSSFWorkbook(5); SXSSFSheet s = wb.createSheet(); - + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - + SXSSFCell c = s.createRow(0).createCell(0); c.setCellFormula("1+2"); assertEquals(0, (int)c.getNumericCellValue()); eval.evaluateFormulaCell(c); assertEquals(3, (int)c.getNumericCellValue()); - + c = s.createRow(1).createCell(0); c.setCellFormula("CONCATENATE(\"hello\",\" \",\"world\")"); eval.evaluateFormulaCell(c); assertEquals("hello world", c.getStringCellValue()); - + wb.close(); } @Test + @Disabled( + "This test is disabled because it fails for SXSSF because " + + "handling of errors in formulas is slightly different than in XSSF, " + + "but this proved to be non-trivial to solve..." + ) public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() { - //noinspection ConstantConditions - Assume.assumeTrue("This test is disabled because it fails for SXSSF because " + - "handling of errors in formulas is slightly different than in XSSF, " + - "but this proved to be non-trivial to solve...", - false); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java index e1e237b689..8a2cf0e69d 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java @@ -19,7 +19,7 @@ package org.apache.poi.xssf.streaming; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import org.apache.poi.ss.usermodel.BaseTestHyperlink; import org.apache.poi.ss.usermodel.Hyperlink; @@ -38,11 +38,11 @@ public class TestSXSSFHyperlink extends BaseTestHyperlink { } - @After + @AfterEach public void tearDown(){ SXSSFITestDataProvider.instance.cleanup(); } - + @Override public XSSFHyperlink copyHyperlink(Hyperlink link) { // FIXME: replace with SXSSFHyperlink if it ever gets created diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java index 88c12d7e01..c3a4521646 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java @@ -21,9 +21,9 @@ package org.apache.poi.xssf.streaming; import org.apache.poi.ss.tests.usermodel.BaseTestXRow; import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests for XSSFRow @@ -35,18 +35,18 @@ public final class TestSXSSFRow extends BaseTestXRow { } - @After + @AfterEach public void tearDown() { ((SXSSFITestDataProvider) _testDataProvider).cleanup(); } @Override - @Ignore ("see ") @Test + @Disabled("see ") @Test public void testCellShiftingRight(){ // Remove when SXSSFRow.shiftCellsRight() is implemented. } @Override - @Ignore ("see ") @Test + @Disabled("see ") @Test public void testCellShiftingLeft(){ // Remove when SXSSFRow.shiftCellsLeft() is implemented. } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java index 8a3ffe433f..b6c7f54e17 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java @@ -19,9 +19,9 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; +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.IOException; @@ -30,8 +30,8 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public final class TestSXSSFSheet extends BaseTestXSheet { @@ -41,7 +41,7 @@ public final class TestSXSSFSheet extends BaseTestXSheet { } - @After + @AfterEach public void tearDown(){ SXSSFITestDataProvider.instance.cleanup(); } @@ -123,29 +123,19 @@ public final class TestSXSSFSheet extends BaseTestXSheet { @Test public void overrideRowsInTemplate() throws IOException { - XSSFWorkbook template = new XSSFWorkbook(); - template.createSheet().createRow(1); - - Workbook wb = new SXSSFWorkbook(template); - try { - Sheet sheet = wb.getSheetAt(0); - - try { - sheet.createRow(1); - fail("expected exception"); - } catch (Throwable e){ + try (XSSFWorkbook template = new XSSFWorkbook()) { + template.createSheet().createRow(1); + try (Workbook wb = new SXSSFWorkbook(template);) { + Sheet sheet = wb.getSheetAt(0); + Throwable e; + e = assertThrows(Throwable.class, () -> sheet.createRow(1)); assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", e.getMessage()); - } - try { - sheet.createRow(0); - fail("expected exception"); - } catch (Throwable e){ + + e = assertThrows(Throwable.class, () -> sheet.createRow(0)); assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage()); + + sheet.createRow(2); } - sheet.createRow(2); - } finally { - wb.close(); - template.close(); } } @@ -157,11 +147,11 @@ public final class TestSXSSFSheet extends BaseTestXSheet { SXSSFRow row1 = sheet.createRow(1); sheet.changeRowNum(row0, 2); - assertEquals("Row 1 knows its row number", 1, row1.getRowNum()); - assertEquals("Row 2 knows its row number", 2, row0.getRowNum()); - assertEquals("Sheet knows Row 1's row number", 1, sheet.getRowNum(row1)); - assertEquals("Sheet knows Row 2's row number", 2, sheet.getRowNum(row0)); - assertEquals("Sheet row iteratation order should be ascending", row1, sheet.iterator().next()); + assertEquals(1, row1.getRowNum(), "Row 1 knows its row number"); + assertEquals(2, row0.getRowNum(), "Row 2 knows its row number"); + assertEquals(1, sheet.getRowNum(row1), "Sheet knows Row 1's row number"); + assertEquals(2, sheet.getRowNum(row0), "Sheet knows Row 2's row number"); + assertEquals(row1, sheet.iterator().next(), "Sheet row iteratation order should be ascending"); wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java index 97b11553d9..59431a4b71 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java @@ -16,19 +16,18 @@ ==================================================================== */ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; +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.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; +import java.util.stream.Stream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Font; @@ -37,35 +36,32 @@ 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.SheetUtil; -import org.junit.After; -import org.junit.Assume; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +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; /** * Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all * rows fit into the memory window size etc. - * + * * see Bug #57450 which reported the original misbehaviour */ -@RunWith(Parameterized.class) public class TestSXSSFSheetAutoSizeColumn { - + private static final String SHORT_CELL_VALUE = "Ben"; private static final String LONG_CELL_VALUE = "B Be Ben Beni Benif Benify Benif Beni Ben Be B"; - - // Approximative threshold to decide whether test is PASS or FAIL: + + // Approximate threshold to decide whether test is PASS or FAIL: // shortCellValue ends up with approx column width 1_000 (on my machine), // longCellValue ends up with approx. column width 10_000 (on my machine) // so shortCellValue can be expected to be < 5000 for all fonts // and longCellValue can be expected to be > 5000 for all fonts private static final int COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG = 4000; private static final int MAX_COLUMN_WIDTH = 255*256; - + private static final SortedSet columns; static { SortedSet_columns = new TreeSet<>(); @@ -74,23 +70,16 @@ public class TestSXSSFSheetAutoSizeColumn { _columns.add(3); columns = Collections.unmodifiableSortedSet(_columns); } - - + + private SXSSFSheet sheet; private SXSSFWorkbook workbook; - - @Parameter - public boolean useMergedCells; - - @Parameters(name="{index}: useMergedCells={0}") - public static Collection data() { - return Arrays.asList(new Object[][] { - {false}, - {true}, - }); + + public static Stream data() { + return Stream.of(Arguments.of(false), Arguments.of(true)); } - - @After + + @AfterEach public void tearDownSheetAndWorkbook() throws IOException { if (sheet != null) { sheet.dispose(); @@ -99,43 +88,28 @@ public class TestSXSSFSheetAutoSizeColumn { workbook.close(); } } - - @Test - public void test_EmptySheet_NoException() { + + @ParameterizedTest + @MethodSource("data") + public void test_EmptySheet_NoException(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); sheet.trackAllColumnsForAutoSizing(); - + for (int i = 0; i < 10; i++) { sheet.autoSizeColumn(i, useMergedCells); } } - - @Test - public void test_WindowSizeDefault_AllRowsFitIntoWindowSize() { + + @ParameterizedTest + @MethodSource("data") + public void test_WindowSizeDefault_AllRowsFitIntoWindowSize(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); sheet.trackAllColumnsForAutoSizing(); - + final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @Test - public void test_WindowSizeEqualsOne_ConsiderFlushedRows() { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - assumeRequiredFontsAreInstalled(workbook, cellRow0); createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); @@ -145,14 +119,15 @@ public class TestSXSSFSheetAutoSizeColumn { assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); } - @Test - public void test_WindowSizeEqualsOne_lastRowIsNotWidest() { + @ParameterizedTest + @MethodSource("data") + public void test_WindowSizeEqualsOne_ConsiderFlushedRows(boolean useMergedCells) { workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory sheet = workbook.createSheet(); sheet.trackAllColumnsForAutoSizing(); - + final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - + assumeRequiredFontsAreInstalled(workbook, cellRow0); createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); @@ -161,44 +136,64 @@ public class TestSXSSFSheetAutoSizeColumn { assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); } - - @Test - public void test_WindowSizeEqualsOne_lastRowIsWidest() { + + @ParameterizedTest + @MethodSource("data") + public void test_WindowSizeEqualsOne_lastRowIsNotWidest(boolean useMergedCells) { workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory sheet = workbook.createSheet(); sheet.trackAllColumnsForAutoSizing(); - + + final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); + + assumeRequiredFontsAreInstalled(workbook, cellRow0); + + createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); + + sheet.autoSizeColumn(0, useMergedCells); + + assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); + } + + @ParameterizedTest + @MethodSource("data") + public void test_WindowSizeEqualsOne_lastRowIsWidest(boolean useMergedCells) { + workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory + sheet = workbook.createSheet(); + sheet.trackAllColumnsForAutoSizing(); + final Cell cellRow0 = createRowWithCellValues(sheet, 0, SHORT_CELL_VALUE); assumeRequiredFontsAreInstalled(workbook, cellRow0); - + createRowWithCellValues(sheet, 1, LONG_CELL_VALUE); sheet.autoSizeColumn(0, useMergedCells); assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); } - + // fails only for useMergedCell=true - @Test - public void test_WindowSizeEqualsOne_flushedRowHasMergedCell() { + @ParameterizedTest + @MethodSource("data") + public void test_WindowSizeEqualsOne_flushedRowHasMergedCell(boolean useMergedCells) { workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory sheet = workbook.createSheet(); sheet.trackAllColumnsForAutoSizing(); - + Cell a1 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); assumeRequiredFontsAreInstalled(workbook, a1); assertEquals(0, sheet.addMergedRegion(CellRangeAddress.valueOf("A1:B1"))); - + createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE, SHORT_CELL_VALUE); - + /* * A B * 1 LONGMERGED * 2 SHORT SHORT */ - + sheet.autoSizeColumn(0, useMergedCells); sheet.autoSizeColumn(1, useMergedCells); @@ -217,145 +212,126 @@ public class TestSXSSFSheetAutoSizeColumn { } assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(1), 0, COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG); //short } - - @Test - public void autoSizeColumn_trackColumnForAutoSizing() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_trackColumnForAutoSizing(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); sheet.trackColumnForAutoSizing(0); - + SortedSet expected = new TreeSet<>(); expected.add(0); assertEquals(expected, sheet.getTrackedColumnsForAutoSizing()); - + sheet.autoSizeColumn(0, useMergedCells); - try { - sheet.autoSizeColumn(1, useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(1, useMergedCells), + "Should not be able to auto-size an untracked column"); } - - @Test - public void autoSizeColumn_trackColumnsForAutoSizing() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_trackColumnsForAutoSizing(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackColumnsForAutoSizing(columns); SortedSet sorted = new TreeSet<>(columns); assertEquals(sorted, sheet.getTrackedColumnsForAutoSizing()); - + sheet.autoSizeColumn(sorted.first(), useMergedCells); - try { - assumeFalse(columns.contains(5)); - sheet.autoSizeColumn(5, useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } + assumeFalse(columns.contains(5)); + + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(5, useMergedCells), + "Should not be able to auto-size an untracked column"); } - - @Test - public void autoSizeColumn_untrackColumnForAutoSizing() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_untrackColumnForAutoSizing(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackColumnsForAutoSizing(columns); sheet.untrackColumnForAutoSizing(columns.first()); - + assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(columns.last())); sheet.autoSizeColumn(columns.last(), useMergedCells); - try { - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - sheet.autoSizeColumn(columns.first(), useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } + assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); + + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(columns.first(), useMergedCells), + "Should not be able to auto-size an untracked column"); } - - @Test - public void autoSizeColumn_untrackColumnsForAutoSizing() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_untrackColumnsForAutoSizing(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackColumnForAutoSizing(15); sheet.trackColumnsForAutoSizing(columns); sheet.untrackColumnsForAutoSizing(columns); - + assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(15)); sheet.autoSizeColumn(15, useMergedCells); - try { - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - sheet.autoSizeColumn(columns.first(), useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } + assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); + + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(columns.first(), useMergedCells), + "Should not be able to auto-size an untracked column"); } - + @Test public void autoSizeColumn_isColumnTrackedForAutoSizing() { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackColumnsForAutoSizing(columns); for (int column : columns) { assertTrue(sheet.isColumnTrackedForAutoSizing(column)); - + assumeFalse(columns.contains(column+10)); assertFalse(sheet.isColumnTrackedForAutoSizing(column+10)); } } - - @Test - public void autoSizeColumn_trackAllColumns() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_trackAllColumns(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackAllColumnsForAutoSizing(); sheet.autoSizeColumn(0, useMergedCells); - + sheet.untrackAllColumnsForAutoSizing(); - try { - sheet.autoSizeColumn(0, useMergedCells); - fail("Should not be able to auto-size an implicitly untracked column"); - } catch (final IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(0, useMergedCells), + "Should not be able to auto-size an implicitly untracked column"); } - - @Test - public void autoSizeColumn_trackAllColumns_explicitUntrackColumn() { + + @ParameterizedTest + @MethodSource("data") + public void autoSizeColumn_trackAllColumns_explicitUntrackColumn(boolean useMergedCells) { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(); - + sheet.trackColumnsForAutoSizing(columns); sheet.trackAllColumnsForAutoSizing(); boolean untracked = sheet.untrackColumnForAutoSizing(0); assertTrue(untracked); - try { - sheet.autoSizeColumn(0, useMergedCells); - fail("Should not be able to auto-size an explicitly untracked column"); - } catch (final IllegalStateException e) { - // expected - } + assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(0, useMergedCells), + "Should not be able to auto-size an explicitly untracked column"); } - - + + private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { // autoSize will fail if required fonts are not installed, skip this test then Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); + assumeTrue(SheetUtil.canComputeColumnWidth(font), + "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); } - + private static Cell createRowWithCellValues(final Sheet sheet, final int rowNumber, final String... cellValues) { Row row = sheet.createRow(rowNumber); int cellIndex = 0; @@ -369,12 +345,12 @@ public class TestSXSSFSheetAutoSizeColumn { } return firstCell; } - + private static void assertColumnWidthStrictlyWithinRange(final int actualColumnWidth, final int lowerBoundExclusive, final int upperBoundExclusive) { - assertTrue("Expected a column width greater than " + lowerBoundExclusive + " but found " + actualColumnWidth, - actualColumnWidth > lowerBoundExclusive); - assertTrue("Expected column width less than " + upperBoundExclusive + " but found " + actualColumnWidth, actualColumnWidth < upperBoundExclusive); - + assertTrue(actualColumnWidth > lowerBoundExclusive, + "Expected a column width greater than " + lowerBoundExclusive + " but found " + actualColumnWidth); + assertTrue(actualColumnWidth < upperBoundExclusive, + "Expected column width less than " + upperBoundExclusive + " but found " + actualColumnWidth); } - + } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java index fdaea4ea19..60b4c0de69 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java @@ -17,13 +17,14 @@ package org.apache.poi.xssf.streaming; +import static org.junit.jupiter.api.Assertions.assertEquals; + 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.util.TempFile; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileInputStream; @@ -33,7 +34,7 @@ import java.io.IOException; public class TestSXSSFUnicodeSurrogates { // "𝝊𝝋𝝌𝝍𝝎𝝏𝝐𝝑𝝒𝝓𝝔𝝕𝝖𝝗𝝘𝝙𝝚𝝛𝝜𝝝𝝞𝝟𝝠𝝡𝝢𝝣𝝤𝝥𝝦𝝧𝝨𝝩𝝪𝝫𝝬𝝭𝝮𝝯𝝰𝝱𝝲𝝳𝝴𝝵𝝶𝝷𝝸𝝹𝝺"; - private static String unicodeText = + private static final String unicodeText = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" + "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58" + "\uD835\uDF59\uD835\uDF5A\uD835\uDF5B\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835" + @@ -58,7 +59,7 @@ public class TestSXSSFUnicodeSurrogates { XSSFWorkbook wb2 = new XSSFWorkbook(fis)) { Sheet sheet2 = wb2.getSheet(sheetName); Cell cell2 = sheet2.getRow(0).getCell(0); - Assert.assertEquals(unicodeText, cell2.getStringCellValue()); + assertEquals(unicodeText, cell2.getStringCellValue()); } } finally { tf.delete(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java index efabb8c00e..000c3ba747 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java @@ -21,12 +21,13 @@ package org.apache.poi.xssf.streaming; import static org.apache.poi.POITestCase.assertEndsWith; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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.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; @@ -52,9 +53,9 @@ import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @@ -62,7 +63,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { super(SXSSFITestDataProvider.instance); } - @After + @AfterEach public void tearDown(){ ((SXSSFITestDataProvider)_testDataProvider).cleanup(); } @@ -73,12 +74,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test public void cloneSheet() throws IOException { - try { - super.cloneSheet(); - fail("expected exception"); - } catch (RuntimeException e){ - assertEquals("Not Implemented", e.getMessage()); - } + RuntimeException e = assertThrows(RuntimeException.class, super::cloneSheet); + assertEquals("Not Implemented", e.getMessage()); } /** @@ -87,12 +84,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test public void sheetClone() throws IOException { - try { - super.sheetClone(); - fail("expected exception"); - } catch (RuntimeException e){ - assertEquals("Not Implemented", e.getMessage()); - } + RuntimeException e = assertThrows(RuntimeException.class, super::sheetClone); + assertEquals("Not Implemented", e.getMessage()); } /** @@ -100,7 +93,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { * changes. */ @Override - @Ignore("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") + @Disabled("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") @Test public void setSheetName() { } @@ -288,7 +281,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { assertEquals("sheet" + i, sh.getSheetName()); for(int j = 0; j < rowNum; j++){ Row row = sh.getRow(j); - assertNotNull("row[" + j + "]", row); + assertNotNull(row, "row[" + j + "]"); Cell cell1 = row.getCell(0); assertEquals(new CellReference(cell1).formatAsString(), cell1.getStringCellValue()); @@ -353,7 +346,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { wb2.close(); } - @Ignore("currently writing the same sheet multiple times is not supported...") + @Disabled("currently writing the same sheet multiple times is not supported...") @Test public void bug53515() throws Exception { Workbook wb1 = new SXSSFWorkbook(10); @@ -366,7 +359,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { wb1.close(); } - @Ignore("Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files, " + @Disabled("Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files, " + "see http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html") @Test public void bug53515a() throws Exception { @@ -494,7 +487,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { * TODO Fix this to work! */ @Test - @Ignore + @Disabled public void createFromReadOnlyWorkbook() throws Exception { String sheetName = "Test SXSSF"; File input = XSSFTestDataSamples.getSampleFile("sample.xlsx"); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java index aeffd1a1ab..17b6c7321a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java @@ -19,9 +19,9 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 static java.nio.charset.StandardCharsets.UTF_8; import java.io.ByteArrayInputStream; @@ -31,7 +31,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.util.List; @@ -46,17 +45,17 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * This class tests that an SXSSFWorkbook can be written and read where all temporary disk I/O * is encrypted, but the final saved workbook is not encrypted */ public final class TestSXSSFWorkbookWithCustomZipEntrySource { - + final String sheetName = "TestSheet1"; final String cellValue = "customZipEntrySource"; - + // write an unencrypted workbook to disk, but any temporary files are encrypted @Test public void customZipEntrySource() throws IOException { @@ -77,7 +76,7 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { assertEquals(cellValue, xc1.getStringCellValue()); xwb.close(); } - + // write an encrypted workbook to disk, and encrypt any temporary files as well @Test public void customZipEntrySourceForWriteAndRead() throws IOException, GeneralSecurityException, InvalidFormatException { @@ -105,7 +104,7 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { } } } - + @Test public void validateTempFilesAreEncrypted() throws IOException { TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource workbook = new TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource(); @@ -119,7 +118,7 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { List tempFiles = workbook.getTempFiles(); assertEquals(1, tempFiles.size()); File tempFile = tempFiles.get(0); - assertTrue("tempFile exists?", tempFile.exists()); + assertTrue(tempFile.exists(), "tempFile exists?"); try (InputStream stream = new FileInputStream(tempFile)) { byte[] data = IOUtils.toByteArray(stream); String text = new String(data, UTF_8); @@ -127,6 +126,6 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { assertFalse(text.contains(cellValue)); } workbook.dispose(); - assertFalse("tempFile deleted after dispose?", tempFile.exists()); + assertFalse(tempFile.exists(), "tempFile deleted after dispose?"); } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java index dabd8a882d..257196cc75 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java @@ -19,9 +19,9 @@ package org.apache.poi.xssf.streaming; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.File; import java.io.FileInputStream; @@ -29,7 +29,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestSheetDataWriter { @@ -53,7 +53,7 @@ public final class TestSheetDataWriter { assertTrue(SheetDataWriter.replaceWithQuestionMark('\u000F')); assertTrue(SheetDataWriter.replaceWithQuestionMark('\u001F')); } - + @Test public void testWriteUnicodeSurrogates() throws IOException { SheetDataWriter writer = new SheetDataWriter(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java deleted file mode 100644 index d88d1fd959..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.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.xssf.usermodel; - -import org.apache.poi.ss.formula.eval.forked.BaseTestForkedEvaluator; -import org.apache.poi.xssf.usermodel.extensions.TestXSSFBorder; -import org.apache.poi.xssf.usermodel.extensions.TestXSSFCellFill; -import org.apache.poi.xssf.usermodel.helpers.TestColumnHelper; -import org.apache.poi.xssf.usermodel.helpers.TestHeaderFooterHelper; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.xssf.usermodel and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestFormulaEvaluatorOnXSSF.class, - TestMultiSheetFormulaEvaluatorOnXSSF.class, - TestSheetHiding.class, - TestXSSFBugs.class, - TestXSSFDataFormat.class, - TestXSSFCellStyle.class, - TestXSSFComment.class, - TestXSSFDialogSheet.class, - TestXSSFDrawing.class, - TestXSSFFont.class, - TestXSSFFormulaEvaluation.class, - //TestXSSFHeaderFooter.class, //converted to junit4 - TestXSSFHyperlink.class, - TestXSSFName.class, - TestXSSFPicture.class, - TestXSSFPictureData.class, - TestXSSFPrintSetup.class, - TestXSSFRichTextString.class, - TestXSSFRow.class, - TestXSSFSheet.class, - TestXSSFSheetUpdateArrayFormulas.class, - TestXSSFTable.class, - TestXSSFWorkbook.class, - TestXSSFBorder.class, - TestXSSFCellFill.class, - TestColumnHelper.class, - TestHeaderFooterHelper.class, - //TestXSSFPivotTable.class, //converted to junit4 - BaseTestForkedEvaluator.class -}) -public final class AllXSSFUsermodelTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java index ff16a5358f..b79aeac621 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java @@ -16,9 +16,10 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.io.IOException; @@ -28,9 +29,9 @@ import org.apache.poi.ss.usermodel.DataConsolidateFunction; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageField; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageFields; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields; @@ -47,10 +48,10 @@ public abstract class BaseTestXSSFPivotTable { /** * required to set up the test pivot tables and cell reference, either by name or reference. */ - @Before + @BeforeEach public abstract void setUp(); - @After + @AfterEach public void tearDown() throws IOException { if (wb != null) { XSSFWorkbook wb2 = _testDataProvider.writeOutAndReadBack(wb); @@ -87,9 +88,9 @@ public abstract class BaseTestXSSFPivotTable { /** * Verify that it's not possible to create a row label outside of the referenced area. */ - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testAddRowLabelOutOfRangeThrowsException() { - pivotTable.addRowLabel(5); + assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addRowLabel(5)); } /** @@ -208,9 +209,9 @@ public abstract class BaseTestXSSFPivotTable { /** * Verify that it's not possible to create a column label outside of the referenced area. */ - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testAddColumnLabelOutOfRangeThrowsException() { - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 5); + assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 5)); } /** @@ -230,9 +231,9 @@ public abstract class BaseTestXSSFPivotTable { /** * Verify that it's not possible to create a data column outside of the referenced area. */ - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testAddDataColumnOutOfRangeThrowsException() { - pivotTable.addDataColumn(5, true); + assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addDataColumn(5, true)); } /** @@ -253,9 +254,9 @@ public abstract class BaseTestXSSFPivotTable { /** * Verify that it's not possible to create a new filter outside of the referenced area. */ - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testAddReportFilterOutOfRangeThrowsException() { - pivotTable.addReportFilter(5); + assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addReportFilter(5)); } /** @@ -316,8 +317,8 @@ public abstract class BaseTestXSSFPivotTable { /** * Verify that it's not possible to create a col label outside of the referenced area. */ - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testAddColLabelOutOfRangeThrowsException() { - pivotTable.addColLabel(5); + assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addColLabel(5)); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java index e1ffbd6337..acfccb52ed 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java @@ -17,17 +17,16 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; 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.openxml4j.opc.OPCPackage; @@ -43,12 +42,10 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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; /** * Performs much the same role as {@link TestFormulasFromSpreadsheet}, @@ -60,7 +57,6 @@ import org.junit.runners.Parameterized.Parameters; * Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx * */ -@RunWith(Parameterized.class) public final class TestFormulaEvaluatorOnXSSF { private static final POILogger logger = POILogFactory.getLogger(TestFormulaEvaluatorOnXSSF.class); @@ -72,7 +68,7 @@ public final class TestFormulaEvaluatorOnXSSF { /** * This class defines constants for navigating around the test data spreadsheet used for these tests. */ - private static interface SS { + private interface SS { /** * Name of the test spreadsheet (found in the standard test data folder) @@ -107,21 +103,13 @@ public final class TestFormulaEvaluatorOnXSSF { int NUMBER_OF_ROWS_PER_FUNCTION = 4; } - @Parameter(value = 0) - public String targetFunctionName; - @Parameter(value = 1) - public int formulasRowIdx; - @Parameter(value = 2) - public int expectedValuesRowIdx; - - @AfterClass + @AfterAll public static void closeResource() throws Exception { LocaleUtil.setUserLocale(userLocale); workbook.close(); } - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 @@ -132,7 +120,7 @@ public final class TestFormulaEvaluatorOnXSSF { sheet = workbook.getSheetAt( 0 ); evaluator = new XSSFFormulaEvaluator(workbook); - List data = new ArrayList<>(); + List data = new ArrayList<>(); processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); @@ -140,7 +128,7 @@ public final class TestFormulaEvaluatorOnXSSF { // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - return data; + return data.stream(); } /** @@ -148,7 +136,7 @@ public final class TestFormulaEvaluatorOnXSSF { * @param testFocusFunctionName name of a single function/operator to test alone. * Typically pass null to test all functions */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { + private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { Row r = sheet.getRow(rowIndex); @@ -156,9 +144,9 @@ public final class TestFormulaEvaluatorOnXSSF { if(r == null) continue; String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" + assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); + + SS.FUNCTION_NAMES_END_SENTINEL + "'"); if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { // found end of functions list @@ -169,18 +157,18 @@ public final class TestFormulaEvaluatorOnXSSF { // expected results are on the row below Row expectedValuesRow = sheet.getRow(rowIndex + 1); // +1 for 1-based, +1 for next row - assertNotNull("Missing expected values row for function '" - + targetFunctionName + " (row " + rowIndex + 2 + ")" - , expectedValuesRow); + assertNotNull(expectedValuesRow, "Missing expected values row for function '" + + targetFunctionName + " (row " + rowIndex + 2 + ")"); - data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); + data.add(Arguments.of(targetFunctionName, rowIndex, rowIndex + 1)); } } } - @Test - public void processFunctionRow() { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { Row formulasRow = sheet.getRow(formulasRowIdx); Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); @@ -189,7 +177,7 @@ public final class TestFormulaEvaluatorOnXSSF { // iterate across the row for all the evaluation cases for (short colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { Cell c = formulasRow.getCell(colnum); - assumeNotNull(c); + assumeTrue(c != null); assumeTrue(c.getCellType() == CellType.FORMULA); ignoredFormulaTestCase(c.getCellFormula()); @@ -199,20 +187,20 @@ public final class TestFormulaEvaluatorOnXSSF { String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); + assertNotNull(expValue, msg + " - Bad setup data expected value is null"); + assertNotNull(actValue, msg + " - actual value was null"); final CellType expectedCellType = expValue.getCellType(); switch (expectedCellType) { case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(CellType.BLANK, actValue.getCellType(), msg); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); + assertEquals(CellType.ERROR, actValue.getCellType(), msg); // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values // assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); // } @@ -220,15 +208,15 @@ public final class TestFormulaEvaluatorOnXSSF { 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(msg, CellType.NUMERIC, actValue.getCellType()); - BaseTestNumeric.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); // double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); // double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); // assertTrue(msg, delta <= pctExpValue); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + expectedCellType); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java index 487ce8560a..c56b3d458b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java @@ -17,14 +17,15 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +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.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.functions.BaseTestNumeric; @@ -38,14 +39,11 @@ import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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; -@RunWith(Parameterized.class) public final class TestMatrixFormulasFromXMLSpreadsheet { private static final POILogger LOG = POILogFactory.getLogger(TestMatrixFormulasFromXMLSpreadsheet.class); @@ -96,21 +94,15 @@ public final class TestMatrixFormulasFromXMLSpreadsheet { } - /* Parameters for test case */ - @Parameter(0) - public String targetFunctionName; - @Parameter(1) - public int formulasRowIdx; - @AfterClass + @AfterAll public static void closeResource() throws Exception { LocaleUtil.setUserLocale(userLocale); workbook.close(); } /* generating parameter instances */ - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 @@ -121,11 +113,11 @@ public final class TestMatrixFormulasFromXMLSpreadsheet { sheet = workbook.getSheetAt(0); evaluator = new XSSFFormulaEvaluator(workbook); - List data = new ArrayList(); + List data = new ArrayList<>(); processFunctionGroup(data, Navigator.START_OPERATORS_ROW_INDEX, null); - return data; + return data.stream(); } /** @@ -133,25 +125,27 @@ public final class TestMatrixFormulasFromXMLSpreadsheet { * @param testFocusFunctionName name of a single function/operator to test alone. * Typically pass null to test all functions */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { + private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { for (int rowIndex = startRowIndex; true; rowIndex += Navigator.ROW_OFF_NEXT_OP) { Row r = sheet.getRow(rowIndex); String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" - + (rowIndex) + "). Expected function name or '" - + Navigator.END_OF_TESTS + "'", targetFunctionName); + 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; } if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - data.add(new Object[]{targetFunctionName, rowIndex}); + data.add(Arguments.of(targetFunctionName, rowIndex)); } } } - @Test - public void processFunctionRow() { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow(String targetFunctionName, int formulasRowIdx) { int endColNum = Navigator.START_RESULT_COL_INDEX + Navigator.COL_OFF_EXPECTED_RESULT; @@ -176,31 +170,31 @@ public final class TestMatrixFormulasFromXMLSpreadsheet { String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" , targetFunctionName, c.getCellFormula(), rowNum, colNum); - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); + 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(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(CellType.BLANK, actValue.getCellType(), msg); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); - assertEquals(msg, ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue())); + 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(msg, CellType.NUMERIC, actValue.getCellType()); - BaseTestNumeric.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + cellType); @@ -223,15 +217,11 @@ public final class TestMatrixFormulasFromXMLSpreadsheet { LOG.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + Navigator.START_OPERATORS_COL_INDEX + ", can't figure out function name"); return null; } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - fail("Bad cell type for 'function name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - 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/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java index f8ba0ff7db..55790fde8d 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java @@ -17,12 +17,12 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.formula.BaseTestMissingWorkbook; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; /** * XSSF Specific version of the Missing Workbooks test @@ -33,7 +33,7 @@ public final class TestMissingWorkbookOnXSSF extends BaseTestMissingWorkbook { } @Override - @Before + @BeforeEach public void setUp() { mainWorkbook = XSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java index 09817ecd45..791d8a9034 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java @@ -17,16 +17,16 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeTrue; +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 static org.junit.jupiter.api.Assumptions.assumeTrue; 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.openxml4j.opc.OPCPackage; @@ -40,17 +40,14 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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 for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) */ -@RunWith(Parameterized.class) public final class TestMultiSheetFormulaEvaluatorOnXSSF { private static final POILogger logger = POILogFactory.getLogger(TestMultiSheetFormulaEvaluatorOnXSSF.class); @@ -98,29 +95,22 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { String TEST_SHEET_NAME = "test"; } - @Parameter(value = 0) - public String targetTestName; - @Parameter(value = 1) - public String targetFunctionName; - @Parameter(value = 2) - public int formulasRowIdx; - @AfterClass + @AfterAll public static void closeResource() throws Exception { workbook.close(); } - @Parameters(name="{0}") - public static Collection data() throws Exception { + public static Stream data() throws Exception { workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) ); sheet = workbook.getSheet( SS.TEST_SHEET_NAME ); evaluator = new XSSFFormulaEvaluator(workbook); - List data = new ArrayList<>(); + List data = new ArrayList<>(); processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - return data; + return data.stream(); } /** @@ -128,7 +118,7 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { * @param testFocusFunctionName name of a single function/operator to test alone. * Typically pass null to test all functions */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { + private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { for (int rowIndex = startRowIndex; true; rowIndex++) { Row r = sheet.getRow(rowIndex); @@ -136,9 +126,10 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { if(r == null) continue; String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" + assertNotNull(targetFunctionName, + "Test spreadsheet cell empty on row (" + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); + + SS.FUNCTION_NAMES_END_SENTINEL + "'"); if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { // found end of functions list @@ -150,31 +141,29 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { // expected results are on the row below Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull("Missing expected values cell for function '" + assertNotNull(expectedValueCell, + "Missing expected values cell for function '" + targetFunctionName + ", test" + targetTestName + " (row " + - rowIndex + 1 + ")", expectedValueCell); + rowIndex + 1 + ")"); - data.add(new Object[]{targetTestName, targetFunctionName, rowIndex}); + data.add(Arguments.of(targetTestName, targetFunctionName, rowIndex)); } } } - /** - * - * @return a constant from the local Result class denoting whether there were any evaluation - * cases, and whether they all succeeded. - */ - @Test - public void processFunctionRow() { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow(String targetTestName, String targetFunctionName, int formulasRowIdx) { Row r = sheet.getRow(formulasRowIdx); Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull("Missing expected values cell for function '" + assertNotNull(expValue, + "Missing expected values cell for function '" + targetFunctionName + ", test" + targetTestName + " (row " + - formulasRowIdx + 1 + ")", expValue); + formulasRowIdx + 1 + ")"); Cell c = r.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); - assumeNotNull(c); + assumeTrue(c != null); assumeTrue(c.getCellType() == CellType.FORMULA); CellValue actValue = evaluator.evaluate(c); @@ -182,19 +171,19 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { String msg = String.format(Locale.ROOT, "Function '%s': Test: '%s': Formula: %s @ %d:%d", targetFunctionName, targetTestName, c.getCellFormula(), formulasRowIdx, SS.COLUMN_INDEX_ACTUAL_VALUE); - assertNotNull(msg + " - actual value was null", actValue); + assertNotNull(actValue, msg + " - actual value was null"); final CellType expectedCellType = expValue.getCellType(); switch (expectedCellType) { case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(CellType.BLANK, actValue.getCellType(), msg); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); + assertEquals(CellType.ERROR, actValue.getCellType(), msg); // if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values // assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue()); // } @@ -202,15 +191,15 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { 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(msg, CellType.NUMERIC, actValue.getCellType()); - BaseTestNumeric.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue()); // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue()); // assertTrue(msg, delta <= pctExpected); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + expectedCellType); @@ -230,17 +219,14 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); return null; } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - fail("Bad cell type for 'function name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; + 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; } + /** * @return null if cell is missing, empty or blank */ @@ -254,16 +240,10 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name"); return null; } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } + CellType ct = cell.getCellType(); + assertTrue(ct == CellType.BLANK || ct == CellType.STRING, + "Bad cell type for 'test name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - fail("Bad cell type for 'test name' column: (" - + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; + return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; } - } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java index 44d06dcd33..ad85072249 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java @@ -17,11 +17,12 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.FileOutputStream; @@ -42,8 +43,8 @@ import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; public final class TestSXSSFBugs extends BaseTestBugzillaIssues { @@ -52,11 +53,16 @@ public final class TestSXSSFBugs extends BaseTestBugzillaIssues { } // override some tests which do not work for SXSSF - @Override @Ignore("cloneSheet() not implemented") @Test public void bug18800() { /* cloneSheet() not implemented */ } - @Override @Ignore("cloneSheet() not implemented") @Test public void bug22720() { /* cloneSheet() not implemented */ } - @Override @Ignore("Evaluation is not fully supported") @Test public void bug47815() { /* Evaluation is not supported */ } - @Override @Ignore("Evaluation is not fully supported") @Test public void bug46729_testMaxFunctionArguments() { /* Evaluation is not supported */ } - @Override @Ignore("Reading data is not supported") @Test public void bug57798() { /* Reading data is not supported */ } + @Override @Disabled("cloneSheet() not implemented") @Test + public void bug18800() { /* cloneSheet() not implemented */ } + @Override @Disabled("cloneSheet() not implemented") @Test + public void bug22720() { /* cloneSheet() not implemented */ } + @Override @Disabled("Evaluation is not fully supported") @Test + public void bug47815() { /* Evaluation is not supported */ } + @Override @Disabled("Evaluation is not fully supported") @Test + public void bug46729_testMaxFunctionArguments() { /* Evaluation is not supported */ } + @Override @Disabled("Reading data is not supported") @Test + public void bug57798() { /* Reading data is not supported */ } /** * Setting repeating rows and columns shouldn't break @@ -122,10 +128,8 @@ public final class TestSXSSFBugs extends BaseTestBugzillaIssues { // does not work try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - writeWorkbook(wb, SXSSFITestDataProvider.instance); - fail("Should catch exception here"); - } catch (RuntimeException e) { - // this is not implemented yet + assertThrows(RuntimeException.class, () -> writeWorkbook(wb, SXSSFITestDataProvider.instance), + "this is not implemented yet"); } } @@ -173,7 +177,7 @@ public final class TestSXSSFBugs extends BaseTestBugzillaIssues { } @Test - @Ignore("takes too long for the normal test run") + @Disabled("takes too long for the normal test run") public void test62872() throws Exception { final int COLUMN_COUNT = 300; final int ROW_COUNT = 600000; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java index 11f979f947..b7ad0e9d38 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java @@ -17,10 +17,10 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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 org.apache.poi.ss.usermodel.DifferentialStyleProvider; import org.apache.poi.ss.usermodel.FontFormatting; @@ -30,7 +30,7 @@ import org.apache.poi.ss.usermodel.TableStyle; import org.apache.poi.ss.usermodel.TableStyleInfo; import org.apache.poi.ss.usermodel.TableStyleType; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test built-in table styles @@ -43,37 +43,35 @@ public class TestTableStyles { @Test public void testBuiltinStyleInit() { TableStyle style = XSSFBuiltinTableStyle.TableStyleMedium2.getStyle(); - assertNotNull("no style found for Medium2", style); - assertNull("Should not have style info for blankRow", style.getStyle(TableStyleType.blankRow)); + assertNotNull(style, "no style found for Medium2"); + assertNull(style.getStyle(TableStyleType.blankRow), "Should not have style info for blankRow"); DifferentialStyleProvider headerRow = style.getStyle(TableStyleType.headerRow); - assertNotNull("no header row style", headerRow); + assertNotNull(headerRow, "no header row style"); FontFormatting font = headerRow.getFontFormatting(); - assertNotNull("No header row font formatting", font); - assertTrue("header row not bold", font.isBold()); + assertNotNull(font, "No header row font formatting"); + assertTrue(font.isBold(), "header row not bold"); PatternFormatting fill = headerRow.getPatternFormatting(); - assertNotNull("No header fill", fill); - assertEquals("wrong header fill", 4, ((XSSFColor) fill.getFillBackgroundColorColor()).getTheme()); + assertNotNull(fill, "No header fill"); + assertEquals(4, ((XSSFColor) fill.getFillBackgroundColorColor()).getTheme(), "wrong header fill"); } @Test public void testCustomStyle() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("tableStyle.xlsx"); - - Table table = wb.getTable("Table1"); - assertNotNull("missing table", table); - - TableStyleInfo style = table.getStyle(); - assertNotNull("Missing table style info", style); - assertNotNull("Missing table style", style.getStyle()); - assertEquals("Wrong name", "TestTableStyle", style.getName()); - assertEquals("Wrong name", "TestTableStyle", style.getStyle().getName()); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("tableStyle.xlsx")) { + Table table = wb.getTable("Table1"); + assertNotNull(table, "missing table"); - DifferentialStyleProvider firstColumn = style.getStyle().getStyle(TableStyleType.firstColumn); - assertNotNull("no first column style", firstColumn); - FontFormatting font = firstColumn.getFontFormatting(); - assertNotNull("no first col font", font); - assertTrue("wrong first col bold", font.isBold()); - - wb.close(); + TableStyleInfo style = table.getStyle(); + assertNotNull(style, "Missing table style info"); + assertNotNull(style.getStyle(), "Missing table style"); + assertEquals("TestTableStyle", style.getName(), "Wrong name"); + assertEquals("TestTableStyle", style.getStyle().getName(), "Wrong name"); + + DifferentialStyleProvider firstColumn = style.getStyle().getStyle(TableStyleType.firstColumn); + assertNotNull(firstColumn, "no first column style"); + FontFormatting font = firstColumn.getFontFormatting(); + assertNotNull(font, "no first col font"); + assertTrue(font.isBold(), "wrong first col bold"); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java index a103d4f422..925a878a53 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java @@ -17,10 +17,10 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayOutputStream; import java.io.IOException; @@ -51,7 +51,7 @@ import org.apache.poi.ss.util.RegionUtil; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; /** @@ -105,13 +105,12 @@ public final class TestUnfixedBugs { int millisecondsInDay2 = (int)((value2 - wholeDays2) * DateUtil.DAY_MILLISECONDS + 0.5); assertEquals(wholeDays1, wholeDays2); - // here we see that the time-value is 5 milliseconds apart, one is 86399000 and the other is 86398995, + // here we see that the time-value is 5 milliseconds apart, one is 86399000 and the other is 86398995, // thus one is one second higher than the other - assertEquals("The time-values are 5 milliseconds apart", - millisecondsInDay1, millisecondsInDay2); + assertEquals(millisecondsInDay1, millisecondsInDay2, "The time-values are 5 milliseconds apart"); // when we do the calendar-stuff, there is a boolean which determines if - // the milliseconds are rounded or not, having this at "false" causes the + // the milliseconds are rounded or not, having this at "false" causes the // second to be different here! int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't @@ -133,7 +132,7 @@ public final class TestUnfixedBugs { assertEquals(DateUtil.getJavaDate(value1, false), DateUtil.getJavaDate(value2, false)); } - // When this is fixed, the test case should go to BaseTestXCell with + // When this is fixed, the test case should go to BaseTestXCell with // adjustments to use _testDataProvider to also verify this for XSSF @Test public void testBug57294() throws IOException { @@ -263,8 +262,7 @@ public final class TestUnfixedBugs { checkRow57423(testSheet, 8, "8"); checkRow57423(testSheet, 9, "9"); - assertNull("Row number 10 should be gone after the shift", - testSheet.getRow(10)); + assertNull(testSheet.getRow(10), "Row number 10 should be gone after the shift"); checkRow57423(testSheet, 11, "11"); checkRow57423(testSheet, 12, "10"); @@ -291,21 +289,19 @@ public final class TestUnfixedBugs { assertTrue(posR12 != -1); assertTrue(posR13 != -1); - assertTrue("Need to find row 12 before row 13 after the shifting, but had row 12 at " + posR12 + " and row 13 at " + posR13, - posR12 < posR13); + assertTrue(posR12 < posR13, "Need to find row 12 before row 13 after the shifting, but had row 12 at " + posR12 + " and row 13 at " + posR13); } private void checkRow57423(Sheet testSheet, int rowNum, String contents) { Row row = testSheet.getRow(rowNum); - assertNotNull("Expecting row at rownum " + rowNum, row); + assertNotNull(row, "Expecting row at rownum " + rowNum); CTRow ctRow = ((XSSFRow)row).getCTRow(); assertEquals(rowNum+1, ctRow.getR()); Cell cell = row.getCell(0); - assertNotNull("Expecting cell at rownum " + rowNum, cell); - assertEquals("Did not have expected contents at rownum " + rowNum, - contents + ".0", cell.toString()); + assertNotNull(cell, "Expecting cell at rownum " + rowNum); + assertEquals( contents + ".0", cell.toString(), "Did not have expected contents at rownum " + rowNum ); } @Test @@ -338,8 +334,7 @@ public final class TestUnfixedBugs { long maxSeenRowNum = 0; //1-based for (final CTRow ctRow : wb.getSheetAt(0).getCTWorksheet().getSheetData().getRowList()) { final long rowNum = ctRow.getR(); //1-based - assertTrue("Row " + rowNum + " (1-based) is not in ascending order; previously saw " + maxSeenRowNum, - rowNum > maxSeenRowNum); + assertTrue(rowNum > maxSeenRowNum, "Row " + rowNum + " (1-based) is not in ascending order; previously saw " + maxSeenRowNum); maxSeenRowNum = rowNum; } } @@ -371,10 +366,10 @@ public final class TestUnfixedBugs { } } - public class HsGetValue implements FreeRefFunction { + public static class HsGetValue implements FreeRefFunction { public static final String name = "HsGetValue"; - private Hashtable cellValues; + private final Hashtable cellValues; public HsGetValue(Hashtable cellValues) { super(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index c280784553..f19190e852 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -19,14 +19,16 @@ package org.apache.poi.xssf.usermodel; import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE; import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -113,10 +115,11 @@ import org.apache.poi.xssf.model.CalculationChain; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; import org.apache.xmlbeans.XmlException; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; @@ -351,7 +354,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { String formula = c.getCellFormula(); double cachedFormulaResult = c.getNumericCellValue(); double evaluatedFormulaResult = cv.getNumberValue(); - assertEquals(formula, cachedFormulaResult, evaluatedFormulaResult, 1E-7); + assertEquals(cachedFormulaResult, evaluatedFormulaResult, 1E-7, formula); } } } @@ -465,10 +468,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); Name nm1 = wb.getName("sale_1"); - assertNotNull("name sale_1 should be present", nm1); + assertNotNull(nm1, "name sale_1 should be present"); assertEquals("Sheet1!#REF!", nm1.getRefersToFormula()); Name nm2 = wb.getName("sale_2"); - assertNotNull("name sale_2 should be present", nm2); + assertNotNull(nm2, "name sale_2 should be present"); assertEquals("Sheet1!#REF!", nm2.getRefersToFormula()); cell = sheet.getRow(1).getCell(0); @@ -1437,7 +1440,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { //simulate correct answer String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; - assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula); + assertEquals(correct, formula, "Incorrect formula in " + ref.formatAsString()); } } @@ -1555,40 +1558,31 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void bug56468() throws IOException, InterruptedException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("Hi"); - sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0)); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFRow row = sheet.createRow(0); + XSSFCell cell = row.createCell(0); + cell.setCellValue("Hi"); + sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0)); - // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had different file-creation - // dates stored. - // We try to do a loop until the current second changes in order to avoid problems with some date information that is written to the ZIP and thus - // causes differences - long start = System.currentTimeMillis() / 1000; - while (System.currentTimeMillis() / 1000 == start) { - Thread.sleep(10); + // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had + // different file-creation dates stored. We try to do a loop until the current second changes in order to + // avoid problems with some date information that is written to the ZIP and thus causes differences + long start = System.currentTimeMillis() / 1000; + while (System.currentTimeMillis() / 1000 == start) { + Thread.sleep(10); + } + + ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); + wb.write(bos); + byte[] firstSave = bos.toByteArray(); + bos.reset(); + wb.write(bos); + byte[] secondSave = bos.toByteArray(); + + assertArrayEquals(firstSave, secondSave, + "Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave)); } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); - wb.write(bos); - byte[] firstSave = bos.toByteArray(); - bos.reset(); - wb.write(bos); - byte[] secondSave = bos.toByteArray(); - - /*OutputStream stream = new FileOutputStream("C:\\temp\\poi.xlsx"); - try { - wb.write(stream); - } finally { - stream.close(); - }*/ - - assertArrayEquals("Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave), - firstSave, secondSave); - - wb.close(); } /** @@ -1624,7 +1618,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - @Ignore("Shifting rows is not yet implemented in SXSSFSheet") + @Disabled("Shifting rows is not yet implemented in SXSSFSheet") @Test public void testBug53798XLSXStream() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { @@ -1904,31 +1898,21 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void bug54764() throws IOException, OpenXML4JException, XmlException { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx"); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx")) { + // Check the core properties - will be found but empty, due + // to the expansion being too much to be considered valid + POIXMLProperties props = new POIXMLProperties(pkg); + assertNull(props.getCoreProperties().getTitle()); + assertNull(props.getCoreProperties().getSubject()); + assertNull(props.getCoreProperties().getDescription()); - // Check the core properties - will be found but empty, due - // to the expansion being too much to be considered valid - POIXMLProperties props = new POIXMLProperties(pkg); - assertNull(props.getCoreProperties().getTitle()); - assertNull(props.getCoreProperties().getSubject()); - assertNull(props.getCoreProperties().getDescription()); - - // Now check the spreadsheet itself - try { - new XSSFWorkbook(pkg).close(); - fail("Should fail as too much expansion occurs"); - } catch (POIXMLException e) { - // Expected + // Now check the spreadsheet itself + assertThrows(POIXMLException.class, () -> new XSSFWorkbook(pkg), "Should fail as too much expansion occurs"); } - pkg.close(); // Try with one with the entities in the Content Types - try { - XSSFTestDataSamples.openSamplePackage("54764-2.xlsx").close(); - fail("Should fail as too much expansion occurs"); - } catch (Exception e) { - // Expected - } + assertThrows(Exception.class, () -> XSSFTestDataSamples.openSamplePackage("54764-2.xlsx"), + "Should fail as too much expansion occurs"); // Check we can still parse valid files after all that try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { @@ -1942,13 +1926,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { try (ZipFile zip = new ZipFile(testFile)) { ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml"); XMLReader reader = XMLHelper.newXMLReader(); - try { - reader.parse(new InputSource(zip.getInputStream(ze))); - fail("should have thrown SAXParseException"); - } catch (SAXParseException e) { - assertNotNull(e.getMessage()); - assertTrue(e.getMessage().contains("more than \"1\" entity")); - } + SAXParseException e = assertThrows(SAXParseException.class, + () -> reader.parse(new InputSource(zip.getInputStream(ze)))); + assertNotNull(e.getMessage()); + assertTrue(e.getMessage().contains("more than \"1\" entity")); } } @@ -1957,13 +1938,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { File testFile = XSSFTestDataSamples.getSampleFile("54764.xlsx"); try (ZipFile zip = new ZipFile(testFile)) { ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml"); - try { - DocumentHelper.readDocument(zip.getInputStream(ze)); - fail("should have thrown SAXParseException"); - } catch (SAXParseException e) { - assertNotNull(e.getMessage()); - assertNotEquals(isOldXercesActive(), e.getMessage().contains("DOCTYPE is disallowed when the feature")); - } + SAXParseException e = assertThrows(SAXParseException.class, + () -> DocumentHelper.readDocument(zip.getInputStream(ze))); + assertNotNull(e.getMessage()); + assertNotEquals(isOldXercesActive(), e.getMessage().contains("DOCTYPE is disallowed when the feature")); } } @@ -1991,34 +1969,17 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void bug56800_xlsb() throws IOException { // Can be opened at the OPC level - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb"); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb")) { + // XSSF Workbook gives helpful error + assertThrows(XLSBUnsupportedException.class, () -> new XSSFWorkbook(pkg), ".xlsb files not supported"); - // XSSF Workbook gives helpful error - try { - new XSSFWorkbook(pkg).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned - } - - // Workbook Factory gives helpful error on package - try { - XSSFWorkbookFactory.createWorkbook(pkg).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned + // Workbook Factory gives helpful error on package + assertThrows(XLSBUnsupportedException.class, () -> XSSFWorkbookFactory.createWorkbook(pkg), ".xlsb files not supported"); } // Workbook Factory gives helpful error on file File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb"); - try { - WorkbookFactory.create(xlsbFile).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned - } - - pkg.close(); + assertThrows(XLSBUnsupportedException.class, () -> WorkbookFactory.create(xlsbFile), ".xlsb files not supported"); } private void checkValue(XSSFWorkbook excel, String expect) { @@ -2157,61 +2118,50 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { * A .xlsx file with no Shared Strings table should open fine * in read-only mode */ - @SuppressWarnings("resource") - @Test - public void bug57482() throws IOException, InvalidFormatException { - for (PackageAccess access : new PackageAccess[]{ - PackageAccess.READ_WRITE, PackageAccess.READ - }) { - File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx"); - OPCPackage pkg = OPCPackage.open(file, access); - try { - // Try to open it and read the contents - XSSFWorkbook wb1 = new XSSFWorkbook(pkg); - assertNotNull(wb1.getSharedStringSource()); - assertEquals(0, wb1.getSharedStringSource().getCount()); + @ParameterizedTest + @EnumSource(value = PackageAccess.class, names = {"READ_WRITE", "READ"}) + public void bug57482(PackageAccess access) throws IOException, InvalidFormatException { + File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx"); + try (OPCPackage pkg = OPCPackage.open(file, access); + XSSFWorkbook wb1 = new XSSFWorkbook(pkg)) { + // Try to open it and read the contents - DataFormatter fmt = new DataFormatter(); - XSSFSheet s = wb1.getSheetAt(0); + assertNotNull(wb1.getSharedStringSource()); + assertEquals(0, wb1.getSharedStringSource().getCount()); + + DataFormatter fmt = new DataFormatter(); + XSSFSheet s = wb1.getSheetAt(0); + assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); + assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); + assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); + + // Add a text cell + s.getRow(0).createCell(3).setCellValue("Testing"); + assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); + + // Try to write-out and read again, should only work + // in read-write mode, not read-only mode + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + if (access == PackageAccess.READ) { + fail("Shouln't be able to write from read-only mode"); + } + + // Check again + s = wb2.getSheetAt(0); assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - - // Add a text cell - s.getRow(0).createCell(3).setCellValue("Testing"); assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - // Try to write-out and read again, should only work - // in read-write mode, not read-only mode - XSSFWorkbook wb2 = null; - try { - wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - if (access == PackageAccess.READ) { - fail("Shouln't be able to write from read-only mode"); - } - - // Check again - s = wb2.getSheetAt(0); - assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); - assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); - assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - - } catch (InvalidOperationException e) { - if (access == PackageAccess.READ_WRITE) { - // Shouldn't occur in write-mode - throw e; - } - } finally { - if (wb2 != null) { - wb2.getPackage().revert(); - } + wb2.getPackage().revert(); + } catch (InvalidOperationException e) { + if (access == PackageAccess.READ_WRITE) { + // Shouldn't occur in write-mode + throw e; } - - wb1.getPackage().revert(); - } finally { - pkg.revert(); } + + pkg.revert(); } } @@ -2364,7 +2314,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { * Not currently working - namespace mis-match from XMLBeans */ @Test - @Ignore("XMLBeans namespace mis-match on ooxml-strict files") + @Disabled("XMLBeans namespace mis-match on ooxml-strict files") public void test57699() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) { assertEquals(3, wb.getNumberOfSheets()); @@ -2433,7 +2383,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { public void testBug57826() throws IOException { XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx"); - assertTrue("no sheets in workbook", workbook.getNumberOfSheets() >= 1); + assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook"); XSSFSheet sheet = workbook.getSheetAt(0); XSSFDrawing drawing = sheet.getDrawingPatriarch(); @@ -2910,7 +2860,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { workbook.close(); } - @Ignore("Creates files for checking results manually, actual values are tested in Test*CellStyle") + @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle") @Test public void test58043() throws IOException { saveRotatedTextExample(new HSSFWorkbook(), TempFile.createTempFile("rotated", ".xls")); @@ -2967,7 +2917,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { workbook.close(); } - @Ignore("bug 59442") + @Disabled("bug 59442") @Test public void testSetRGBBackgroundColor() throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); @@ -3011,7 +2961,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { nwb.close(); } - @Ignore("currently fails on POI 3.15 beta 2") + @Disabled("currently fails on POI 3.15 beta 2") @Test public void test55273() throws IOException { try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) { @@ -3054,7 +3004,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { public void noRowNumbers59746() throws IOException { try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) { Sheet sheet = wb.getSheetAt(0); - assertTrue("Last row num: " + sheet.getLastRowNum(), sheet.getLastRowNum() > 20); + assertTrue(sheet.getLastRowNum() > 20, "Last row num: " + sheet.getLastRowNum()); assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue()); assertFalse(sheet.getRow(70).getCell(8).getBooleanCellValue()); @@ -3079,40 +3029,43 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } // This bug is currently open. When this bug is fixed, it should not throw an AssertionError - @Test(expected = AssertionError.class) + @Test public void test55076_collapseColumnGroups() throws Exception { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); + try (Workbook wb = new XSSFWorkbook()) { + Sheet sheet = wb.createSheet(); - // this column collapsing bug only occurs when the grouped columns are different widths - sheet.setColumnWidth(1, 400); - sheet.setColumnWidth(2, 600); - sheet.setColumnWidth(3, 800); + // this column collapsing bug only occurs when the grouped columns are different widths + sheet.setColumnWidth(1, 400); + sheet.setColumnWidth(2, 600); + sheet.setColumnWidth(3, 800); - assertEquals(400, sheet.getColumnWidth(1)); - assertEquals(600, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); + assertEquals(400, sheet.getColumnWidth(1)); + assertEquals(600, sheet.getColumnWidth(2)); + assertEquals(800, sheet.getColumnWidth(3)); - sheet.groupColumn(1, 3); - sheet.setColumnGroupCollapsed(1, true); + sheet.groupColumn(1, 3); + sheet.setColumnGroupCollapsed(1, true); - assertEquals(0, sheet.getColumnOutlineLevel(0)); - assertEquals(1, sheet.getColumnOutlineLevel(1)); - assertEquals(1, sheet.getColumnOutlineLevel(2)); - assertEquals(1, sheet.getColumnOutlineLevel(3)); - assertEquals(0, sheet.getColumnOutlineLevel(4)); + assertEquals(0, sheet.getColumnOutlineLevel(0)); + assertEquals(1, sheet.getColumnOutlineLevel(1)); + assertEquals(1, sheet.getColumnOutlineLevel(2)); + assertEquals(1, sheet.getColumnOutlineLevel(3)); + assertEquals(0, sheet.getColumnOutlineLevel(4)); + + // none of the columns should be hidden + // column group collapsing is a different concept + for (int c = 0; c < 5; c++) { + // if this fails for c == 1 in the future, then the implementation will be correct + // and we need to adapt this test accordingly + assertEquals(c == 1, sheet.isColumnHidden(c), "Column " + c); + } + + assertEquals(400, sheet.getColumnWidth(1)); + // 600 is the correct value! ... 2048 is just for pacifying the test (see above comment) + assertEquals(2048, sheet.getColumnWidth(2)); + assertEquals(800, sheet.getColumnWidth(3)); - // none of the columns should be hidden - // column group collapsing is a different concept - for (int c = 0; c < 5; c++) { - assertFalse("Column " + c, sheet.isColumnHidden(c)); } - - assertEquals(400, sheet.getColumnWidth(1)); - assertEquals(600, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); - - wb.close(); } /** @@ -3217,7 +3170,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { eval.setDebugEvaluationOutputForNextEval(true); CellValue cv = eval.evaluate(c); assertNotNull(cv); - assertEquals("Had: " + cv, 2.0, cv.getNumberValue(), 0.00001); + assertEquals(2.0, cv.getNumberValue(), 0.00001, "Had: " + cv); } } @@ -3246,8 +3199,8 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals("On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF", - expectedFormula, shiftedFmla); + assertEquals(expectedFormula, shiftedFmla, + "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF"); } { @@ -3258,14 +3211,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals("On move we expect the formula to stay the same, thus expecting the initial formula A1 here", - initialFormula, shiftedFmla); + assertEquals(initialFormula, shiftedFmla, + "On move we expect the formula to stay the same, thus expecting the initial formula A1 here"); } sheet.shiftRows(2, 2, -1); { Cell c2 = sheet.getRow(1).getCell(2); - assertNotNull("cell C2 needs to exist now", c2); + assertNotNull(c2, "cell C2 needs to exist now"); assertEquals(CellType.FORMULA, c2.getCellType()); assertEquals(initialFormula, c2.getCellFormula()); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); @@ -3285,8 +3238,8 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { WorkbookEvaluatorProvider fe = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator(); ConditionalFormattingEvaluator condfmt = new ConditionalFormattingEvaluator(wb, fe); - assertEquals("Conditional formatting is not triggered for this cell", - "[]", condfmt.getConditionalFormattingForCell(cell).toString()); + assertEquals("[]", condfmt.getConditionalFormattingForCell(cell).toString(), + "Conditional formatting is not triggered for this cell"); // but we can read the conditional formatting itself List rules = condfmt.getFormatRulesForSheet(sheet); @@ -3419,7 +3372,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { String value = cell.getStringCellValue(); //System.out.println(value); - assertEquals("The data in the text-file should exactly match the data that we read from the workbook", testData, value); + assertEquals(testData, value, "The data in the text-file should exactly match the data that we read from the workbook"); } @@ -3532,12 +3485,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - @Test(expected = POIXMLException.class) - public void test64045() throws IOException, InvalidFormatException { + @Test + public void test64045() { File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); - try (XSSFWorkbook ignored = new XSSFWorkbook(file)) { - fail("Should catch exception as the file is corrupted"); - } + assertThrows(POIXMLException.class, () -> new XSSFWorkbook(file), "Should catch exception as the file is corrupted"); } @Test @@ -3572,26 +3523,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { Cell cell = row.createCell(0, CellType.FORMULA); cell.setCellFormula("SUM(B1:E1)"); - assertNull("Element 'v' should not be set for formulas unless the value was calculated", - ((XSSFCell) cell).getCTCell().getV()); + assertNull(((XSSFCell) cell).getCTCell().getV(), + "Element 'v' should not be set for formulas unless the value was calculated"); try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0); - assertNull("Element 'v' should not be set for formulas unless the value was calculated", - ((XSSFCell) cellBack).getCTCell().getV()); - assertNotNull("Formula should be set internally now", - ((XSSFCell) cellBack).getCTCell().getF()); + assertNull(((XSSFCell) cellBack).getCTCell().getV(), + "Element 'v' should not be set for formulas unless the value was calculated"); + assertNotNull(((XSSFCell) cellBack).getCTCell().getF(), + "Formula should be set internally now"); wbBack.getCreationHelper().createFormulaEvaluator().evaluateInCell(cellBack); - assertEquals("Element 'v' should be set now as the formula was calculated manually", - "0.0", ((XSSFCell) cellBack).getCTCell().getV()); + assertEquals("0.0", ((XSSFCell) cellBack).getCTCell().getV(), + "Element 'v' should be set now as the formula was calculated manually"); cellBack.setCellValue("123"); - assertEquals("String value should be set now", - "123", cellBack.getStringCellValue()); - assertNull("No formula should be set any more", - ((XSSFCell) cellBack).getCTCell().getF()); + assertEquals("123", cellBack.getStringCellValue(), + "String value should be set now"); + assertNull(((XSSFCell) cellBack).getCTCell().getF(), "No formula should be set any more"); } } } @@ -3608,13 +3558,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(2); - assertNull("Element 'v' should not be set for formulas unless the value was calculated", - ((XSSFCell) cellBack).getCTCell().getV()); + assertNull(((XSSFCell) cellBack).getCTCell().getV(), + "Element 'v' should not be set for formulas unless the value was calculated"); wbBack.getCreationHelper().createFormulaEvaluator().evaluateInCell(cellBack); - assertEquals("Element 'v' should be set now as the formula was calculated manually", - "7.0", ((XSSFCell) cellBack).getCTCell().getV()); + assertEquals("7.0", ((XSSFCell) cellBack).getCTCell().getV(), + "Element 'v' should be set now as the formula was calculated manually"); } } } @@ -3627,8 +3577,8 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { Row row = sheet1.getRow(1); CellReference aCellReference = new CellReference("E2"); Cell aCell = row.getCell(aCellReference.getCol()); - Assert.assertEquals(CellType.STRING, aCell.getCellType()); - Assert.assertEquals("", aCell.getStringCellValue()); + assertEquals(CellType.STRING, aCell.getCellType()); + assertEquals("", aCell.getStringCellValue()); } } @@ -3646,7 +3596,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void testXLSXinPPT() throws Exception { - Assume.assumeFalse(Boolean.getBoolean("scratchpad.ignore")); + assumeFalse(Boolean.getBoolean("scratchpad.ignore")); try (SlideShow ppt = SlideShowFactory.create( POIDataSamples.getSlideShowInstance().openResourceAsStream("testPPT_oleWorkbook.ppt"))) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java index c5c0427f17..18aa00d032 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java @@ -17,14 +17,15 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Assertions.fail; import java.io.IOException; import java.util.List; @@ -56,7 +57,7 @@ import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.SharedStringsTable; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; @@ -140,19 +141,19 @@ public final class TestXSSFCell extends BaseTestXCell { assertNull(str.getString()); cell_0.setCellValue(str); assertEquals(0, sst.getCount()); - assertEquals("Having: " + cell_0, CellType.BLANK, cell_0.getCellType()); + assertEquals(CellType.BLANK, cell_0.getCellType(), "Having: " + cell_0); //case 2. cell.setCellValue((String)null); Cell cell_1 = row.createCell(1); cell_1.setCellValue((String)null); assertEquals(0, sst.getCount()); - assertEquals("Having: " + cell_1, CellType.BLANK, cell_1.getCellType()); + assertEquals(CellType.BLANK, cell_1.getCellType(), "Having: " + cell_1); //case 3. cell.setCellValue((RichTextString)null); Cell cell_2 = row.createCell(2); cell_2.setCellValue((RichTextString) null); assertEquals(0, sst.getCount()); - assertEquals("Having: " + cell_2, CellType.BLANK, cell_2.getCellType()); + assertEquals(CellType.BLANK, cell_2.getCellType(), "Having: " + cell_2); wb.close(); } @@ -201,12 +202,7 @@ public final class TestXSSFCell extends BaseTestXCell { cell.setCellFormula(validFormula); // check that invalid formula does throw exception - try { - cell.setCellFormula(invalidFormula); - fail("Should catch exception here"); - } catch (FormulaParseException e) { - // expected here - } + assertThrows(FormulaParseException.class, () -> cell.setCellFormula(invalidFormula)); // set cell formula validation to false wb.setCellFormulaValidation(false); @@ -322,8 +318,8 @@ public final class TestXSSFCell extends BaseTestXCell { XSSFRow rowRef = (XSSFRow)r; XSSFRow row = sheet.getRow(rowRef.getRowNum()); - assertEquals("number of cells in row["+row.getRowNum()+"]", - rowRef.getPhysicalNumberOfCells(), row.getPhysicalNumberOfCells()); + assertEquals(rowRef.getPhysicalNumberOfCells(), row.getPhysicalNumberOfCells(), + "number of cells in row["+row.getRowNum()+"]"); for(Cell c : rowRef){ XSSFCell cellRef = (XSSFCell)c; @@ -333,7 +329,7 @@ public final class TestXSSFCell extends BaseTestXCell { assertEquals(cellRef.getReference(), cell.getReference()); if(!cell.getCTCell().isSetR()){ - assertTrue("R must e set in cellRef", cellRef.getCTCell().isSetR()); + assertTrue(cellRef.getCTCell().isSetR(), "R must e set in cellRef"); String valRef = formater.formatCellValue(cellRef); String val = formater.formatCellValue(cell); @@ -423,12 +419,7 @@ public final class TestXSSFCell extends BaseTestXCell { validateRow(row); // once again with removing the same cell, this throws an exception - try { - row.removeCell(cell1); - fail("Should catch an exception"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> row.removeCell(cell1)); // now check again validateRow(row); @@ -605,15 +596,13 @@ public final class TestXSSFCell extends BaseTestXCell { destCell.copyCellFrom(srcCell, policy); assertNotNull(destCell.getHyperlink()); - assertSame("unit test assumes srcCell and destCell are on the same sheet", - srcCell.getSheet(), destCell.getSheet()); + assertSame(srcCell.getSheet(), destCell.getSheet(), + "unit test assumes srcCell and destCell are on the same sheet"); final List links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 2, links.size()); - assertEquals("source hyperlink", - new CellAddress(srcCell).formatAsString(), links.get(0).getCellRef()); - assertEquals("destination hyperlink", - new CellAddress(destCell).formatAsString(), links.get(1).getCellRef()); + assertEquals(2, links.size(), "number of hyperlinks on sheet"); + assertEquals(new CellAddress(srcCell).formatAsString(), links.get(0).getCellRef(), "source hyperlink"); + assertEquals(new CellAddress(destCell).formatAsString(), links.get(1).getCellRef(), "destination hyperlink"); wb.close(); } @@ -642,8 +631,8 @@ public final class TestXSSFCell extends BaseTestXCell { setLinkCellStyle(wb, destCell); // Pre-condition assumptions. This test is broken if either of these fail. - assertSame("unit test assumes srcCell and destCell are on the same sheet", - srcCell.getSheet(), destCell.getSheet()); + assertSame(srcCell.getSheet(), destCell.getSheet(), + "unit test assumes srcCell and destCell are on the same sheet"); assertNull(srcCell.getHyperlink()); // Merge hyperlink - since srcCell doesn't have a hyperlink, destCell's hyperlink is not overwritten (cleared). @@ -655,9 +644,8 @@ public final class TestXSSFCell extends BaseTestXCell { List links; links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 1, links.size()); - assertEquals("source hyperlink", - new CellAddress(destCell).formatAsString(), links.get(0).getCellRef()); + assertEquals(1, links.size(), "number of hyperlinks on sheet"); + assertEquals(new CellAddress(destCell).formatAsString(), links.get(0).getCellRef(), "source hyperlink"); // Merge destCell's hyperlink to srcCell. Since destCell does have a hyperlink, this should copy destCell's hyperlink to srcCell. srcCell.copyCellFrom(destCell, policy); @@ -665,11 +653,9 @@ public final class TestXSSFCell extends BaseTestXCell { assertNotNull(destCell.getHyperlink()); links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 2, links.size()); - assertEquals("dest hyperlink", - new CellAddress(destCell).formatAsString(), links.get(0).getCellRef()); - assertEquals("source hyperlink", - new CellAddress(srcCell).formatAsString(), links.get(1).getCellRef()); + assertEquals(2, links.size(), "number of hyperlinks on sheet"); + assertEquals(new CellAddress(destCell).formatAsString(), links.get(0).getCellRef(), "dest hyperlink"); + assertEquals(new CellAddress(srcCell).formatAsString(), links.get(1).getCellRef(), "source hyperlink"); wb.close(); } @@ -763,9 +749,9 @@ public final class TestXSSFCell extends BaseTestXCell { } } - @Test(expected = IllegalStateException.class) + @Test public void getErrorCellValue_returns0_onABlankCell() { Cell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0); - cell.getErrorCellValue(); + assertThrows(IllegalStateException.class, cell::getErrorCellValue); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java index 1b2bbdf899..dbea37c010 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java @@ -17,14 +17,14 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -46,8 +46,8 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder; import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellXfs; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; @@ -63,7 +63,7 @@ public class TestXSSFCellStyle { private StylesTable stylesTable; private XSSFCellStyle cellStyle; - @Before + @BeforeEach public void setUp() { stylesTable = new StylesTable(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java index afea5bc1b6..984416cc4a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java @@ -17,14 +17,14 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFChart { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java index ebb098ee93..4f605cc82d 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java @@ -19,12 +19,12 @@ package org.apache.poi.xssf.usermodel; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public final class TestXSSFChartSheet { @@ -48,8 +48,7 @@ public final class TestXSSFChartSheet { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { XSSFChartSheet sheet = (XSSFChartSheet) wb.getSheetAt(2); - assertFalse("Row iterator for charts sheets should return zero rows", - sheet.iterator().hasNext()); + assertFalse(sheet.iterator().hasNext(), "Row iterator for charts sheets should return zero rows"); //access to a arbitrary row assertNull(sheet.getRow(1)); @@ -68,7 +67,7 @@ public final class TestXSSFChartSheet { assertNotNull(sheet.getCTChartsheet()); } } - + @Test public void testGetCharts() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java index 8d068ca678..d7b1a865da 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java @@ -17,16 +17,16 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; @@ -52,26 +52,26 @@ public class TestXSSFColGrouping { */ @Test public void testNoColsWithoutWidthWhenGrouping() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); + sheet.setColumnWidth(4, 5000); + sheet.setColumnWidth(5, 5000); - sheet.groupColumn((short) 4, (short) 7); - sheet.groupColumn((short) 9, (short) 12); + sheet.groupColumn((short) 4, (short) 7); + sheet.groupColumn((short) 9, (short) 12); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping")) { + sheet = wb2.getSheet("test"); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "test52186/cols:" + cols); - for (CTCol col : cols.getColArray()) { - assertTrue("Col width attribute is unset: " + col, col.isSetWidth()); - } + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "test52186/cols:" + cols); + for (CTCol col : cols.getColArray()) { + assertTrue(col.isSetWidth(), "Col width attribute is unset: " + col); + } - wb2.close(); - wb1.close(); + } + } } /** @@ -80,31 +80,31 @@ public class TestXSSFColGrouping { */ @Test public void testNoColsWithoutWidthWhenGroupingAndCollapsing() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); + sheet.setColumnWidth(4, 5000); + sheet.setColumnWidth(5, 5000); - sheet.groupColumn((short) 4, (short) 5); + sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); + sheet.setColumnGroupCollapsed(4, true); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing")) { + sheet = wb2.getSheet("test"); - for (int i = 4; i <= 5; i++) { - assertEquals("Unexpected width of column "+ i, 5000, sheet.getColumnWidth(i)); + for (int i = 4; i <= 5; i++) { + assertEquals(5000, sheet.getColumnWidth(i), "Unexpected width of column " + i); + } + cols = sheet.getCTWorksheet().getColsArray(0); + for (CTCol col : cols.getColArray()) { + assertTrue(col.isSetWidth(), "Col width attribute is unset: " + col); + } + } } - cols = sheet.getCTWorksheet().getColsArray(0); - for (CTCol col : cols.getColArray()) { - assertTrue("Col width attribute is unset: " + col, col.isSetWidth()); - } - wb2.close(); - wb1.close(); } /** @@ -112,47 +112,47 @@ public class TestXSSFColGrouping { */ @Test public void testMergingOverlappingCols_OVERLAPS_2_WRAPS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(1 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + CTCol col = cols.addNewCol(); + col.setMin(1 + 1); + col.setMax(4 + 1); + col.setWidth(20); + col.setCustomWidth(true); - sheet.groupColumn((short) 2, (short) 3); + sheet.groupColumn((short) 2, (short) 3); - sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols); + sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols); - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertTrue(cols.getColArray(0).getCustomWidth()); + assertEquals(0, cols.getColArray(0).getOutlineLevel()); + assertEquals(2, cols.getColArray(0).getMin()); // 1 based + assertEquals(2, cols.getColArray(0).getMax()); // 1 based + assertTrue(cols.getColArray(0).getCustomWidth()); - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); + assertEquals(1, cols.getColArray(1).getOutlineLevel()); + assertEquals(3, cols.getColArray(1).getMin()); // 1 based + assertEquals(4, cols.getColArray(1).getMax()); // 1 based + assertTrue(cols.getColArray(1).getCustomWidth()); - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertTrue(cols.getColArray(2).getCustomWidth()); + assertEquals(0, cols.getColArray(2).getOutlineLevel()); + assertEquals(5, cols.getColArray(2).getMin()); // 1 based + assertEquals(5, cols.getColArray(2).getMax()); // 1 based + assertTrue(cols.getColArray(2).getCustomWidth()); - assertEquals(3, cols.sizeOfColArray()); + assertEquals(3, cols.sizeOfColArray()); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS")) { + sheet = wb2.getSheet("test"); - for (int i = 1; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); + for (int i = 1; i <= 4; i++) { + assertEquals(20 * 256, sheet.getColumnWidth(i), "Unexpected width of column " + i); + } + + } } - - wb2.close(); - wb1.close(); } /** @@ -160,47 +160,47 @@ public class TestXSSFColGrouping { */ @Test public void testMergingOverlappingCols_OVERLAPS_1_WRAPS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + CTCol col = cols.addNewCol(); + col.setMin(2 + 1); + col.setMax(4 + 1); + col.setWidth(20); + col.setCustomWidth(true); - sheet.groupColumn((short) 1, (short) 5); + sheet.groupColumn((short) 1, (short) 5); - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols); + cols = sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols); - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertFalse(cols.getColArray(0).getCustomWidth()); + assertEquals(1, cols.getColArray(0).getOutlineLevel()); + assertEquals(2, cols.getColArray(0).getMin()); // 1 based + assertEquals(2, cols.getColArray(0).getMax()); // 1 based + assertFalse(cols.getColArray(0).getCustomWidth()); - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); + assertEquals(1, cols.getColArray(1).getOutlineLevel()); + assertEquals(3, cols.getColArray(1).getMin()); // 1 based + assertEquals(5, cols.getColArray(1).getMax()); // 1 based + assertTrue(cols.getColArray(1).getCustomWidth()); - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertFalse(cols.getColArray(2).getCustomWidth()); + assertEquals(1, cols.getColArray(2).getOutlineLevel()); + assertEquals(6, cols.getColArray(2).getMin()); // 1 based + assertEquals(6, cols.getColArray(2).getMax()); // 1 based + assertFalse(cols.getColArray(2).getCustomWidth()); - assertEquals(3, cols.sizeOfColArray()); + assertEquals(3, cols.sizeOfColArray()); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS")) { + sheet = wb2.getSheet("test"); - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); + for (int i = 2; i <= 4; i++) { + assertEquals(20 * 256, sheet.getColumnWidth(i), "Unexpected width of column " + i); + } + + } } - - wb2.close(); - wb1.close(); } /** @@ -208,48 +208,48 @@ public class TestXSSFColGrouping { */ @Test public void testMergingOverlappingCols_OVERLAPS_1_MINOR() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + CTCol col = cols.addNewCol(); + col.setMin(2 + 1); + col.setMax(4 + 1); + col.setWidth(20); + col.setCustomWidth(true); - sheet.groupColumn((short) 3, (short) 5); + sheet.groupColumn((short) 3, (short) 5); - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols); + cols = sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols); - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(3, cols.getColArray(0).getMin()); // 1 based - assertEquals(3, cols.getColArray(0).getMax()); // 1 based - assertTrue(cols.getColArray(0).getCustomWidth()); + assertEquals(0, cols.getColArray(0).getOutlineLevel()); + assertEquals(3, cols.getColArray(0).getMin()); // 1 based + assertEquals(3, cols.getColArray(0).getMax()); // 1 based + assertTrue(cols.getColArray(0).getCustomWidth()); - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(4, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); + assertEquals(1, cols.getColArray(1).getOutlineLevel()); + assertEquals(4, cols.getColArray(1).getMin()); // 1 based + assertEquals(5, cols.getColArray(1).getMax()); // 1 based + assertTrue(cols.getColArray(1).getCustomWidth()); - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertFalse(cols.getColArray(2).getCustomWidth()); + assertEquals(1, cols.getColArray(2).getOutlineLevel()); + assertEquals(6, cols.getColArray(2).getMin()); // 1 based + assertEquals(6, cols.getColArray(2).getMax()); // 1 based + assertFalse(cols.getColArray(2).getCustomWidth()); - assertEquals(3, cols.sizeOfColArray()); + assertEquals(3, cols.sizeOfColArray()); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR")) { + sheet = wb2.getSheet("test"); - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256L, sheet.getColumnWidth(i)); + for (int i = 2; i <= 4; i++) { + assertEquals(20 * 256L, sheet.getColumnWidth(i), "Unexpected width of column " + i); + } + assertEquals(sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(5), "Unexpected width of column " + 5); + + } } - assertEquals("Unexpected width of column "+ 5, sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(5)); - - wb2.close(); - wb1.close(); } /** @@ -257,48 +257,48 @@ public class TestXSSFColGrouping { */ @Test public void testMergingOverlappingCols_OVERLAPS_2_MINOR() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("test"); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + CTCol col = cols.addNewCol(); + col.setMin(2 + 1); + col.setMax(4 + 1); + col.setWidth(20); + col.setCustomWidth(true); - sheet.groupColumn((short) 1, (short) 3); + sheet.groupColumn((short) 1, (short) 3); - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols); + cols = sheet.getCTWorksheet().getColsArray(0); + logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols); - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertFalse(cols.getColArray(0).getCustomWidth()); + assertEquals(1, cols.getColArray(0).getOutlineLevel()); + assertEquals(2, cols.getColArray(0).getMin()); // 1 based + assertEquals(2, cols.getColArray(0).getMax()); // 1 based + assertFalse(cols.getColArray(0).getCustomWidth()); - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); + assertEquals(1, cols.getColArray(1).getOutlineLevel()); + assertEquals(3, cols.getColArray(1).getMin()); // 1 based + assertEquals(4, cols.getColArray(1).getMax()); // 1 based + assertTrue(cols.getColArray(1).getCustomWidth()); - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertTrue(cols.getColArray(2).getCustomWidth()); + assertEquals(0, cols.getColArray(2).getOutlineLevel()); + assertEquals(5, cols.getColArray(2).getMin()); // 1 based + assertEquals(5, cols.getColArray(2).getMax()); // 1 based + assertTrue(cols.getColArray(2).getCustomWidth()); - assertEquals(3, cols.sizeOfColArray()); + assertEquals(3, cols.sizeOfColArray()); - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR"); - sheet = wb2.getSheet("test"); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR")) { + sheet = wb2.getSheet("test"); - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256L, sheet.getColumnWidth(i)); + for (int i = 2; i <= 4; i++) { + assertEquals(20 * 256L, sheet.getColumnWidth(i), "Unexpected width of column " + i); + } + assertEquals(sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(1), "Unexpected width of column " + 1); + + } } - assertEquals("Unexpected width of column "+ 1, sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(1)); - - wb2.close(); - wb1.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java index 2a2eece2f5..70c594cf34 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java @@ -17,20 +17,20 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.io.IOException; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColors; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRgbColor; public final class TestXSSFColor { - + @Test public void testIndexedColour() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { @@ -181,7 +181,7 @@ public final class TestXSSFColor { assertEquals(102, rgb4.getRGBWithTint()[2]); } } - + @Test public void testCustomIndexedColour() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx")) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java index c11879b71b..177f4f3ae8 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java @@ -18,13 +18,14 @@ package org.apache.poi.xssf.usermodel; import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Assertions.fail; import java.io.FileOutputStream; import java.io.IOException; @@ -49,8 +50,8 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.CommentsTable; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.xmlbeans.XmlObject; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; @@ -131,12 +132,9 @@ public final class TestXSSFComment extends BaseTestCellComment { XSSFComment comment = sh.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); //passing HSSFRichTextString is incorrect - try { - comment.setString(new HSSFRichTextString(TEST_RICHTEXTSTRING)); - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Only XSSFRichTextString argument is supported", e.getMessage()); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> comment.setString(new HSSFRichTextString(TEST_RICHTEXTSTRING))); + assertEquals("Only XSSFRichTextString argument is supported", e.getMessage()); //simple string argument comment.setString(TEST_RICHTEXTSTRING); @@ -174,7 +172,7 @@ public final class TestXSSFComment extends BaseTestCellComment { assertEquals(8.5, rPr.getSzArray(0).getVal(), 0); assertEquals(IndexedColors.BLUE_GREY.getIndex(), rPr.getColorArray(0).getIndexed()); assertEquals("Tahoma", rPr.getRFontArray(0).getVal()); - + assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); } @@ -198,7 +196,7 @@ public final class TestXSSFComment extends BaseTestCellComment { @Test public void testBug58175() throws IOException { - try (Workbook wb = new SXSSFWorkbook()) { + try (SXSSFWorkbook wb = new SXSSFWorkbook()) { Sheet sheet = wb.createSheet(); Row row = sheet.createRow(1); @@ -218,9 +216,9 @@ public final class TestXSSFComment extends BaseTestCellComment { XSSFClientAnchor ca = (XSSFClientAnchor) anchor; // create comments and vmlDrawing parts if they don't exist - CommentsTable comments = ((SXSSFWorkbook) wb).getXSSFWorkbook() + CommentsTable comments = wb.getXSSFWorkbook() .getSheetAt(0).getCommentsTable(true); - XSSFVMLDrawing vml = ((SXSSFWorkbook) wb).getXSSFWorkbook() + XSSFVMLDrawing vml = wb.getXSSFWorkbook() .getSheetAt(0).getVMLDrawing(true); CTShape vmlShape1 = vml.newCommentShape(); if (ca.isSet()) { @@ -259,12 +257,12 @@ public final class TestXSSFComment extends BaseTestCellComment { assertEquals(table1.getNumberOfComments(), table2.getNumberOfComments()); assertEquals(table1.getRelations(), table2.getRelations());*/ - assertEquals("The vmlShapes should have equal content afterwards", - vmlShape1.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), vmlShape2.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000")); + assertEquals(vmlShape1.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), vmlShape2.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), + "The vmlShapes should have equal content afterwards"); } } - @Ignore("Used for manual testing with opening the resulting Workbook in Excel") + @Disabled("Used for manual testing with opening the resulting Workbook in Excel") @Test public void testBug58175a() throws IOException { try (Workbook wb = new SXSSFWorkbook()) { @@ -323,7 +321,7 @@ public final class TestXSSFComment extends BaseTestCellComment { //wb.write(new FileOutputStream("/tmp/outnocomment.xlsx")); comment = newsheet.getRow(0).getCell(0).getCellComment(); - assertNotNull("Should have a comment on A1 in the new sheet", comment); + assertNotNull(comment, "Should have a comment on A1 in the new sheet"); assertEquals("Comment Here\n", comment.getString().getString()); Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java index f88faa29eb..6ae7f31bf9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java @@ -18,8 +18,8 @@ */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -35,7 +35,7 @@ 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.xssf.XSSFITestDataProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * XSSF-specific Conditional Formatting tests @@ -47,13 +47,13 @@ public class TestXSSFConditionalFormatting extends BaseTestConditionalFormatting } @Override - protected void assertColour(String hexExpected, Color actual) { - assertNotNull("Colour must be given", actual); - XSSFColor colour = (XSSFColor)actual; + protected void assertColor(String hexExpected, Color actual) { + assertNotNull(actual, "Color must be given"); + XSSFColor color = (XSSFColor)actual; if (hexExpected.length() == 8) { - assertEquals(hexExpected, colour.getARGBHex()); + assertEquals(hexExpected, color.getARGBHex()); } else { - assertEquals(hexExpected, colour.getARGBHex().substring(2)); + assertEquals(hexExpected, color.getARGBHex().substring(2)); } } @@ -61,7 +61,7 @@ public class TestXSSFConditionalFormatting extends BaseTestConditionalFormatting public void testRead() throws IOException { testRead("WithConditionalFormatting.xlsx"); } - + @Test public void testReadOffice2007() throws IOException { testReadOffice2007("NewStyleConditionalFormattings.xlsx"); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java index b4c12f8cbe..128ee0a867 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java @@ -17,18 +17,16 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; -import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; import org.apache.poi.ss.formula.WorkbookEvaluatorProvider; import org.apache.poi.ss.usermodel.BaseTestDataFormat; import org.apache.poi.ss.usermodel.BuiltinFormats; 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.DataFormat; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.FormulaEvaluator; @@ -36,7 +34,7 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link XSSFDataFormat} @@ -55,7 +53,7 @@ public final class TestXSSFDataFormat extends BaseTestDataFormat { public void test49928() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49928.xlsx"); doTest49928Core(wb); - + DataFormat dataFormat = wb.createDataFormat(); // As of 2015-12-27, there is no way to override a built-in number format with POI XSSFWorkbook @@ -64,18 +62,18 @@ public final class TestXSSFDataFormat extends BaseTestDataFormat { assertEquals(poundFmtIdx, dataFormat.getFormat(poundFmt)); // 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)); - + wb.close(); } - + /** - * [Bug 58532] Handle formats that go numnum, numK, numM etc + * [Bug 58532] Handle formats that go numnum, numK, numM etc */ @Override @Test @@ -84,7 +82,7 @@ public final class TestXSSFDataFormat extends BaseTestDataFormat { doTest58532Core(wb); wb.close(); } - + /** * [Bug 58778] Built-in number formats can be overridden with XSSFDataFormat.putFormat(int id, String fmt) */ @@ -94,23 +92,23 @@ public final class TestXSSFDataFormat extends BaseTestDataFormat { Cell cell = wb1.createSheet("bug58778").createRow(0).createCell(0); cell.setCellValue(5.25); CellStyle style = wb1.createCellStyle(); - + XSSFDataFormat dataFormat = wb1.createDataFormat(); - + short poundFmtIdx = 6; dataFormat.putFormat(poundFmtIdx, poundFmt); style.setDataFormat(poundFmtIdx); cell.setCellStyle(style); // Cell should appear as "5" - + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutCloseAndReadBack(wb1); cell = wb2.getSheet("bug58778").getRow(0).getCell(0); assertEquals(5.25, cell.getNumericCellValue(), 0); - + style = cell.getCellStyle(); assertEquals(poundFmt, style.getDataFormatString()); assertEquals(poundFmtIdx, style.getDataFormat()); - + // manually check the file to make sure the cell is rendered as "5" // Verified with LibreOffice 4.2.8.2 on 2015-12-28 wb2.close(); @@ -136,17 +134,17 @@ public final class TestXSSFDataFormat extends BaseTestDataFormat { assertEquals("-2.00E+03", formatter.formatCellValue(cell, evaluator, cfEvaluator)); // verify cell format without the conditional rule applied assertEquals("-2000", formatter.formatCellValue(cell, evaluator)); - + ref = new CellReference("A4"); cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); assertEquals("100", formatter.formatCellValue(cell, evaluator, cfEvaluator)); - + ref = new CellReference("A5"); cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); assertEquals("$1,000", formatter.formatCellValue(cell, evaluator, cfEvaluator)); // verify cell format without the conditional rule applied assertEquals("1000", formatter.formatCellValue(cell, evaluator)); - + wb.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java index 8e59366351..9cc9a8f9cf 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 java.math.BigDecimal; @@ -40,7 +40,7 @@ import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFDataValidation extends BaseTestDataValidation { @@ -51,24 +51,23 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { @Test public void testAddValidations() throws Exception { XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("DataValidations-49244.xlsx"); - Sheet sheet = wb1.getSheetAt(0); - List dataValidations = ((XSSFSheet)sheet).getDataValidations(); + XSSFSheet sheet = wb1.getSheetAt(0); + List dataValidations = sheet.getDataValidations(); + + // For each validation type, there are two cells with the same validation. This tests + // application of a single validation definition to multiple cells. + // + // For list ( 3 validations for explicit and 3 for formula ) + // - one validation that allows blank. + // - one that does not allow blank. + // - one that does not show the drop down arrow. + // = 2 + // + // For number validations ( integer/decimal and text length ) with 8 different types of operators. + // = 50 + // + // = 52 ( Total ) -/** - * For each validation type, there are two cells with the same validation. This tests - * application of a single validation definition to multiple cells. - * - * For list ( 3 validations for explicit and 3 for formula ) - * - one validation that allows blank. - * - one that does not allow blank. - * - one that does not show the drop down arrow. - * = 2 - * - * For number validations ( integer/decimal and text length ) with 8 different types of operators. - * = 50 - * - * = 52 ( Total ) - */ assertEquals(52,dataValidations.size()); DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); @@ -111,7 +110,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { Cell thirdCell = row.createCell(3);thirdCell.setCellValue("IL"); int rowNum = row.getRowNum() + 1; - String listFormula = new StringBuilder("$B$").append(rowNum).append(":").append("$D$").append(rowNum).toString(); + String listFormula = "$B$" + rowNum + ":" + "$D$" + rowNum; DataValidationConstraint formulaListValidation = dataValidationHelper.createFormulaListConstraint(listFormula); dataValidation = dataValidationHelper.createValidation(formulaListValidation, cellRangeAddressList); @@ -153,7 +152,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters(validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); //Now create real formula based validation. String formula1 = new CellReference(cell_13.getRowIndex(),cell_13.getColumnIndex()).formatAsString(); @@ -164,7 +163,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters(validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); cellRangeAddressList = new CellRangeAddressList(); if (cell_22 != null) { @@ -173,7 +172,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters( validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); } else if(i==0 && j==1 ){ cellRangeAddressList = new CellRangeAddressList(); cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); @@ -183,14 +182,14 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters( validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); } else { cellRangeAddressList = new CellRangeAddressList(); cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters(validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); } } @@ -221,7 +220,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); setOtherValidationParameters(validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); //Now create real formula based validation. @@ -234,14 +233,14 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { setOtherValidationParameters(validation); sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); + assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); } } XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); wb1.close(); - Sheet sheetAt = wb2.getSheetAt(0); - assertEquals(lastKnownNumValidations,((XSSFSheet)sheetAt).getDataValidations().size()); + XSSFSheet sheetAt = wb2.getSheetAt(0); + assertEquals(lastKnownNumValidations, sheetAt.getDataValidations().size()); wb2.close(); } @@ -376,7 +375,7 @@ public class TestXSSFDataValidation extends BaseTestDataValidation { XSSFFormulaEvaluator fEval = wb.getCreationHelper().createFormulaEvaluator(); DataValidationEvaluator dve = new DataValidationEvaluator(wb, fEval); List values = dve.getValidationValuesForCell(new CellReference("County Ranking", 8, 6, false, false)); - assertEquals("wrong # of valid values", 32, values.size()); + assertEquals(32, values.size(), "wrong # of valid values"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java index 4bd1ad11f0..4bbd2036b0 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.apache.poi.ss.formula.DataValidationEvaluator; import org.apache.poi.ss.usermodel.DataValidationConstraint; @@ -24,7 +24,7 @@ import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; import org.apache.poi.ss.util.CellReference; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.stream.IntStream; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java index 2f35a007b4..4141a2b0a4 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java @@ -17,17 +17,17 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java index aacd1c18db..e2bd1e9a31 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java @@ -24,10 +24,9 @@ import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.FontUnderline; import org.apache.poi.ss.usermodel.ShapeTypes; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.util.Units; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; @@ -35,21 +34,17 @@ import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing; import java.awt.*; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class TestXSSFDrawing { @Test public void bug54803() throws Exception { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("bug54803.xlsx")) { XSSFSheet sheet = wb.getSheetAt(0); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); + sheet.createDrawingPatriarch(); XSSFTestDataSamples.writeOutAndReadBack(wb).close(); } } @@ -835,22 +830,19 @@ public class TestXSSFDrawing { wb2.close(); } - @Test(expected=IllegalArgumentException.class) + @Test public void testBug56835CellComment() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); - // first comment works - ClientAnchor anchor = new XSSFClientAnchor(1, 1, 2, 2, 3, 3, 4, 4); - XSSFComment comment = drawing.createCellComment(anchor); - assertNotNull(comment); + // first comment works + ClientAnchor anchor = new XSSFClientAnchor(1, 1, 2, 2, 3, 3, 4, 4); + XSSFComment comment = drawing.createCellComment(anchor); + assertNotNull(comment); - // Should fail if we try to add the same comment for the same cell - try { - drawing.createCellComment(anchor); - } finally { - wb.close(); + // Should fail if we try to add the same comment for the same cell + assertThrows(IllegalArgumentException.class, () -> drawing.createCellComment(anchor)); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java index fdb8576361..0a92d72c58 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java @@ -16,17 +16,17 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.Test; +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.AbstractMap; import java.util.Map; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +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; public class TestXSSFEvaluationSheet extends BaseTestXEvaluationSheet { @@ -38,24 +38,24 @@ public class TestXSSFEvaluationSheet extends BaseTestXEvaluationSheet { row.createCell(0); XSSFEvaluationSheet evalsheet = new XSSFEvaluationSheet(sheet); - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNull("Cell 0,1 is not found", evalsheet.getCell(0, 1)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); + assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); + assertNull(evalsheet.getCell(0, 1), "Cell 0,1 is not found"); + assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); // now add Cell 0,1 row.createCell(1); - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNotNull("Cell 0,1 is now also found", evalsheet.getCell(0, 1)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); + assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); + assertNotNull(evalsheet.getCell(0, 1), "Cell 0,1 is now also found"); + assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); // after clearing all values it also works row.createCell(2); evalsheet.clearAllCachedResultValues(); - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNotNull("Cell 0,2 is now also found", evalsheet.getCell(0, 2)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); + assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); + assertNotNull(evalsheet.getCell(0, 2), "Cell 0,2 is now also found"); + assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); // other things assertEquals(sheet, evalsheet.getXSSFSheet()); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java index 62e855242d..2f737647ce 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFEvenFooter { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java index e3b12bfe98..e4070c3996 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFEvenHeader { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java index e06faeca1e..8f0a050f8b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFFirstFooter { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java index ab9e575978..1734d0387e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFFirstHeader { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java index a6f75c520b..84e5835bdc 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; @@ -34,7 +34,7 @@ import org.apache.poi.ss.util.SheetUtil; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STVerticalAlignRun; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; @@ -107,29 +107,24 @@ public final class TestXSSFFont extends BaseTestFont{ // This one isn't allowed assertNull(org.apache.poi.ss.usermodel.FontCharset.valueOf(9999)); - try { - xssfFont.setCharSet(9999); - fail("Shouldn't be able to set an invalid charset"); - } catch(POIXMLException e) { - // expected here - } - + assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), + "Shouldn't be able to set an invalid charset"); // Now try with a few sample files // Normal charset - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - wb1.close(); + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { + assertEquals(0, + wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } // GB2312 charset - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx"); - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - wb2.close(); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { + assertEquals(134, + wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } } @Test @@ -157,12 +152,7 @@ public final class TestXSSFFont extends BaseTestFont{ // This one isn't allowed assertNull(FontCharset.valueOf(9999)); - try { - xssfFont.setCharSet(9999); - fail("Shouldn't be able to set an invalid charset"); - } catch(POIXMLException e) { - // expected here - } + assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), "Shouldn't be able to set an invalid charset"); // Now try with a few sample files diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java index b5aa83026a..7f03808ea8 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java @@ -17,10 +17,11 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.HashMap; @@ -37,8 +38,8 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { @@ -104,12 +105,12 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { CellValue cv_noformula = evaluator.evaluate(cell_noformula); CellValue cv_formula = evaluator.evaluate(cell_formula); - assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(), - cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0); + assertEquals(cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0, + "Wrong evaluation result in " + ref_formula.formatAsString()); } } } - + /** * Related to bugs #56737 and #56752 - XSSF workbooks which have * formulas that refer to cells and named ranges in multiple other @@ -149,73 +150,55 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { // Try to evaluate without references, won't work // (At least, not unit we fix bug #56752 that is) - try { - evaluator.evaluate(cXSL_cell); - fail("Without a fix for #56752, shouldn't be able to evaluate a " + - "reference to a non-provided linked workbook"); - } catch (Exception e) { - // expected here - } + assertThrows(Exception.class, () -> evaluator.evaluate(cXSL_cell), + "Without a fix for #56752, shouldn't be able to evaluate a reference to a non-provided linked workbook"); // Setup the environment Map evaluators = new HashMap<>(); evaluators.put("ref2-56737.xlsx", evaluator); - Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx"); - evaluators.put("56737.xlsx", - wbEval1.getCreationHelper().createFormulaEvaluator()); - Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls"); - evaluators.put("56737.xls", - wbEval2.getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); + try (Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx"); + Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls")) { + evaluators.put("56737.xlsx", wbEval1.getCreationHelper().createFormulaEvaluator()); + evaluators.put("56737.xls", wbEval2.getCreationHelper().createFormulaEvaluator()); + evaluator.setupReferencedWorkbooks(evaluators); - // Try evaluating all of them, ensure we don't blow up - for (Row r : s) { - for (Cell c : r) { - evaluator.evaluate(c); + // Try evaluating all of them, ensure we don't blow up + for (Row r : s) { + for (Cell c : r) { + evaluator.evaluate(c); + } } + // And evaluate the other way too + evaluator.evaluateAll(); + + // Static evaluator won't work, as no references passed in + assertThrows(Exception.class, () -> XSSFFormulaEvaluator.evaluateAllFormulaCells(wb), + "Static method lacks references, shouldn't work"); + + // Evaluate specific cells and check results + assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); + assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); + assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); + + assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); + assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); + assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); + + + // Add another formula referencing these workbooks + Cell cXSL_cell2 = rXSL.createCell(40); + cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); + // TODO Shouldn't it become [2] like the others? + assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); + assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); + + + // Now add a formula that refers to yet another (different) workbook + // Won't work without the workbook being linked + Cell cXSLX_nw_cell = rXSLX.createCell(42); + assertThrows(Exception.class, () -> cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"), + "New workbook not linked, shouldn't be able to add"); } - // And evaluate the other way too - evaluator.evaluateAll(); - - // Static evaluator won't work, as no references passed in - try { - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - fail("Static method lacks references, shouldn't work"); - } catch (Exception e) { - // expected here - } - - - // Evaluate specific cells and check results - assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); - - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); - - - // Add another formula referencing these workbooks - Cell cXSL_cell2 = rXSL.createCell(40); - cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); - // TODO Shouldn't it become [2] like the others? - assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); - - - // Now add a formula that refers to yet another (different) workbook - // Won't work without the workbook being linked - Cell cXSLX_nw_cell = rXSLX.createCell(42); - try { - cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); - fail("New workbook not linked, shouldn't be able to add"); - } catch (Exception e) { - // expected here - } - - wbEval1.close(); - wbEval2.close(); // Link and re-try try (Workbook alt = new XSSFWorkbook()) { @@ -229,10 +212,8 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { assertEquals("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula()); // Evaluate it, without a link to that workbook - try { - evaluator.evaluate(cXSLX_nw_cell); - fail("No cached value and no link to workbook, shouldn't evaluate"); - } catch(Exception e) {} + assertThrows(Exception.class, () -> evaluator.evaluate(cXSLX_nw_cell), + "No cached value and no link to workbook, shouldn't evaluate"); // Add a link, check it does evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator()); @@ -244,7 +225,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { } } } - + /** * If a formula references cells or named ranges in another workbook, * but that isn't available at evaluation time, the cached values @@ -252,13 +233,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { * TODO Add the support then add a unit test * See bug #56752 */ - @Test - @Ignore + @Disabled public void testCachedReferencesToOtherWorkbooks() { - // TODO - fail("unit test not written yet"); } - + /** * A handful of functions (such as SUM, COUNTA, MIN) support * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from @@ -275,57 +253,57 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); Sheet s1 = wb.getSheetAt(0); - + // Simple SUM over numbers Cell sumF = s1.getRow(2).getCell(0); assertNotNull(sumF); assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - assertEquals("Failed for " + wb.getClass(), "66.0", evaluator.evaluate(sumF).formatAsString()); - - + assertEquals("66.0", evaluator.evaluate(sumF).formatAsString(), "Failed for " + wb.getClass()); + + // Various Stats formulas on numbers Cell avgF = s1.getRow(2).getCell(1); assertNotNull(avgF); assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); assertEquals("22.0", evaluator.evaluate(avgF).formatAsString()); - + Cell minF = s1.getRow(3).getCell(1); assertNotNull(minF); assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula()); assertEquals("11.0", evaluator.evaluate(minF).formatAsString()); - + Cell maxF = s1.getRow(4).getCell(1); assertNotNull(maxF); assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); assertEquals("33.0", evaluator.evaluate(maxF).formatAsString()); - + Cell countF = s1.getRow(5).getCell(1); assertNotNull(countF); assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula()); assertEquals("3.0", evaluator.evaluate(countF).formatAsString()); - - + + // Various CountAs on Strings Cell countA_1F = s1.getRow(2).getCell(2); assertNotNull(countA_1F); assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula()); assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString()); - + Cell countA_2F = s1.getRow(2).getCell(3); assertNotNull(countA_2F); assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula()); assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString()); - + Cell countA_3F = s1.getRow(2).getCell(4); assertNotNull(countA_3F); assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula()); assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString()); } - + wb2.close(); wb1.close(); } - + /** * A handful of functions (such as SUM, COUNTA, MIN) support * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2, @@ -342,36 +320,36 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); Sheet s1 = wb.getSheetAt(0); - + // SUM over a range Cell sumFA = s1.getRow(2).getCell(7); assertNotNull(sumFA); assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - assertEquals("Failed for " + wb.getClass(), "110.0", evaluator.evaluate(sumFA).formatAsString()); + assertEquals("110.0", evaluator.evaluate(sumFA).formatAsString(), "Failed for " + wb.getClass()); + - // Various Stats formulas on ranges of numbers Cell avgFA = s1.getRow(2).getCell(8); assertNotNull(avgFA); assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString()); - + Cell minFA = s1.getRow(3).getCell(8); assertNotNull(minFA); assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula()); assertEquals("11.0", evaluator.evaluate(minFA).formatAsString()); - + Cell maxFA = s1.getRow(4).getCell(8); assertNotNull(maxFA); assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString()); - + Cell countFA = s1.getRow(5).getCell(8); assertNotNull(countFA); assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); assertEquals("4.0", evaluator.evaluate(countFA).formatAsString()); } - + wb2.close(); wb1.close(); } @@ -381,9 +359,9 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { public void structuredReferences() throws IOException { verifyAllFormulasInWorkbookCanBeEvaluated("evaluate_formula_with_structured_table_references.xlsx"); } - + // bug 57840 - @Ignore("Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.") + @Disabled("Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.") @Test public void testLotsOfFormulasWithStructuredReferencesToCalculatedTableColumns() throws IOException { verifyAllFormulasInWorkbookCanBeEvaluated("StructuredRefs-lots-with-lookups.xlsx"); @@ -412,7 +390,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { assertEquals(1, value.getNumberValue(), 0.001); } } - + @Test public void evaluateInCellReturnsSameDataType() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { @@ -423,7 +401,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { assertSame(cell, same); } } - + @Test public void testBug61468() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) { @@ -435,9 +413,9 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { assertEquals(3750, value.getNumberValue(), 0.001); } } - + @Test - @Ignore // this is from an open bug/discussion over handling localization for number formats + @Disabled // this is from an open bug/discussion over handling localization for number formats public void testBug61495() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); @@ -453,7 +431,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { } } - + /** * see bug 62834, handle when a shared formula range doesn't contain only formula cells */ @@ -464,17 +442,17 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { Cell a2 = wb.getSheetAt(0).getRow(1).getCell(0); Cell value = evaluator.evaluateInCell(a2); - assertEquals("wrong value A2", "a value", value.getStringCellValue()); - + assertEquals("a value", value.getStringCellValue(), "wrong value A2"); + // evaluator.clearAllCachedResultValues(); - + Cell a3 = wb.getSheetAt(0).getRow(2).getCell(0); value = evaluator.evaluateInCell(a3); - assertEquals("wrong value A3", "a value", value.getStringCellValue()); - + assertEquals("a value", value.getStringCellValue(), "wrong value A3"); + Cell a5 = wb.getSheetAt(0).getRow(4).getCell(0); value = evaluator.evaluateInCell(a5); - assertEquals("wrong value A5", "another value", value.getStringCellValue()); + assertEquals("another value", value.getStringCellValue(), "wrong value A5"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java index 912ebdd49e..49876ec205 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java @@ -17,11 +17,12 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.IOException; import java.util.Arrays; @@ -62,7 +63,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFFormulaParser { private static Ptg[] parse(FormulaParsingWorkbook fpb, String fmla) { @@ -80,38 +81,31 @@ public final class TestXSSFFormulaParser { ptgs = parse(fpb, "ABC10"); assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); + assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); ptgs = parse(fpb, "A500000"); assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); + assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); ptgs = parse(fpb, "ABC500000"); assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); + assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); //highest allowed rows and column (XFD and 0x100000) ptgs = parse(fpb, "XFD1048576"); assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); + assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); //column greater than XFD - try { - /*ptgs =*/ parse(fpb, "XFE10"); - fail("expected exception"); - } catch (FormulaParseException e){ - assertEquals("Specified named range 'XFE10' does not exist in the current workbook.", e.getMessage()); - } + FormulaParseException e; + e = assertThrows(FormulaParseException.class, () -> parse(fpb, "XFE10")); + assertEquals("Specified named range 'XFE10' does not exist in the current workbook.", e.getMessage()); //row greater than 0x100000 - try { - /*ptgs =*/ parse(fpb, "XFD1048577"); - fail("expected exception"); - } catch (FormulaParseException e){ - assertEquals("Specified named range 'XFD1048577' does not exist in the current workbook.", e.getMessage()); - } - + e = assertThrows(FormulaParseException.class, () -> parse(fpb, "XFD1048577")); + assertEquals("Specified named range 'XFD1048577' does not exist in the current workbook.", e.getMessage()); + // Formula referencing one cell ptgs = parse(fpb, "ISEVEN(A1)"); assertEquals(3, ptgs.length); @@ -121,7 +115,7 @@ public final class TestXSSFFormulaParser { assertEquals("ISEVEN", ptgs[0].toFormulaString()); assertEquals("A1", ptgs[1].toFormulaString()); assertEquals("#external#", ptgs[2].toFormulaString()); - + // Formula referencing an area ptgs = parse(fpb, "SUM(A1:B3)"); assertEquals(2, ptgs.length); @@ -129,7 +123,7 @@ public final class TestXSSFFormulaParser { assertEquals(AttrPtg.class, ptgs[1].getClass()); assertEquals("A1:B3", ptgs[0].toFormulaString()); assertEquals("SUM", ptgs[1].toFormulaString()); - + // Formula referencing one cell in a different sheet ptgs = parse(fpb, "SUM(Sheet1!A1)"); assertEquals(2, ptgs.length); @@ -137,7 +131,7 @@ public final class TestXSSFFormulaParser { assertEquals(AttrPtg.class, ptgs[1].getClass()); assertEquals("Sheet1!A1", ptgs[0].toFormulaString()); assertEquals("SUM", ptgs[1].toFormulaString()); - + // Formula referencing an area in a different sheet ptgs = parse(fpb, "SUM(Sheet1!A1:B3)"); assertEquals(2, ptgs.length); @@ -157,16 +151,16 @@ public final class TestXSSFFormulaParser { ptgs = parse(fpb, "LOG10"); assertEquals(1, ptgs.length); - assertTrue("",(ptgs[0] instanceof RefPtg)); + assertTrue(ptgs[0] instanceof RefPtg); ptgs = parse(fpb, "LOG10(100)"); assertEquals(2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof IntPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof FuncPtg); + assertTrue(ptgs[0] instanceof IntPtg); + assertTrue(ptgs[1] instanceof FuncPtg); wb.close(); } - + @Test public void formulaReferencesSameWorkbook() throws IOException { // Use a test file with "other workbook" style references @@ -187,7 +181,7 @@ public final class TestXSSFFormulaParser { wb.close(); } - + @Test public void formulaReferencesOtherSheets() throws IOException { // Use a test file with the named ranges in place @@ -202,7 +196,7 @@ public final class TestXSSFFormulaParser { assertEquals(-1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); assertEquals("Uses!A1", ptgs[0].toFormulaString()); - + // Reference to a single cell in a different sheet, which needs quoting ptgs = parse(fpb, "'Testing 47100'!A1"); assertEquals(1, ptgs.length); @@ -211,7 +205,7 @@ public final class TestXSSFFormulaParser { assertEquals("Testing 47100", ((Ref3DPxg)ptgs[0]).getSheetName()); assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); assertEquals("'Testing 47100'!A1", ptgs[0].toFormulaString()); - + // Reference to a sheet scoped named range from another sheet ptgs = parse(fpb, "Defines!NR_To_A1"); assertEquals(1, ptgs.length); @@ -220,7 +214,7 @@ public final class TestXSSFFormulaParser { assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); assertEquals("Defines!NR_To_A1", ptgs[0].toFormulaString()); - + // Reference to a workbook scoped named range ptgs = parse(fpb, "NR_Global_B2"); assertEquals(1, ptgs.length); @@ -229,7 +223,7 @@ public final class TestXSSFFormulaParser { wb.close(); } - + @Test public void formulaReferencesOtherWorkbook() throws IOException { // Use a test file with the external linked table in place @@ -245,7 +239,7 @@ public final class TestXSSFFormulaParser { assertEquals("Uses",((Ref3DPxg)ptgs[0]).getSheetName()); assertEquals("$A$1",((Ref3DPxg)ptgs[0]).format2DRefAsString()); assertEquals("[1]Uses!$A$1", ptgs[0].toFormulaString()); - + // Reference to a sheet-scoped named range in a different workbook ptgs = parse(fpb, "[1]Defines!NR_To_A1"); assertEquals(1, ptgs.length); @@ -254,7 +248,7 @@ public final class TestXSSFFormulaParser { assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); assertEquals("[1]Defines!NR_To_A1", ptgs[0].toFormulaString()); - + // Reference to a global named range in a different workbook ptgs = parse(fpb, "[1]!NR_Global_B2"); assertEquals(1, ptgs.length); @@ -266,15 +260,15 @@ public final class TestXSSFFormulaParser { wb.close(); } - + /** * A handful of functions (such as SUM, COUNTA, MIN) support * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from - * Sheets 1 through Sheet 3) and multi-sheet area references + * Sheets 1 through Sheet 3) and multi-sheet area references * (eg Sheet1:Sheet3!A1:B2 = Cells A1 through B2 from Sheets * 1 through Sheet 3). * This test, based on common test files for HSSF and XSSF, checks - * that we can read and parse these kinds of references + * that we can read and parse these kinds of references * (but not evaluate - that's elsewhere in the test suite) */ @Test @@ -286,42 +280,42 @@ public final class TestXSSFFormulaParser { for (Workbook wb : wbs) { Sheet s1 = wb.getSheetAt(0); Ptg[] ptgs; - + // Check the contents Cell sumF = s1.getRow(2).getCell(0); assertNotNull(sumF); assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - + Cell avgF = s1.getRow(2).getCell(1); assertNotNull(avgF); assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); - + Cell countAF = s1.getRow(2).getCell(2); assertNotNull(countAF); assertEquals("COUNTA(Sheet1:Sheet3!C1)", countAF.getCellFormula()); - + Cell maxF = s1.getRow(4).getCell(1); assertNotNull(maxF); assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); - - + + Cell sumFA = s1.getRow(2).getCell(7); assertNotNull(sumFA); assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - + Cell avgFA = s1.getRow(2).getCell(8); assertNotNull(avgFA); assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); - + Cell maxFA = s1.getRow(4).getCell(8); assertNotNull(maxFA); assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); - + Cell countFA = s1.getRow(5).getCell(8); assertNotNull(countFA); assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); - - + + // Create a formula parser final FormulaParsingWorkbook fpb; if (wb instanceof HSSFWorkbook) @@ -395,7 +389,7 @@ public final class TestXSSFFormulaParser { Cell newF = s1.getRow(0).createCell(10, CellType.FORMULA); newF.setCellFormula("SUM(Sheet2:Sheet3!A1)"); assertEquals("SUM(Sheet2:Sheet3!A1)", newF.getCellFormula()); - + // Check we can round-trip - try to set a new one to a cell range newF = s1.getRow(0).createCell(11, CellType.FORMULA); newF.setCellFormula("MIN(Sheet1:Sheet2!A1:B2)"); @@ -414,17 +408,15 @@ public final class TestXSSFFormulaParser { @Test public void test58648Single() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); + Ptg[] ptgs; - ptgs = parse(fpb, "(ABC10 )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - - wb.close(); + ptgs = parse(fpb, "(ABC10 )"); + assertEquals(2, ptgs.length, "Had: " + Arrays.toString(ptgs)); + assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); + assertTrue(ptgs[1] instanceof ParenthesisPtg, "Had " + Arrays.toString(ptgs)); + } } @Test @@ -435,43 +427,37 @@ public final class TestXSSFFormulaParser { // verify whitespaces in different places ptgs = parse(fpb, "(ABC10)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); + assertEquals(2, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); ptgs = parse(fpb, "( ABC10)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); + assertEquals(2, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); ptgs = parse(fpb, "(ABC10 )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); + assertEquals(2, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); ptgs = parse(fpb, "((ABC10))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); + assertEquals(3, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); + assertTrue(ptgs[2] instanceof ParenthesisPtg); ptgs = parse(fpb, "((ABC10) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); + assertEquals(3, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); + assertTrue(ptgs[2] instanceof ParenthesisPtg); ptgs = parse(fpb, "( (ABC10))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); + assertEquals(3, ptgs.length); + assertTrue(ptgs[0] instanceof RefPtg); + assertTrue(ptgs[1] instanceof ParenthesisPtg); + assertTrue(ptgs[2] instanceof ParenthesisPtg); wb.close(); } @@ -515,41 +501,36 @@ public final class TestXSSFFormulaParser { // verify whitespaces in different places ptgs = parse(fpb, "INTERCEPT(A2:A5, B2:B5)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof FuncPtg); + assertEquals(3, ptgs.length); + assertTrue(ptgs[0] instanceof AreaPtg); + assertTrue(ptgs[1] instanceof AreaPtg); + assertTrue(ptgs[2] instanceof FuncPtg); ptgs = parse(fpb, " INTERCEPT ( \t \r A2 : \nA5 , B2 : B5 ) \t"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof FuncPtg); + assertEquals(3, ptgs.length); + assertTrue(ptgs[0] instanceof AreaPtg); + assertTrue(ptgs[1] instanceof AreaPtg); + assertTrue(ptgs[2] instanceof FuncPtg); ptgs = parse(fpb, "(VLOOKUP(\"item1\", A2:B3, 2, FALSE) - VLOOKUP(\"item2\", A2:B3, 2, FALSE) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 12, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof StringPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof IntPtg); + assertEquals(12, ptgs.length); + assertTrue(ptgs[0] instanceof StringPtg); + assertTrue(ptgs[1] instanceof AreaPtg); + assertTrue(ptgs[2] instanceof IntPtg); ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals("Had: " + Arrays.toString(ptgs), - 4, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemAreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof IntersectionPtg); + assertEquals(4, ptgs.length); + assertTrue(ptgs[0] instanceof MemAreaPtg); + assertTrue(ptgs[1] instanceof AreaPtg); + assertTrue(ptgs[2] instanceof AreaPtg); + assertTrue(ptgs[3] instanceof IntersectionPtg); ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals("Had: " + Arrays.toString(ptgs), - 4, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemAreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof IntersectionPtg); + assertEquals(4, ptgs.length); + assertTrue(ptgs[0] instanceof MemAreaPtg); + assertTrue(ptgs[1] instanceof AreaPtg); + assertTrue(ptgs[2] instanceof AreaPtg); + assertTrue(ptgs[3] instanceof IntersectionPtg); wb.close(); } @@ -562,20 +543,18 @@ public final class TestXSSFFormulaParser { // verify whitespaces in different places ptgs = parse(fpb, "SUM(A1:INDEX(1:1048576,MAX(IFERROR(MATCH(99^99,B:B,1),0),IFERROR(MATCH(\"zzzz\",B:B,1),0)),MAX(IFERROR(MATCH(99^99,1:1,1),0),IFERROR(MATCH(\"zzzz\",1:1,1),0))))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 40, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemFuncPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof NameXPxg); + assertEquals(40, ptgs.length); + assertTrue(ptgs[0] instanceof MemFuncPtg); + assertTrue(ptgs[1] instanceof RefPtg); + assertTrue(ptgs[2] instanceof AreaPtg); + assertTrue(ptgs[3] instanceof NameXPxg); ptgs = parse(fpb, "SUM ( A1 : INDEX( 1 : 1048576 , MAX( IFERROR ( MATCH ( 99 ^ 99 , B : B , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , B:B , 1 ) , 0 ) ) , MAX ( IFERROR ( MATCH ( 99 ^ 99 , 1 : 1 , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , 1 : 1 , 1 ) , 0 ) ) ) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 40, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemFuncPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof NameXPxg); + assertEquals(40, ptgs.length); + assertTrue(ptgs[0] instanceof MemFuncPtg); + assertTrue(ptgs[1] instanceof RefPtg); + assertTrue(ptgs[2] instanceof AreaPtg); + assertTrue(ptgs[3] instanceof NameXPxg); wb.close(); } @@ -632,42 +611,42 @@ public final class TestXSSFFormulaParser { ////// Case 1: Evaluate "Table1[col]" //////// ptgs = parse(fpb, tbl+"[Name]"); assertEquals(1, ptgs.length); - assertEquals("Table1[col]", "Table!B2:B7", ptgs[0].toFormulaString()); + assertEquals("Table!B2:B7", ptgs[0].toFormulaString(), "Table1[col]"); ////// Case 2: Evaluate "Table1[[#Totals],[col]]" //////// ptgs = parse(fpb, tbl+"[[#Totals],[col]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); + assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]]" + noTotalsRowReason); ////// Case 3: Evaluate "Table1[#Totals]" //////// ptgs = parse(fpb, tbl+"[#Totals]"); assertEquals(1, ptgs.length); - assertEquals("Table1[#Totals]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); + assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[#Totals]" + noTotalsRowReason); ////// Case 4: Evaluate "Table1[#All]" //////// ptgs = parse(fpb, tbl+"[#All]"); assertEquals(1, ptgs.length); - assertEquals("Table1[#All]", "Table!A1:C7", ptgs[0].toFormulaString()); + assertEquals("Table!A1:C7", ptgs[0].toFormulaString(), "Table1[#All]"); ////// Case 5: Evaluate "Table1[#Data]" (excludes Header and Data rows) //////// ptgs = parse(fpb, tbl+"[#Data]"); assertEquals(1, ptgs.length); - assertEquals("Table1[#Data]", "Table!A2:C7", ptgs[0].toFormulaString()); + assertEquals("Table!A2:C7", ptgs[0].toFormulaString(), "Table1[#Data]"); ////// Case 6: Evaluate "Table1[#Headers]" //////// ptgs = parse(fpb, tbl+"[#Headers]"); assertEquals(1, ptgs.length); - assertEquals("Table1[#Headers]", "Table!A1:C1", ptgs[0].toFormulaString()); + assertEquals("Table!A1:C1", ptgs[0].toFormulaString(), "Table1[#Headers]"); ////// Case 7: Evaluate "Table1[#Totals]" //////// ptgs = parse(fpb, tbl+"[#Totals]"); assertEquals(1, ptgs.length); - assertEquals("Table1[#Totals]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); + assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[#Totals]" + noTotalsRowReason); ////// Case 8: Evaluate "Table1[#This Row]" //////// ptgs = parse(fpb, tbl+"[#This Row]", 2); assertEquals(1, ptgs.length); - assertEquals("Table1[#This Row]", "Table!A3:C3", ptgs[0].toFormulaString()); + assertEquals("Table!A3:C3", ptgs[0].toFormulaString(), "Table1[#This Row]"); ////// Evaluate "Table1[@]" (equivalent to "Table1[#This Row]") //////// ptgs = parse(fpb, tbl+"[@]", 2); @@ -677,70 +656,70 @@ public final class TestXSSFFormulaParser { ////// Evaluate "Table1[#This Row]" when rowIndex is outside Table //////// ptgs = parse(fpb, tbl+"[#This Row]", 10); assertEquals(1, ptgs.length); - assertEquals("Table1[#This Row]", ErrPtg.VALUE_INVALID, ptgs[0]); + assertEquals(ErrPtg.VALUE_INVALID, ptgs[0], "Table1[#This Row]"); ////// Evaluate "Table1[@]" when rowIndex is outside Table //////// ptgs = parse(fpb, tbl+"[@]", 10); assertEquals(1, ptgs.length); - assertEquals("Table1[@]", ErrPtg.VALUE_INVALID, ptgs[0]); + assertEquals(ErrPtg.VALUE_INVALID, ptgs[0], "Table1[@]"); ////// Evaluate "Table1[[#Data],[col]]" //////// ptgs = parse(fpb, tbl+"[[#Data], [Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Data],[col]]", "Table!C2:C7", ptgs[0].toFormulaString()); + assertEquals("Table!C2:C7", ptgs[0].toFormulaString(), "Table1[[#Data],[col]]"); ////// Case 9: Evaluate "Table1[[#All],[col]]" //////// ptgs = parse(fpb, tbl+"[[#All], [Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#All],[col]]", "Table!C1:C7", ptgs[0].toFormulaString()); + assertEquals("Table!C1:C7", ptgs[0].toFormulaString(), "Table1[[#All],[col]]"); ////// Case 10: Evaluate "Table1[[#Headers],[col]]" //////// ptgs = parse(fpb, tbl+"[[#Headers], [Number]]"); assertEquals(1, ptgs.length); // also acceptable: Table1!B1 - assertEquals("Table1[[#Headers],[col]]", "Table!C1:C1", ptgs[0].toFormulaString()); + assertEquals("Table!C1:C1", ptgs[0].toFormulaString(), "Table1[[#Headers],[col]]"); ////// Case 11: Evaluate "Table1[[#Totals],[col]]" //////// ptgs = parse(fpb, tbl+"[[#Totals],[Name]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); + assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]]" + noTotalsRowReason); ////// Case 12: Evaluate "Table1[[#All],[col1]:[col2]]" //////// ptgs = parse(fpb, tbl+"[[#All], [Name]:[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#All],[col1]:[col2]]", "Table!B1:C7", ptgs[0].toFormulaString()); + assertEquals("Table!B1:C7", ptgs[0].toFormulaString(), "Table1[[#All],[col1]:[col2]]"); ////// Case 13: Evaluate "Table1[[#Data],[col]:[col2]]" //////// ptgs = parse(fpb, tbl+"[[#Data], [Name]:[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Data],[col]:[col2]]", "Table!B2:C7", ptgs[0].toFormulaString()); + assertEquals("Table!B2:C7", ptgs[0].toFormulaString(), "Table1[[#Data],[col]:[col2]]"); ////// Case 14: Evaluate "Table1[[#Headers],[col1]:[col2]]" //////// ptgs = parse(fpb, tbl+"[[#Headers], [Name]:[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Headers],[col1]:[col2]]", "Table!B1:C1", ptgs[0].toFormulaString()); + assertEquals("Table!B1:C1", ptgs[0].toFormulaString(), "Table1[[#Headers],[col1]:[col2]]"); ////// Case 15: Evaluate "Table1[[#Totals],[col]:[col2]]" //////// ptgs = parse(fpb, tbl+"[[#Totals], [Name]:[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]:[col2]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); + assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]:[col2]]" + noTotalsRowReason); ////// Case 16: Evaluate "Table1[[#Headers],[#Data],[col]]" //////// ptgs = parse(fpb, tbl+"[[#Headers],[#Data],[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[#Headers],[#Data],[col]]", "Table!C1:C7", ptgs[0].toFormulaString()); + assertEquals("Table!C1:C7", ptgs[0].toFormulaString(), "Table1[[#Headers],[#Data],[col]]"); ////// Case 17: Evaluate "Table1[[#This Row], [col1]]" //////// ptgs = parse(fpb, tbl+"[[#This Row], [Number]]", 2); assertEquals(1, ptgs.length); // also acceptable: Table!C3 - assertEquals("Table1[[#This Row], [col1]]", "Table!C3:C3", ptgs[0].toFormulaString()); + assertEquals("Table!C3:C3", ptgs[0].toFormulaString(), "Table1[[#This Row], [col1]]"); ////// Case 18: Evaluate "Table1[[col]:[col2]]" //////// ptgs = parse(fpb, tbl+"[[Name]:[Number]]"); assertEquals(1, ptgs.length); - assertEquals("Table1[[col]:[col2]]", "Table!B2:C7", ptgs[0].toFormulaString()); + assertEquals("Table!B2:C7", ptgs[0].toFormulaString(), "Table1[[col]:[col2]]"); wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java index 92e7f7fcbe..7137cdb8fa 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java @@ -17,27 +17,27 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFHeaderFooterProperties { - + private XSSFWorkbook wb; private XSSFSheet sheet; private XSSFHeaderFooterProperties hfProp; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); hfProp = sheet.getHeaderFooterProperties(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java index faadec0b62..d9090cf53f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java @@ -27,11 +27,11 @@ import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public final class TestXSSFHyperlink extends BaseTestHyperlink { public TestXSSFHyperlink() { @@ -98,23 +98,19 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { @Test public void testInvalidURLs() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFCreationHelper createHelper = workbook.getCreationHelper(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFCreationHelper createHelper = workbook.getCreationHelper(); - String[] invalidURLs = { + String[] invalidURLs = { "http:\\apache.org", "www.apache .org", "c:\\temp", "\\poi"}; - for(String s : invalidURLs){ - try { - createHelper.createHyperlink(HyperlinkType.URL).setAddress(s); - fail("expected IllegalArgumentException: " + s); - } catch (IllegalArgumentException e){ - // expected here + for (String s : invalidURLs) { + assertThrows(IllegalArgumentException.class, + () -> createHelper.createHyperlink(HyperlinkType.URL).setAddress(s)); } } - workbook.close(); } @Test @@ -312,24 +308,24 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { CellAddress A7 = new CellAddress("A7"); XSSFHyperlink link = sh.getHyperlink(A2); - assertEquals("address", "A2", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getType()); - assertEquals("link target", "http://twitter.com/#!/apacheorg", link.getAddress()); + assertEquals("A2", link.getCellRef(), "address"); + assertEquals(HyperlinkType.URL, link.getType(), "link type"); + assertEquals("http://twitter.com/#!/apacheorg", link.getAddress(), "link target"); link = sh.getHyperlink(A3); - assertEquals("address", "A3", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getType()); - assertEquals("link target", "http://www.bailii.org/databases.html#ie", link.getAddress()); + assertEquals("A3", link.getCellRef(), "address"); + assertEquals(HyperlinkType.URL, link.getType(), "link type"); + assertEquals("http://www.bailii.org/databases.html#ie", link.getAddress(), "link target"); link = sh.getHyperlink(A4); - assertEquals("address", "A4", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getType()); - assertEquals("link target", "https://en.wikipedia.org/wiki/Apache_POI#See_also", link.getAddress()); + assertEquals("A4", link.getCellRef(), "address"); + assertEquals(HyperlinkType.URL, link.getType(), "link type"); + assertEquals("https://en.wikipedia.org/wiki/Apache_POI#See_also", link.getAddress(), "link target"); link = sh.getHyperlink(A7); - assertEquals("address", "A7", link.getCellRef()); - assertEquals("link type", HyperlinkType.DOCUMENT, link.getType()); - assertEquals("link target", "Sheet1", link.getAddress()); + assertEquals("A7", link.getCellRef(), "address"); + assertEquals(HyperlinkType.DOCUMENT, link.getType(), "link type"); + assertEquals("Sheet1", link.getAddress(), "link target"); wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java index 3989d74d66..96d9dc4346 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java @@ -17,16 +17,16 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Arrays; -import org.junit.Test; import org.apache.poi.ss.usermodel.BaseTestNamedRange; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFITestDataProvider; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -76,7 +76,7 @@ public final class TestXSSFName extends BaseTestNamedRange { // Save and re-open XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); wb.close(); - + assertEquals(1, nwb.getNumberOfNames()); nr1 = nwb.getName(XSSFName.BUILTIN_PRINT_TITLE); @@ -142,12 +142,8 @@ public final class TestXSSFName extends BaseTestNamedRange { // Cell addresses/references are not allowed for (String ref : Arrays.asList("A1", "$A$1", "A1:B2")) { - try { - name.setNameName(ref); - fail("cell addresses are not allowed: " + ref); - } catch (final IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> name.setNameName(ref), + "cell addresses are not allowed: " + ref); } // Name that looks similar to a cell reference but is outside the cell reference row and column limits diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java index 0a20a20e57..e9f51bc02e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFOddFooter { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java index 4f53c2f244..fe49bdd175 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java @@ -17,24 +17,24 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestXSSFOddHeader { - + private XSSFWorkbook wb; private XSSFSheet sheet; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java index e5599479cf..be741242c3 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.IOException; import java.util.List; @@ -29,7 +29,7 @@ import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.STEditAs; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java index db2801fc3d..27c7acd238 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java @@ -17,17 +17,17 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +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 java.io.IOException; import java.util.List; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -129,7 +129,7 @@ public final class TestXSSFPictureData { List shapes1 = sheet1.createDrawingPatriarch().getShapes(); assertNotNull(shapes1); assertEquals(5, shapes1.size()); - + for(int i = 0; i < wb.getNumberOfSheets(); i++){ XSSFSheet sheet = wb.getSheetAt(i); XSSFDrawing drawing = sheet.createDrawingPatriarch(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java index 8df2a663da..a8ea2eeafc 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java @@ -20,7 +20,7 @@ package org.apache.poi.xssf.usermodel; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellReference; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; /** * Test pivot tables created by named range @@ -28,7 +28,7 @@ import org.junit.Before; public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { @Override - @Before + @BeforeEach public void setUp(){ wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); @@ -67,9 +67,9 @@ public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { XSSFName namedRange = sheet.getWorkbook().createName(); namedRange.setRefersToFormula(sheet.getSheetName() + "!" + "A1:C2"); pivotTable = sheet.createPivotTable(namedRange, new CellReference("H5")); - + XSSFSheet offsetSheet = wb.createSheet(); - + Row tableRow_1 = offsetSheet.createRow(1); offsetOuterCell = tableRow_1.createCell(1); offsetOuterCell.setCellValue(-1); @@ -79,7 +79,7 @@ public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { tableCell_1_2.setCellValue("Exponent"); Cell tableCell_1_3 = tableRow_1.createCell(4); tableCell_1_3.setCellValue("10^Exponent"); - + Row tableRow_2 = offsetSheet.createRow(2); Cell tableCell_2_1 = tableRow_2.createCell(2); tableCell_2_1.setCellValue(0); @@ -87,7 +87,7 @@ public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { tableCell_2_2.setCellValue(0); Cell tableCell_2_3 = tableRow_2.createCell(4); tableCell_2_3.setCellValue(1); - + Row tableRow_3= offsetSheet.createRow(3); Cell tableCell_3_1 = tableRow_3.createCell(2); tableCell_3_1.setCellValue(1); @@ -95,7 +95,7 @@ public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { tableCell_3_2.setCellValue(1); Cell tableCell_3_3 = tableRow_3.createCell(4); tableCell_3_3.setCellValue(10); - + Row tableRow_4 = offsetSheet.createRow(4); Cell tableCell_4_1 = tableRow_4.createCell(2); tableCell_4_1.setCellValue(2); @@ -103,7 +103,7 @@ public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { tableCell_4_2.setCellValue(2); Cell tableCell_4_3 = tableRow_4.createCell(4); tableCell_4_3.setCellValue(100); - + namedRange = sheet.getWorkbook().createName(); namedRange.setRefersToFormula("C2:E4"); namedRange.setSheetIndex(sheet.getWorkbook().getSheetIndex(sheet)); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java index 2eb7253b7d..d132b52326 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java @@ -21,15 +21,15 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; /** * Test pivot tables created by area reference */ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { - + @Override - @Before + @BeforeEach public void setUp(){ wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); @@ -67,9 +67,9 @@ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { AreaReference source = wb.getCreationHelper().createAreaReference("A1:C2"); pivotTable = sheet.createPivotTable(source, new CellReference("H5")); - + XSSFSheet offsetSheet = wb.createSheet(); - + Row tableRow_1 = offsetSheet.createRow(1); offsetOuterCell = tableRow_1.createCell(1); offsetOuterCell.setCellValue(-1); @@ -79,7 +79,7 @@ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { tableCell_1_2.setCellValue("Exponent"); Cell tableCell_1_3 = tableRow_1.createCell(4); tableCell_1_3.setCellValue("10^Exponent"); - + Row tableRow_2 = offsetSheet.createRow(2); Cell tableCell_2_1 = tableRow_2.createCell(2); tableCell_2_1.setCellValue(0); @@ -87,7 +87,7 @@ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { tableCell_2_2.setCellValue(0); Cell tableCell_2_3 = tableRow_2.createCell(4); tableCell_2_3.setCellValue(1); - + Row tableRow_3= offsetSheet.createRow(3); Cell tableCell_3_1 = tableRow_3.createCell(2); tableCell_3_1.setCellValue(1); @@ -95,7 +95,7 @@ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { tableCell_3_2.setCellValue(1); Cell tableCell_3_3 = tableRow_3.createCell(4); tableCell_3_3.setCellValue(10); - + Row tableRow_4 = offsetSheet.createRow(4); Cell tableCell_4_1 = tableRow_4.createCell(2); tableCell_4_1.setCellValue(2); @@ -103,7 +103,7 @@ public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { tableCell_4_2.setCellValue(2); Cell tableCell_4_3 = tableRow_4.createCell(4); tableCell_4_3.setCellValue(100); - + AreaReference offsetSource = wb.getCreationHelper().createAreaReference( new CellReference("C2"), new CellReference("E4")); offsetPivotTable = offsetSheet.createPivotTable(offsetSource, new CellReference("C6")); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java index db700a9054..4f0f0b02c0 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java @@ -22,7 +22,7 @@ import org.apache.poi.ss.usermodel.PaperSize; import org.apache.poi.ss.usermodel.PrintCellComments; import org.apache.poi.ss.usermodel.PrintOrientation; import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageMargins; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageSetup; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; @@ -30,9 +30,9 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellComments; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STOrientation; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPageOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link XSSFPrintSetup} @@ -254,23 +254,23 @@ public class TestXSSFPrintSetup { XSSFSheet s1 = wb.createSheet(); assertFalse(s1.getCTWorksheet().isSetPageSetup()); assertTrue(s1.getCTWorksheet().isSetPageMargins()); - + XSSFPrintSetup print = s1.getPrintSetup(); assertTrue(s1.getCTWorksheet().isSetPageSetup()); assertTrue(s1.getCTWorksheet().isSetPageMargins()); - + print.setCopies((short)3); print.setLandscape(true); assertEquals(3, print.getCopies()); assertTrue(print.getLandscape()); - + XSSFSheet s2 = wb.createSheet(); assertFalse(s2.getCTWorksheet().isSetPageSetup()); assertTrue(s2.getCTWorksheet().isSetPageMargins()); - + // Round trip and check XSSFWorkbook wbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(wb); - + s1 = wbBack.getSheetAt(0); s2 = wbBack.getSheetAt(1); @@ -278,11 +278,11 @@ public class TestXSSFPrintSetup { assertTrue(s1.getCTWorksheet().isSetPageMargins()); assertFalse(s2.getCTWorksheet().isSetPageSetup()); assertTrue(s2.getCTWorksheet().isSetPageMargins()); - + print = s1.getPrintSetup(); assertEquals(3, print.getCopies()); assertTrue(print.getLandscape()); - + wb.close(); } @@ -298,12 +298,12 @@ public class TestXSSFPrintSetup { @Test public void testSetLandscapeFalse() { XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - + assertFalse(ps.getLandscape()); - + ps.setLandscape(true); assertTrue(ps.getLandscape()); - + ps.setLandscape(false); assertFalse(ps.getLandscape()); } @@ -311,12 +311,12 @@ public class TestXSSFPrintSetup { @Test public void testSetLeftToRight() { XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - + assertFalse(ps.getLeftToRight()); - + ps.setLeftToRight(true); assertTrue(ps.getLeftToRight()); - + ps.setLeftToRight(false); assertFalse(ps.getLeftToRight()); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java index e83ad65ead..d4efdb6321 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java @@ -17,13 +17,14 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Assertions.fail; import java.io.IOException; import java.util.TreeMap; @@ -33,7 +34,7 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.StylesTable; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STXstring; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; @@ -124,13 +125,7 @@ public final class TestXSSFRichTextString { StylesTable tbl = new StylesTable(); rt.setStylesTableReference(tbl); - - try { - rt.applyFont(0, 10, (short)1); - fail("Fails without styles in the table"); - } catch (IndexOutOfBoundsException e) { - // expected - } + assertThrows(IndexOutOfBoundsException.class, () -> rt.applyFont(0, 10, (short)1), "Fails without styles in the table"); tbl.putFont(new XSSFFont()); rt.applyFont(0, 10, (short)1); @@ -142,27 +137,15 @@ public final class TestXSSFRichTextString { XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); rt.applyFont(0, 0, (short)1); + IllegalArgumentException e; + e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(11, 10, (short)1)); + assertTrue(e.getMessage().contains("11")); - try { - rt.applyFont(11, 10, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("11")); - } + e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(-1, 10, (short)1)); + assertTrue(e.getMessage().contains("-1")); - try { - rt.applyFont(-1, 10, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("-1")); - } - - try { - rt.applyFont(0, 555, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("555")); - } + e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(0, 555, (short)1)); + assertTrue(e.getMessage().contains("555")); } @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java index 669544fd41..fcfda3bb3b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +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.io.IOException; @@ -32,7 +32,7 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSSFRow @@ -96,38 +96,38 @@ public final class TestXSSFRow extends BaseTestXRow { col = 0; Cell cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("RefPtg", "B6", cell.getCellFormula()); + assertEquals("B6", cell.getCellFormula(), "RefPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "src!B6", cell.getCellFormula()); + assertEquals("src!B6", cell.getCellFormula(), "Ref3DPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "dest!B6", cell.getCellFormula()); + assertEquals("dest!B6", cell.getCellFormula(), "Ref3DPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "other!B6", cell.getCellFormula()); + assertEquals("other!B6", cell.getCellFormula(), "Ref3DPtg"); ///////////////////////////////////////////// //Test 2D and 3D Ref Ptgs with absolute row (Ptg row number shouldn't change) cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("RefPtg", "B$5", cell.getCellFormula()); + assertEquals("B$5", cell.getCellFormula(), "RefPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "src!B$5", cell.getCellFormula()); + assertEquals("src!B$5", cell.getCellFormula(), "Ref3DPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "dest!B$5", cell.getCellFormula()); + assertEquals("dest!B$5", cell.getCellFormula(), "Ref3DPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Ref3DPtg", "other!B$5", cell.getCellFormula()); + assertEquals("other!B$5", cell.getCellFormula(), "Ref3DPtg"); ////////////////////////////////////////// @@ -136,19 +136,19 @@ public final class TestXSSFRow extends BaseTestXRow { // to maintain topLeft:bottomRight order cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Area2DPtg", "SUM(B$5:D6)", cell.getCellFormula()); + assertEquals("SUM(B$5:D6)", cell.getCellFormula(), "Area2DPtg"); cell = destRow.getCell(col++); assertNotNull(cell); - assertEquals("Area3DPtg", "SUM(src!B$5:D6)", cell.getCellFormula()); + assertEquals("SUM(src!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); cell = destRow.getCell(col++); assertNotNull(destRow.getCell(6)); - assertEquals("Area3DPtg", "SUM(dest!B$5:D6)", cell.getCellFormula()); + assertEquals("SUM(dest!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); cell = destRow.getCell(col++); assertNotNull(destRow.getCell(7)); - assertEquals("Area3DPtg", "SUM(other!B$5:D6)", cell.getCellFormula()); + assertEquals("SUM(other!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); workbook.close(); } @@ -179,19 +179,19 @@ public final class TestXSSFRow extends BaseTestXRow { // to the new row (and allow the old row to be garbage collected) // this is mostly so existing references to rows that are overwritten are updated // rather than allowing users to continue updating rows that are no longer part of the sheet - assertSame("existing references to srcRow are still valid", srcRow, sheet1.getRow(0)); - assertSame("existing references to destRow are still valid", destRow, sheet1.getRow(1)); - assertSame("existing references to observerRow are still valid", observerRow, sheet1.getRow(2)); - assertSame("existing references to externObserverRow are still valid", externObserverRow, sheet2.getRow(0)); + assertSame(srcRow, sheet1.getRow(0), "existing references to srcRow are still valid"); + assertSame(destRow, sheet1.getRow(1), "existing references to destRow are still valid"); + assertSame(observerRow, sheet1.getRow(2), "existing references to observerRow are still valid"); + assertSame(externObserverRow, sheet2.getRow(0), "existing references to externObserverRow are still valid"); // Make sure copyRowFrom actually copied row (this is tested elsewhere) assertEquals(CellType.STRING, destRow.getCell(0).getCellType()); assertEquals("hello", destRow.getCell(0).getStringCellValue()); // We don't want #REF! errors if we copy a row that contains cells that are referred to by other cells outside of copied region - assertEquals("references to overwritten cells are unmodified", "A2", observerRow.getCell(0).getCellFormula()); - assertEquals("references to overwritten cells are unmodified", "B2", observerRow.getCell(1).getCellFormula()); - assertEquals("references to overwritten cells are unmodified", "Sheet1!A2", externObserverRow.getCell(0).getCellFormula()); + assertEquals("A2", observerRow.getCell(0).getCellFormula(), "references to overwritten cells are unmodified"); + assertEquals("B2", observerRow.getCell(1).getCellFormula(), "references to overwritten cells are unmodified"); + assertEquals("Sheet1!A2", externObserverRow.getCell(0).getCellFormula(), "references to overwritten cells are unmodified"); workbook.close(); } @@ -220,19 +220,15 @@ public final class TestXSSFRow extends BaseTestXRow { XSSFTestDataSamples.writeOutAndReadBack(wb1); assertEquals("hello", srcRow.getCell(0).getStringCellValue()); - assertEquals("hello", - wb1.getSheet("Sheet1").getRow(0).getCell(0).getStringCellValue()); + assertEquals("hello", wb1.getSheet("Sheet1").getRow(0).getCell(0).getStringCellValue()); assertEquals("cruel", srcRow.getCell(1).getStringCellValue()); - assertEquals("cruel", - wb1.getSheet("Sheet1").getRow(0).getCell(1).getStringCellValue()); + assertEquals("cruel", wb1.getSheet("Sheet1").getRow(0).getCell(1).getStringCellValue()); assertEquals("world", srcRow.getCell(3).getStringCellValue()); - assertEquals("world", - wb1.getSheet("Sheet1").getRow(0).getCell(3).getStringCellValue()); + assertEquals("world", wb1.getSheet("Sheet1").getRow(0).getCell(3).getStringCellValue()); srcRow.getCell(1).setCellValue((RichTextString) null); XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals("Cell should be blank", CellType.BLANK, - wb3.getSheet("Sheet1").getRow(0).getCell(1).getCellType()); + assertEquals(CellType.BLANK, wb3.getSheet("Sheet1").getRow(0).getCell(1).getCellType(), "Cell should be blank"); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java index 3955219e20..f262211718 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java @@ -17,14 +17,14 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSSFShape @@ -64,8 +64,7 @@ public final class TestXSSFShape { str.append(", Row1:").append(((XSSFClientAnchor) shape.getAnchor()).getRow1()); str.append(", Row2:").append(((XSSFClientAnchor) shape.getAnchor()).getRow2()); } - - assertEquals("Having shapes: " + str, - expectedShapes, shapes.size()); + + assertEquals(expectedShapes, shapes.size(), "Having shapes: " + str); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java index 1ed0273e35..204190b0c9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java @@ -17,15 +17,17 @@ package org.apache.poi.xssf.usermodel; +import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Arrays; @@ -55,6 +57,7 @@ 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.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; @@ -67,7 +70,8 @@ import org.apache.poi.xssf.model.CommentsTable; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.helpers.ColumnHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; @@ -289,8 +293,8 @@ public final class TestXSSFSheet extends BaseTestXSheet { sheet.removeMergedRegion(1); sheet.removeMergedRegion(0); assertEquals(0, sheet.getNumMergedRegions()); - assertNull(" CTMergeCells should be deleted after removing the last merged " + - "region on the sheet.", sheet.getCTWorksheet().getMergeCells()); + assertNull(sheet.getCTWorksheet().getMergeCells(), + "CTMergeCells should be deleted after removing the last merged region on the sheet."); assertEquals(0, sheet.addMergedRegion(region_1)); assertEquals(1, sheet.addMergedRegion(region_2)); assertEquals(2, sheet.addMergedRegion(region_3)); @@ -415,23 +419,20 @@ public final class TestXSSFSheet extends BaseTestXSheet { workbook.close(); } - @Test(expected=IllegalArgumentException.class) + @Test public void setZoom() throws IOException { - XSSFWorkbook workBook = new XSSFWorkbook(); - XSSFSheet sheet1 = workBook.createSheet("new sheet"); - sheet1.setZoom(75); // 75 percent magnification - long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 75); + try (XSSFWorkbook workBook = new XSSFWorkbook()) { + XSSFSheet sheet1 = workBook.createSheet("new sheet"); + sheet1.setZoom(75); // 75 percent magnification + long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); + assertEquals(zoom, 75); - sheet1.setZoom(200); - zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 200); + sheet1.setZoom(200); + zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); + assertEquals(zoom, 200); - // Valid scale values range from 10 to 400 - try { - sheet1.setZoom(500); - } finally { - workBook.close(); + // Valid scale values range from 10 to 400 + assertThrows(IllegalArgumentException.class, () -> sheet1.setZoom(500)); } } @@ -443,118 +444,117 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test public void setColumnGroupCollapsed() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet1 = wb1.createSheet(); - CTCols cols = sheet1.getCTWorksheet().getColsArray(0); - assertEquals(0, cols.sizeOfColArray()); + CTCols cols = sheet1.getCTWorksheet().getColsArray(0); + assertEquals(0, cols.sizeOfColArray()); - sheet1.groupColumn( 4, 7 ); + sheet1.groupColumn(4, 7); - assertEquals(1, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true + assertEquals(1, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - sheet1.groupColumn( 9, 12 ); + sheet1.groupColumn(9, 12); - assertEquals(2, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 12); // false, true + assertEquals(2, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); // false, true + checkColumnGroup(cols.getColArray(1), 9, 12); // false, true - sheet1.groupColumn( 10, 11 ); + sheet1.groupColumn(10, 11); - assertEquals(4, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 9); // false, true - checkColumnGroup(cols.getColArray(2), 10, 11); // false, true - checkColumnGroup(cols.getColArray(3), 12, 12); // false, true + assertEquals(4, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); // false, true + checkColumnGroup(cols.getColArray(1), 9, 9); // false, true + checkColumnGroup(cols.getColArray(2), 10, 11); // false, true + checkColumnGroup(cols.getColArray(3), 12, 12); // false, true - // collapse columns - 1 - sheet1.setColumnGroupCollapsed( 5, true ); + // collapse columns - 1 + sheet1.setColumnGroupCollapsed(5, true); - // FIXME: we grew a column? - assertEquals(5, cols.sizeOfColArray()); - checkColumnGroupIsCollapsed(cols.getColArray(0), 4, 7); // true, true - checkColumnGroup(cols.getColArray(1), 8, 8); // false, true - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true + // FIXME: we grew a column? + assertEquals(5, cols.sizeOfColArray()); + checkColumnGroupIsCollapsed(cols.getColArray(0), 4, 7); // true, true + checkColumnGroup(cols.getColArray(1), 8, 8); // false, true + checkColumnGroup(cols.getColArray(2), 9, 9); // false, true + checkColumnGroup(cols.getColArray(3), 10, 11); // false, true + checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - // expand columns - 1 - sheet1.setColumnGroupCollapsed( 5, false ); - assertEquals(5, cols.sizeOfColArray()); + // expand columns - 1 + sheet1.setColumnGroupCollapsed(5, false); + assertEquals(5, cols.sizeOfColArray()); - checkColumnGroupIsExpanded(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true + checkColumnGroupIsExpanded(cols.getColArray(0), 4, 7); // false, true + checkColumnGroup(cols.getColArray(1), 8, 8, false, false); + checkColumnGroup(cols.getColArray(2), 9, 9); // false, true + checkColumnGroup(cols.getColArray(3), 10, 11); // false, true + checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - //collapse - 2 - sheet1.setColumnGroupCollapsed( 9, true ); - // it grew again? - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroupIsCollapsed(cols.getColArray(2), 9, 9); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(4), 12, 12); // true, true - // why was this column group added? - checkColumnGroup(cols.getColArray(5), 13, 13); // false, true + //collapse - 2 + sheet1.setColumnGroupCollapsed(9, true); + // it grew again? + assertEquals(6, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); // false, true + checkColumnGroup(cols.getColArray(1), 8, 8, false, false); + checkColumnGroupIsCollapsed(cols.getColArray(2), 9, 9); // true, true + checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true + checkColumnGroupIsCollapsed(cols.getColArray(4), 12, 12); // true, true + // why was this column group added? + checkColumnGroup(cols.getColArray(5), 13, 13); // false, true - //expand - 2 - sheet1.setColumnGroupCollapsed( 9, false ); - assertEquals(6, cols.sizeOfColArray()); + //expand - 2 + sheet1.setColumnGroupCollapsed(9, false); + assertEquals(6, cols.sizeOfColArray()); - //outline level 2: the line under ==> collapsed==True - assertEquals(2, cols.getColArray(3).getOutlineLevel()); - assertTrue(cols.getColArray(4).isSetCollapsed()); + //outline level 2: the line under ==> collapsed==True + assertEquals(2, cols.getColArray(3).getOutlineLevel()); + assertTrue(cols.getColArray(4).isSetCollapsed()); - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); + checkColumnGroup(cols.getColArray(0), 4, 7); + checkColumnGroup(cols.getColArray(1), 8, 8, false, false); + checkColumnGroup(cols.getColArray(2), 9, 9); // false, true + checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true + checkColumnGroup(cols.getColArray(4), 12, 12); // false, true + checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - //DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO - //collapse - 3 - sheet1.setColumnGroupCollapsed( 10, true ); - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); + //DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO + //collapse - 3 + sheet1.setColumnGroupCollapsed(10, true); + assertEquals(6, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); + checkColumnGroup(cols.getColArray(1), 8, 8, false, false); + checkColumnGroup(cols.getColArray(2), 9, 9); // false, true + checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true + checkColumnGroup(cols.getColArray(4), 12, 12); // false, true + checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - //expand - 3 - sheet1.setColumnGroupCollapsed( 10, false ); - assertEquals(6, cols.sizeOfColArray()); - assertFalse(cols.getColArray(0).getHidden()); - assertFalse(cols.getColArray(5).getHidden()); - assertFalse(cols.getColArray(4).isSetCollapsed()); + //expand - 3 + sheet1.setColumnGroupCollapsed(10, false); + assertEquals(6, cols.sizeOfColArray()); + assertFalse(cols.getColArray(0).getHidden()); + assertFalse(cols.getColArray(5).getHidden()); + assertFalse(cols.getColArray(4).isSetCollapsed()); -// write out and give back - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - // FIXME: forgot to reassign! - //cols = sheet1.getCTWorksheet().getColsArray(0); + // write out and give back + // Save and re-load + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet1 = wb2.getSheetAt(0); + // FIXME: forgot to reassign! + //cols = sheet1.getCTWorksheet().getColsArray(0); - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12, false, false); - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - wb2.close(); + assertEquals(6, cols.sizeOfColArray()); + checkColumnGroup(cols.getColArray(0), 4, 7); // false, true + checkColumnGroup(cols.getColArray(1), 8, 8, false, false); + checkColumnGroup(cols.getColArray(2), 9, 9); // false, true + checkColumnGroup(cols.getColArray(3), 10, 11); // false, true + checkColumnGroup(cols.getColArray(4), 12, 12, false, false); + checkColumnGroup(cols.getColArray(5), 13, 13, false, false); + } + } } /** @@ -570,10 +570,10 @@ public final class TestXSSFSheet extends BaseTestXSheet { int fromColumnIndex, int toColumnIndex, boolean isSetHidden, boolean isSetCollapsed ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertEquals("isSetHidden", isSetHidden, col.isSetHidden()); - assertEquals("isSetCollapsed", isSetCollapsed, col.isSetCollapsed()); //not necessarily set + assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based + assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based + assertEquals(isSetHidden, col.isSetHidden(), "isSetHidden"); + assertEquals(isSetCollapsed, col.isSetCollapsed(), "isSetCollapsed"); //not necessarily set } /** @@ -583,15 +583,13 @@ public final class TestXSSFSheet extends BaseTestXSheet { * @param fromColumnIndex 0-indexed * @param toColumnIndex 0-indexed */ - private static void checkColumnGroup( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertFalse("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); //not necessarily set + private static void checkColumnGroup(CTCol col, int fromColumnIndex, int toColumnIndex) { + assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based + assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based + assertFalse(col.isSetHidden(), "isSetHidden"); + assertTrue(col.isSetCollapsed(), "isSetCollapsed"); //not necessarily set } + /** * Verify that column groups were created correctly after Sheet.groupColumn * @@ -599,16 +597,14 @@ public final class TestXSSFSheet extends BaseTestXSheet { * @param fromColumnIndex 0-indexed * @param toColumnIndex 0-indexed */ - private static void checkColumnGroupIsCollapsed( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertTrue("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); - //assertTrue("getCollapsed", col.getCollapsed()); + private static void checkColumnGroupIsCollapsed(CTCol col, int fromColumnIndex, int toColumnIndex) { + assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based + assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based + assertTrue(col.isSetHidden(), "isSetHidden"); + assertTrue(col.isSetCollapsed(), "isSetCollapsed"); + //assertTrue(col.getCollapsed(), "getCollapsed"); } + /** * Verify that column groups were created correctly after Sheet.groupColumn * @@ -617,16 +613,13 @@ public final class TestXSSFSheet extends BaseTestXSheet { * @param toColumnIndex 0-indexed */ @SuppressWarnings("SameParameterValue") - private static void checkColumnGroupIsExpanded( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertFalse("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); - //assertTrue("isSetCollapsed", !col.isSetCollapsed() || !col.getCollapsed()); - //assertFalse("getCollapsed", col.getCollapsed()); + private static void checkColumnGroupIsExpanded(CTCol col, int fromColumnIndex, int toColumnIndex) { + assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based + assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based + assertFalse(col.isSetHidden(), "isSetHidden"); + assertTrue(col.isSetCollapsed(), "isSetCollapsed"); + //assertTrue(!col.isSetCollapsed() || !col.getCollapsed(), "isSetCollapsed"); + //assertFalse(col.getCollapsed(), "getCollapsed"); } /** @@ -1043,20 +1036,20 @@ public final class TestXSSFSheet extends BaseTestXSheet { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull("CTSheetProtection should be null by default", pr); + assertNull(pr, "CTSheetProtection should be null by default"); String password = "Test"; sheet.protectSheet(password); pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull("CTSheetProtection should be not null", pr); - assertTrue("sheet protection should be on", pr.isSetSheet()); - assertTrue("object protection should be on", pr.isSetObjects()); - assertTrue("scenario protection should be on", pr.isSetScenarios()); + assertNotNull(pr, "CTSheetProtection should be not null"); + assertTrue(pr.isSetSheet(), "sheet protection should be on"); + assertTrue(pr.isSetObjects(), "object protection should be on"); + assertTrue(pr.isSetScenarios(), "scenario protection should be on"); int hashVal = CryptoFunctions.createXorVerifier1(password); int actualVal = Integer.parseInt(pr.xgetPassword().getStringValue(),16); - assertEquals("well known value for top secret hash should match", hashVal, actualVal); + assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); sheet.protectSheet(null); - assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); + assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); wb.close(); } @@ -1066,21 +1059,21 @@ public final class TestXSSFSheet extends BaseTestXSheet { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull("CTSheetProtection should be null by default", pr); + assertNull(pr, "CTSheetProtection should be null by default"); String password = ""; sheet.protectSheet(password); pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull("CTSheetProtection should be not null", pr); - assertTrue("sheet protection should be on", pr.isSetSheet()); - assertTrue("object protection should be on", pr.isSetObjects()); - assertTrue("scenario protection should be on", pr.isSetScenarios()); + assertNotNull(pr, "CTSheetProtection should be not null"); + assertTrue(pr.isSetSheet(), "sheet protection should be on"); + assertTrue(pr.isSetObjects(), "object protection should be on"); + assertTrue(pr.isSetScenarios(), "scenario protection should be on"); int hashVal = CryptoFunctions.createXorVerifier1(password); STUnsignedShortHex xpassword = pr.xgetPassword(); int actualVal = Integer.parseInt(xpassword.getStringValue(),16); - assertEquals("well known value for top secret hash should match", hashVal, actualVal); + assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); sheet.protectSheet(null); - assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); + assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); wb.close(); } @@ -1113,8 +1106,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { XSSFRow row = sheet.getRow(0); sheet.removeRow(row); - assertEquals("XSSFSheet#removeRow did not clear calcChain entries", - 0, calcChain.getCTCalcChain().sizeOfCArray()); + assertEquals(0, calcChain.getCTCalcChain().sizeOfCArray(), "XSSFSheet#removeRow did not clear calcChain entries"); //calcChain should be gone XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); @@ -1208,7 +1200,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { for (int si = 0; si < wb.getNumberOfSheets(); si++) { Sheet sh = wb.getSheetAt(si); assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow()); + assertEquals(topRows[si], sh.getTopRow(), "Did not match for sheet " + si); } // for XSSF also test with SXSSF @@ -1217,7 +1209,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { for (int si = 0; si < swb.getNumberOfSheets(); si++) { Sheet sh = swb.getSheetAt(si); assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow()); + assertEquals(topRows[si], sh.getTopRow(), "Did not match for sheet " + si); } swb.close(); } @@ -1233,7 +1225,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { for (int si = 0; si < wb.getNumberOfSheets(); si++) { Sheet sh = wb.getSheetAt(si); assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol()); + assertEquals(topRows[si], sh.getLeftCol(), "Did not match for sheet " + si); } // for XSSF also test with SXSSF @@ -1242,7 +1234,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { for (int si = 0; si < swb.getNumberOfSheets(); si++) { Sheet sh = swb.getSheetAt(si); assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol()); + assertEquals(topRows[si], sh.getLeftCol(), "Did not match for sheet " + si); } swb.close(); } @@ -1252,22 +1244,12 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Test public void bug55745() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55745.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - List tables = sheet.getTables(); - /*System.out.println(tables.size()); - - for(XSSFTable table : tables) { - System.out.println("XPath: " + table.getCommonXpath()); - System.out.println("Name: " + table.getName()); - System.out.println("Mapped Cols: " + table.getNumberOfMappedColumns()); - System.out.println("Rowcount: " + table.getRowCount()); - System.out.println("End Cell: " + table.getEndCellReference()); - System.out.println("Start Cell: " + table.getStartCellReference()); - }*/ - assertEquals("Sheet should contain 8 tables", 8, tables.size()); - assertNotNull("Sheet should contain a comments table", sheet.getCommentsTable(false)); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55745.xlsx")) { + XSSFSheet sheet = wb.getSheetAt(0); + List tables = sheet.getTables(); + assertEquals(8, tables.size(), "Sheet should contain 8 tables"); + assertNotNull(sheet.getCommentsTable(false), "Sheet should contain a comments table"); + } } @Test @@ -1299,7 +1281,8 @@ public final class TestXSSFSheet extends BaseTestXSheet { wb.close(); } - @Test(timeout=180000) + @Timeout(value = 180, unit = SECONDS) + @Test public void bug51585() throws IOException { XSSFTestDataSamples.openSampleWorkbook("51585.xlsx").close(); } @@ -1409,29 +1392,25 @@ public final class TestXSSFSheet extends BaseTestXSheet { wb.close(); } - @Test(expected=IllegalArgumentException.class) + @Test public void testCreatePivotTableWithConflictingDataSheets() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet("TEST"); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet = wb.getSheetAt(0); + XSSFSheet sheet2 = wb.createSheet("TEST"); + CellReference cr = new CellReference("H5"); + AreaReference ar = wb.getCreationHelper().createAreaReference(sheet.getSheetName() + "!A$1:B$2"); - sheet2.createPivotTable( - wb.getCreationHelper().createAreaReference(sheet.getSheetName()+"!A$1:B$2"), - new CellReference("H5"), - sheet2); - wb.close(); + assertThrows(IllegalArgumentException.class, () -> sheet2.createPivotTable(ar, cr, sheet2)); + } } - @Test(expected=POIXMLException.class) + @Test public void testReadFails() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); - // Throws exception because we cannot read here - try { - sheet.onDocumentRead(); - } finally { - wb.close(); + // Throws exception because we cannot read here + assertThrows(POIXMLException.class, sheet::onDocumentRead); } } @@ -1451,7 +1430,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { wb.close(); } - protected void testCopyOneRow(String copyRowsTestWorkbook) throws IOException { + private void testCopyOneRow(String copyRowsTestWorkbook) throws IOException { final double FLOAT_PRECISION = 1e-9; final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); final XSSFSheet sheet = wb.getSheetAt(0); @@ -1468,98 +1447,91 @@ public final class TestXSSFSheet extends BaseTestXSheet { // Style cell = CellUtil.getCell(destRow, col++); - assertEquals("[Style] B7 cell value", "Red", cell.getStringCellValue()); - assertEquals("[Style] B7 cell style", CellUtil.getCell(srcRow, 1).getCellStyle(), cell.getCellStyle()); + assertEquals("Red", cell.getStringCellValue(), "[Style] B7 cell value"); + assertEquals(CellUtil.getCell(srcRow, 1).getCellStyle(), cell.getCellStyle(), "[Style] B7 cell style"); // Blank cell = CellUtil.getCell(destRow, col++); - assertEquals("[Blank] C7 cell type", CellType.BLANK, cell.getCellType()); + assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C7 cell type"); // Error cell = CellUtil.getCell(destRow, col++); - assertEquals("[Error] D7 cell type", CellType.ERROR, cell.getCellType()); + assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D7 cell type"); final FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D7 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + assertEquals(FormulaError.NA, error, "[Error] D7 cell value"); // Date cell = CellUtil.getCell(destRow, col++); - assertEquals("[Date] E7 cell type", CellType.NUMERIC, cell.getCellType()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E7 cell type"); final Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals("[Date] E7 cell value", date, cell.getDateCellValue()); + assertEquals(date, cell.getDateCellValue(), "[Date] E7 cell value"); // Boolean cell = CellUtil.getCell(destRow, col++); - assertEquals("[Boolean] F7 cell type", CellType.BOOLEAN, cell.getCellType()); - assertTrue("[Boolean] F7 cell value", cell.getBooleanCellValue()); + assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F7 cell type"); + assertTrue(cell.getBooleanCellValue(), "[Boolean] F7 cell value"); // String cell = CellUtil.getCell(destRow, col++); - assertEquals("[String] G7 cell type", CellType.STRING, cell.getCellType()); - assertEquals("[String] G7 cell value", "Hello", cell.getStringCellValue()); + assertEquals(CellType.STRING, cell.getCellType(), "[String] G7 cell type"); + assertEquals("Hello", cell.getStringCellValue(), "[String] G7 cell value"); // Int cell = CellUtil.getCell(destRow, col++); - assertEquals("[Int] H7 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Int] H7 cell value", 15, (int) cell.getNumericCellValue()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H7 cell type"); + assertEquals(15, (int) cell.getNumericCellValue(), "[Int] H7 cell value"); // Float cell = CellUtil.getCell(destRow, col++); - assertEquals("[Float] I7 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Float] I7 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I7 cell type"); + assertEquals(12.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I7 cell value"); // Cell Formula cell = CellUtil.getCell(destRow, col++); assertEquals("Sheet1!J7", new CellReference(cell).formatAsString()); - assertEquals("[Cell Formula] J7 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula] J7 cell formula", "5+2", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J7 cell type"); + assertEquals("5+2", cell.getCellFormula(), "[Cell Formula] J7 cell formula"); //System.out.println("Cell formula evaluation currently unsupported"); // Cell Formula with Reference // Formula row references should be adjusted by destRowNum-srcRowNum cell = CellUtil.getCell(destRow, col++); assertEquals("Sheet1!K7", new CellReference(cell).formatAsString()); - assertEquals("[Cell Formula with Reference] K7 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference] K7 cell formula", - "J7+H$2", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K7 cell type"); + assertEquals("J7+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K7 cell formula"); // Cell Formula with Reference spanning multiple rows cell = CellUtil.getCell(destRow, col++); - assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell formula", - "G7&\" \"&G8", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L7 cell type"); + assertEquals("G7&\" \"&G8", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L7 cell formula"); // Cell Formula with Reference spanning multiple rows cell = CellUtil.getCell(destRow, col++); - assertEquals("[Cell Formula with Area Reference] M7 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Area Reference] M7 cell formula", - "SUM(H7:I8)", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M7 cell type"); + assertEquals("SUM(H7:I8)", cell.getCellFormula(), "[Cell Formula with Area Reference] M7 cell formula"); // Array Formula cell = CellUtil.getCell(destRow, col++); //System.out.println("Array formulas currently unsupported"); // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() /* - assertEquals("[Array Formula] N7 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Array Formula] N7 cell formula", "{SUM(H7:J7*{1,2,3})}", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N7 cell type"); + assertEquals("{SUM(H7:J7*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N7 cell formula"); */ // Data Format cell = CellUtil.getCell(destRow, col++); - assertEquals("[Data Format] O7 cell type;", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Data Format] O7 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Data Format] O7 cell type"); + assertEquals(100.20, cell.getNumericCellValue(), FLOAT_PRECISION, "[Data Format] O7 cell value"); //FIXME: currently fails final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals("[Data Format] O7 data format", moneyFormat, cell.getCellStyle().getDataFormatString()); + assertEquals(moneyFormat, cell.getCellStyle().getDataFormatString(), "[Data Format] O7 data format"); // Merged cell = CellUtil.getCell(destRow, col); - assertEquals("[Merged] P7:Q7 cell value", - "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P7:Q7 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7"))); + assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P7:Q7 cell value"); + assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7")), "[Merged] P7:Q7 merged region"); // Merged across multiple rows // Microsoft Excel 2013 does not copy a merged region unless all rows of @@ -1574,12 +1546,11 @@ public final class TestXSSFSheet extends BaseTestXSheet { //assertFalse("[Merged across multiple rows] R7:S8 merged region", // sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); // As currently implemented, cell value is copied but merged region is not copied - assertEquals("[Merged across multiple rows] R7:S8 cell value", - "Merged cells across multiple rows", cell.getStringCellValue()); - assertFalse("[Merged across multiple rows] R7:S7 merged region (one row)", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7"))); //shouldn't do 1-row merge - assertFalse("[Merged across multiple rows] R7:S8 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); //shouldn't do 2-row merge + assertEquals("Merged cells across multiple rows", cell.getStringCellValue(), "[Merged across multiple rows] R7:S8 cell value"); + // shouldn't do 1-row merge + assertFalse(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7")), "[Merged across multiple rows] R7:S7 merged region (one row)"); + //shouldn't do 2-row merge + assertFalse(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8")), "[Merged across multiple rows] R7:S8 merged region"); // Make sure other rows are blank (off-by-one errors) assertNull(sheet.getRow(5)); @@ -1588,7 +1559,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { wb.close(); } - protected void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException { + private void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException { final double FLOAT_PRECISION = 1e-9; final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); final XSSFSheet sheet = wb.getSheetAt(0); @@ -1616,135 +1587,128 @@ public final class TestXSSFSheet extends BaseTestXSheet { // Style col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Style] B10 cell value", "Red", cell.getStringCellValue()); - assertEquals("[Style] B10 cell style", CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle()); + assertEquals("Red", cell.getStringCellValue(), "[Style] B10 cell value"); + assertEquals(CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle(), "[Style] B10 cell style"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Style] B11 cell value", "Blue", cell.getStringCellValue()); - assertEquals("[Style] B11 cell style", CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle()); + assertEquals("Blue", cell.getStringCellValue(), "[Style] B11 cell value"); + assertEquals(CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle(), "[Style] B11 cell style"); // Blank col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Blank] C10 cell type", CellType.BLANK, cell.getCellType()); + assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C10 cell type"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Blank] C11 cell type", CellType.BLANK, cell.getCellType()); + assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C11 cell type"); // Error col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Error] D10 cell type", CellType.ERROR, cell.getCellType()); FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D10 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D10 cell type"); + assertEquals(FormulaError.NA, error, "[Error] D10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Error] D11 cell type", CellType.ERROR, cell.getCellType()); error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D11 cell value", FormulaError.NAME, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here + assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D11 cell type"); + assertEquals(FormulaError.NAME, error, "[Error] D11 cell value"); // Date col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Date] E10 cell type", CellType.NUMERIC, cell.getCellType()); Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals("[Date] E10 cell value", date, cell.getDateCellValue()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E10 cell type"); + assertEquals(date, cell.getDateCellValue(), "[Date] E10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Date] E11 cell type", CellType.NUMERIC, cell.getCellType()); date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime(); - assertEquals("[Date] E11 cell value", date, cell.getDateCellValue()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E11 cell type"); + assertEquals(date, cell.getDateCellValue(), "[Date] E11 cell value"); // Boolean col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Boolean] F10 cell type", CellType.BOOLEAN, cell.getCellType()); - assertTrue("[Boolean] F10 cell value", cell.getBooleanCellValue()); + assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F10 cell type"); + assertTrue(cell.getBooleanCellValue(), "[Boolean] F10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Boolean] F11 cell type", CellType.BOOLEAN, cell.getCellType()); - assertFalse("[Boolean] F11 cell value", cell.getBooleanCellValue()); + assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F11 cell type"); + assertFalse(cell.getBooleanCellValue(), "[Boolean] F11 cell value"); // String col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[String] G10 cell type", CellType.STRING, cell.getCellType()); - assertEquals("[String] G10 cell value", "Hello", cell.getStringCellValue()); + assertEquals(CellType.STRING, cell.getCellType(), "[String] G10 cell type"); + assertEquals("Hello", cell.getStringCellValue(), "[String] G10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[String] G11 cell type", CellType.STRING, cell.getCellType()); - assertEquals("[String] G11 cell value", "World", cell.getStringCellValue()); + assertEquals(CellType.STRING, cell.getCellType(), "[String] G11 cell type"); + assertEquals("World", cell.getStringCellValue(), "[String] G11 cell value"); // Int col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Int] H10 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Int] H10 cell value", 15, (int) cell.getNumericCellValue()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H10 cell type"); + assertEquals(15, (int) cell.getNumericCellValue(), "[Int] H10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Int] H11 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Int] H11 cell value", 42, (int) cell.getNumericCellValue()); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H11 cell type"); + assertEquals(42, (int) cell.getNumericCellValue(), "[Int] H11 cell value"); // Float col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Float] I10 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Float] I10 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I10 cell type"); + assertEquals(12.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I10 cell value"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Float] I11 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Float] I11 cell value", 5.5, cell.getNumericCellValue(), FLOAT_PRECISION); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I11 cell type"); + assertEquals(5.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I11 cell value"); // Cell Formula col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula] J10 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula] J10 cell formula", "5+2", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J10 cell type"); + assertEquals("5+2", cell.getCellFormula(), "[Cell Formula] J10 cell formula"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula] J11 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula] J11 cell formula", "6+18", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J11 cell type"); + assertEquals("6+18", cell.getCellFormula(), "[Cell Formula] J11 cell formula"); // Cell Formula with Reference col++; // Formula row references should be adjusted by destRowNum-srcRowNum cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Reference] K10 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference] K10 cell formula", - "J10+H$2", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K10 cell type"); + assertEquals("J10+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K10 cell formula"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Reference] K11 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference] K11 cell formula", "J11+H$2", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K11 cell type"); + assertEquals("J11+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K11 cell formula"); // Cell Formula with Reference spanning multiple rows col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell formula", - "G10&\" \"&G11", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L10 cell type"); + assertEquals("G10&\" \"&G11", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L10 cell formula"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell formula", - "G11&\" \"&G12", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L11 cell type"); + assertEquals("G11&\" \"&G12", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L11 cell formula"); // Cell Formula with Area Reference col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Area Reference] M10 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Area Reference] M10 cell formula", - "SUM(H10:I11)", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M10 cell type"); + assertEquals("SUM(H10:I11)", cell.getCellFormula(), "[Cell Formula with Area Reference] M10 cell formula"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Area Reference] M11 cell type", - CellType.FORMULA, cell.getCellType()); - assertEquals("[Cell Formula with Area Reference] M11 cell formula", - "SUM($H$3:I10)", cell.getCellFormula()); //Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order + // Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order + assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M11 cell type"); + assertEquals("SUM($H$3:I10)", cell.getCellFormula(), "[Cell Formula with Area Reference] M11 cell formula"); // Array Formula col++; @@ -1752,35 +1716,32 @@ public final class TestXSSFSheet extends BaseTestXSheet { // System.out.println("Array formulas currently unsupported"); /* // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals("[Array Formula] N10 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Array Formula] N10 cell formula", "{SUM(H10:J10*{1,2,3})}", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N10 cell type"); + assertEquals("{SUM(H10:J10*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N10 cell formula"); cell = CellUtil.getCell(destRow2, col); // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals("[Array Formula] N11 cell type", CellType.FORMULA, cell.getCellType()); - assertEquals("[Array Formula] N11 cell formula", "{SUM(H11:J11*{1,2,3})}", cell.getCellFormula()); + assertEquals(CellType.FORMULA, cell.getCellType(). "[Array Formula] N11 cell type"); + assertEquals("{SUM(H11:J11*{1,2,3})}", cell.getCellFormula(). "[Array Formula] N11 cell formula"); */ // Data Format col++; cell = CellUtil.getCell(destRow2, col); - assertEquals("[Data Format] O10 cell type", CellType.NUMERIC, cell.getCellType()); - assertEquals("[Data Format] O10 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION); + assertEquals(CellType.NUMERIC, cell.getCellType(), "[Data Format] O10 cell type"); + assertEquals(100.20, cell.getNumericCellValue(), FLOAT_PRECISION, "[Data Format] O10 cell value"); final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals("[Data Format] O10 cell data format", moneyFormat, cell.getCellStyle().getDataFormatString()); + assertEquals(moneyFormat, cell.getCellStyle().getDataFormatString(), "[Data Format] O10 cell data format"); // Merged col++; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Merged] P10:Q10 cell value", - "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P10:Q10 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10"))); + assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P10:Q10 cell value"); + assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10")), "[Merged] P10:Q10 merged region"); cell = CellUtil.getCell(destRow2, col); - assertEquals("[Merged] P11:Q11 cell value", "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P11:Q11 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11"))); + assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P11:Q11 cell value"); + assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11")), "[Merged] P11:Q11 merged region"); // Should Q10/Q11 be checked? @@ -1790,19 +1751,17 @@ public final class TestXSSFSheet extends BaseTestXSheet { // POI's behavior should match this behavior col += 2; cell = CellUtil.getCell(destRow1, col); - assertEquals("[Merged across multiple rows] R10:S11 cell value", - "Merged cells across multiple rows", cell.getStringCellValue()); - assertTrue("[Merged across multiple rows] R10:S11 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11"))); + assertEquals("Merged cells across multiple rows", cell.getStringCellValue(), "[Merged across multiple rows] R10:S11 cell value"); + assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11")), "[Merged across multiple rows] R10:S11 merged region"); // Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too. if (srcRow3 == null) { - assertNull("Row 3 was empty, so Row 11 should be empty", destRow3); + assertNull(destRow3, "Row 3 was empty, so Row 11 should be empty"); } // Make sure other rows are blank (off-by-one errors) - assertNull("Off-by-one lower edge case", sheet.getRow(7)); //one row above destHeaderRow - assertNull("Off-by-one upper edge case", sheet.getRow(12)); //one row below destRow3 + assertNull(sheet.getRow(7), "Off-by-one lower edge case"); //one row above destHeaderRow + assertNull(sheet.getRow(12), "Off-by-one upper edge case"); //one row below destRow3 wb.close(); } @@ -1956,16 +1915,16 @@ public final class TestXSSFSheet extends BaseTestXSheet { for (int i = 0; i < 2; i++) { ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(0); - anchor.setRow1(0 + i); + anchor.setRow1(i); anchor.setCol2(2); anchor.setRow2(3 + i); Comment comment = drawing.createCellComment(anchor); comment.setString(helper.createRichTextString("BugTesting")); - Row row = sheet.getRow(0 + i); + Row row = sheet.getRow(i); if (row == null) { - row = sheet.createRow(0 + i); + row = sheet.createRow(i); } Cell cell = row.getCell(0); if (cell == null) { @@ -1980,20 +1939,19 @@ public final class TestXSSFSheet extends BaseTestXSheet { // bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments @Test public void testRemoveRowWithCommentAndGapAbove() throws IOException { - final Workbook wb = _testDataProvider.openSampleWorkbook("59687.xlsx"); - final Sheet sheet = wb.getSheetAt(0); + try (Workbook wb = _testDataProvider.openSampleWorkbook("59687.xlsx")) { + final Sheet sheet = wb.getSheetAt(0); - // comment exists - CellAddress commentCellAddress = new CellAddress("A4"); - assertNotNull(sheet.getCellComment(commentCellAddress)); + // comment exists + CellAddress commentCellAddress = new CellAddress("A4"); + assertNotNull(sheet.getCellComment(commentCellAddress)); - assertEquals("Wrong starting # of comments", 1, sheet.getCellComments().size()); + assertEquals(1, sheet.getCellComments().size(), "Wrong starting # of comments"); - sheet.removeRow(sheet.getRow(commentCellAddress.getRow())); + sheet.removeRow(sheet.getRow(commentCellAddress.getRow())); - assertEquals("There should not be any comments left!", 0, sheet.getCellComments().size()); - - wb.close(); + assertEquals(0, sheet.getCellComments().size(), "There should not be any comments left!"); + } } @Test @@ -2037,7 +1995,7 @@ public final class TestXSSFSheet extends BaseTestXSheet { // on sheet-level, the flag is still set for (Sheet s : wb) { - assertTrue("Sheet-level flag is still set to true", s.getForceFormulaRecalculation()); + assertTrue(s.getForceFormulaRecalculation(), "Sheet-level flag is still set to true"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java index 4f2779d97b..bc1be64b1f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.List; @@ -25,7 +25,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFSheetMergeRegions { @@ -54,8 +54,8 @@ public class TestXSSFSheetMergeRegions { // This time is typically ~800ms, versus ~7800ms to iterate getMergedRegion(int). // when running in Gump, the VM is very slow, so we should allow much more time - assertTrue("Should have taken <2000 ms to iterate 50k merged regions but took " + millis, - inGump ? millis < 8000 : millis < 2000); + assertTrue(inGump ? millis < 8000 : millis < 2000, + "Should have taken <2000 ms to iterate 50k merged regions but took " + millis); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java index bcdfb3d5e8..7901432648 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java @@ -17,8 +17,8 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -27,7 +27,7 @@ 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.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFSheetRowGrouping { @@ -310,20 +310,20 @@ public final class TestXSSFSheetRowGrouping { assertEquals(collapsed.length, hidden.length); assertEquals(collapsed.length, outlineLevel.length); - assertEquals("Expected " + collapsed.length + " rows with collapsed state, but had " + (sheet.getLastRowNum()-sheet.getFirstRowNum()+1) + " rows (" - + sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")", - collapsed.length, sheet.getLastRowNum()-sheet.getFirstRowNum()+1); + assertEquals(collapsed.length, sheet.getLastRowNum()-sheet.getFirstRowNum()+1, + "Expected " + collapsed.length + " rows with collapsed state, but had " + (sheet.getLastRowNum()-sheet.getFirstRowNum()+1) + " rows (" + + sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")"); for(int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum();i++) { if(collapsed[i-sheet.getFirstRowNum()] == null) { continue; } XSSFRow row = (XSSFRow) sheet.getRow(i); - assertNotNull("Could not read row " + i, row); - assertNotNull("Could not read row " + i, row.getCTRow()); - assertEquals("Row: " + i + ": collapsed", collapsed[i - sheet.getFirstRowNum()], row.getCTRow().getCollapsed()); - assertEquals("Row: " + i + ": hidden", hidden[i-sheet.getFirstRowNum()], row.getCTRow().getHidden()); + assertNotNull(row, "Could not read row " + i); + assertNotNull(row.getCTRow(), "Could not read row " + i); + assertEquals(collapsed[i - sheet.getFirstRowNum()], row.getCTRow().getCollapsed(), "Row: " + i + ": collapsed"); + assertEquals(hidden[i-sheet.getFirstRowNum()], row.getCTRow().getHidden(), "Row: " + i + ": hidden"); - assertEquals("Row: " + i + ": level", outlineLevel[i-sheet.getFirstRowNum()], row.getCTRow().getOutlineLevel()); + assertEquals(outlineLevel[i-sheet.getFirstRowNum()], row.getCTRow().getOutlineLevel(), "Row: " + i + ": level"); } writeToFile(wb); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java index f8e76cfc17..c9674ed4da 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java @@ -23,11 +23,11 @@ import org.apache.poi.ss.util.CellUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { @@ -61,34 +61,34 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { /** negative row shift causes corrupted data or throws exception */ @Test public void testBug53798() throws IOException { - // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected + // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); Sheet testSheet = wb.getSheetAt(0); - // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about + // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about // when shifted by less than -1 negative amount (try -2) testSheet.shiftRows(3, 3, -2); - + // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted - // xlsx file with unreadable data in the negative shifted row. + // xlsx file with unreadable data in the negative shifted row. // NOTE it's ok to create any other row. Row newRow = testSheet.createRow(3); Cell newCell = newRow.createCell(0); newCell.setCellValue("new Cell in row "+newRow.getRowNum()); - - // 3) once a negative shift has been made any attempt to shift another group of rows - // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: + + // 3) once a negative shift has been made any attempt to shift another group of rows + // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. - // NOTE: another negative shift on another group of rows is successful, provided no new rows in + // NOTE: another negative shift on another group of rows is successful, provided no new rows in // place of previously shifted rows were attempted to be created as explained above. // -- CHANGE the shift to positive once the behaviour of the above has been tested - testSheet.shiftRows(6, 7, 1); - + testSheet.shiftRows(6, 7, 1); + Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); wb.close(); assertNotNull(read); - + Sheet readSheet = read.getSheetAt(0); verifyCellContent(readSheet, 0, "0.0"); verifyCellContent(readSheet, 1, "3.0"); @@ -115,7 +115,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertEquals(expect, readCell.getStringCellValue()); } } - + /** negative row shift causes corrupted data or throws exception */ @Test public void testBug53798a() throws IOException { @@ -127,11 +127,11 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { r.getRowNum(); } testSheet.shiftRows(6, 6, 1); - + Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); wb.close(); assertNotNull(read); - + Sheet readSheet = read.getSheetAt(0); verifyCellContent(readSheet, 0, "0.0"); verifyCellContent(readSheet, 1, "1.0"); @@ -144,7 +144,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { verifyCellContent(readSheet, 8, "8.0"); read.close(); } - + /** Shifting rows with comment result - Unreadable content error and comment deletion */ @Test public void testBug56017() throws IOException { @@ -156,19 +156,19 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertNotNull(comment); assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - + sheet.shiftRows(0, 1, 1); // comment in row 0 is gone comment = sheet.getCellComment(new CellAddress(0, 0)); assertNull(comment); - + // comment is now in row 1 comment = sheet.getCellComment(new CellAddress(1, 0)); assertNotNull(comment); assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - + Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); wb.close(); assertNotNull(wbBack); @@ -219,14 +219,14 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { @Test public void testSetSheetOrderAndAdjustActiveSheet() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - + assertEquals(5, wb.getActiveSheetIndex()); // move the sheets around in all possible combinations to check that the active sheet // is set correctly in all cases wb.setSheetOrder(wb.getSheetName(5), 4); assertEquals(4, wb.getActiveSheetIndex()); - + wb.setSheetOrder(wb.getSheetName(5), 5); assertEquals(4, wb.getActiveSheetIndex()); @@ -262,22 +262,22 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { wb.setSheetOrder(wb.getSheetName(0), 5); assertEquals(5, wb.getActiveSheetIndex()); - + wb.close(); - } + } @Test public void testRemoveSheetAndAdjustActiveSheet() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - + assertEquals(5, wb.getActiveSheetIndex()); - + wb.removeSheetAt(0); assertEquals(4, wb.getActiveSheetIndex()); - + wb.setActiveSheet(3); assertEquals(3, wb.getActiveSheetIndex()); - + wb.removeSheetAt(4); assertEquals(3, wb.getActiveSheetIndex()); @@ -292,21 +292,16 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { wb.removeSheetAt(0); assertEquals(0, wb.getActiveSheetIndex()); - - try { - wb.removeSheetAt(0); - fail("Should catch exception as no more sheets are there"); - } catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> wb.removeSheetAt(0), + "Should catch exception as no more sheets are there"); assertEquals(0, wb.getActiveSheetIndex()); - + wb.createSheet(); assertEquals(0, wb.getActiveSheetIndex()); - + wb.removeSheetAt(0); assertEquals(0, wb.getActiveSheetIndex()); - + wb.close(); } @@ -341,32 +336,31 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { /** Shifting rows with cell comments only shifts comments from first such cell. Other cell comments not shifted */ @Test public void testBug57828_OnlyOneCommentShiftedInRow() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx")) { + XSSFSheet sheet = wb.getSheetAt(0); - Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNotNull(comment1); + Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); + assertNotNull(comment1); - Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNotNull(comment2); + Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); + assertNotNull(comment2); - Comment comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNull("NO comment in (1,1) and it should be null", comment3); + Comment comment3 = sheet.getCellComment(new CellAddress(1, 1)); + assertNull(comment3, "NO comment in (1,1) and it should be null"); - sheet.shiftRows(2, 2, -1); + sheet.shiftRows(2, 2, -1); - comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNotNull("Comment in (2,1) moved to (1,1) so its not null now.", comment3); + comment3 = sheet.getCellComment(new CellAddress(1, 1)); + assertNotNull(comment3, "Comment in (2,1) moved to (1,1) so its not null now."); - comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNull("No comment currently in (2,1) and hence it is null", comment1); + comment1 = sheet.getCellComment(new CellAddress(2, 1)); + assertNull(comment1, "No comment currently in (2,1) and hence it is null"); - comment2 = sheet.getCellComment(new CellAddress(1, 2)); - assertNotNull("Comment in (2,2) should have moved as well because of shift rows. But its not", comment2); - - wb.close(); + comment2 = sheet.getCellComment(new CellAddress(1, 2)); + assertNotNull(comment2, "Comment in (2,2) should have moved as well because of shift rows. But its not"); + } } - + @Test public void bug59733() throws IOException { Workbook workbook = new XSSFWorkbook(); @@ -377,7 +371,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { // Shift the 2nd row on top of the 0th row sheet.shiftRows(2, 2, -2); - + sheet.removeRow(sheet.getRow(0)); assertEquals(1, sheet.getRow(1).getRowNum()); @@ -443,7 +437,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E6")); wb.close(); } - + // bug 60260: shift rows or rename a sheet containing a named range // that refers to formula with a unicode (non-ASCII) sheet name formula @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java index 1041b94fa8..dda5d61197 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java @@ -17,8 +17,8 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -29,9 +29,9 @@ import java.util.Locale; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; public class TestXSSFSheetShiftRowsAndColumns { @@ -52,15 +52,14 @@ public class TestXSSFSheetShiftRowsAndColumns { private String fileName = null; public TestXSSFSheetShiftRowsAndColumns() { - assertTrue("Failed to create directory " + resultDir, - resultDir.exists() || resultDir.mkdirs()); + assertTrue(resultDir.exists() || resultDir.mkdirs(), "Failed to create directory " + resultDir); } /** * This creates a workbook with one worksheet. It then puts data in rows 0 to numRows-1 and colulmns * 0 to numCols-1. */ - @Before + @BeforeEach public void setup() throws IOException { final String procName = "TestXSSFSheetShiftRowsAndColumns.setup"; fileName = procName+".xlsx"; @@ -88,7 +87,7 @@ public class TestXSSFSheetShiftRowsAndColumns { /** * This method writes the workbook to resultDir/fileName. */ - @After + @AfterEach public void cleanup() throws IOException { final String procName = "TestXSSFSheetRemoveTable.cleanup"; if (workbook == null) { @@ -184,8 +183,8 @@ public class TestXSSFSheetShiftRowsAndColumns { final Object cellAddress = cell.getAddress().formatAsString(); final Object r = ctCell.getR(); - assertEquals(String.format(Locale.US, "%s: Testing cell.getAddress",procName),address,cellAddress); - assertEquals(String.format(Locale.US, "%s: Testing ctCell.getR",procName),address,r); + assertEquals(address,cellAddress,String.format(Locale.US, "%s: Testing cell.getAddress",procName)); + assertEquals(address,r,String.format(Locale.US, "%s: Testing ctCell.getR",procName)); } } @@ -196,9 +195,8 @@ public class TestXSSFSheetShiftRowsAndColumns { */ private void testMergeRegion(String procName,int nRowsToShift,int nColsToShift) { final CellRangeAddress range = sheet.getMergedRegion(0); - assertEquals(String.format(Locale.US, "%s: Testing merge area %s", procName, range), - new CellRangeAddress(FIRST_MERGE_ROW + nRowsToShift, LAST_MERGE_ROW + nRowsToShift, - FIRST_MERGE_COL + nColsToShift, LAST_MERGE_COL + nColsToShift), - range); + assertEquals(new CellRangeAddress(FIRST_MERGE_ROW + nRowsToShift, LAST_MERGE_ROW + nRowsToShift, + FIRST_MERGE_COL + nColsToShift, LAST_MERGE_COL + nColsToShift), range, + String.format(Locale.US, "%s: Testing merge area %s", procName, range)); } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java index 99ebd95c0e..fbeae1ab37 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +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.io.IOException; @@ -29,7 +29,7 @@ import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas; import org.apache.poi.ss.usermodel.CellRange; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; @@ -100,7 +100,7 @@ public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateA confirmArrayFormulaCell(c, cellRef, null, null); } private static void confirmArrayFormulaCell(XSSFCell c, String cellRef, String formulaText, String arrayRangeRef) { - assertNotNull("Cell should not be null.", c); + assertNotNull(c, "Cell should not be null."); CTCell ctCell = c.getCTCell(); assertEquals(cellRef, ctCell.getR()); if (formulaText == null) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java index 5387b1a7da..5347f584c7 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.io.IOException; @@ -33,7 +33,7 @@ import org.apache.poi.xddf.usermodel.text.XDDFNormalAutoFit; import org.apache.poi.xddf.usermodel.text.XDDFShapeAutoFit; import org.apache.poi.xddf.usermodel.text.XDDFTextBody; import org.apache.poi.xddf.usermodel.text.XDDFTextParagraph; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFSimpleShape { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java index 45f08f8f0f..135250358e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java @@ -25,7 +25,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo; @@ -38,10 +38,11 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; public final class TestXSSFTable { @@ -72,11 +73,11 @@ public final class TestXSSFTable { CTTable ctTable = wb2.getSheetAt(0).getTables().get(0).getCTTable(); CTTableColumn[] ctTableColumnArray = ctTable.getTableColumns().getTableColumnArray(); - assertEquals("number of headers in xml table should match number of header cells in worksheet", - headers.size(), ctTableColumnArray.length); + assertEquals(headers.size(), ctTableColumnArray.length, + "number of headers in xml table should match number of header cells in worksheet"); for (int i = 0; i < headers.size(); i++) { - assertEquals("header name in xml table should match number of header cells in worksheet", - headers.get(i), ctTableColumnArray[i].getName()); + assertEquals(headers.get(i), ctTableColumnArray[i].getName(), + "header name in xml table should match number of header cells in worksheet"); } assertTrue(outputFile.delete()); wb2.close(); @@ -101,17 +102,15 @@ public final class TestXSSFTable { XSSFWorkbook inputWorkbook = XSSFTestDataSamples.writeOutAndReadBack(outputWorkbook); List tables = inputWorkbook.getSheetAt(0).getTables(); - assertEquals("Tables number", 1, tables.size()); + assertEquals(1, tables.size(), "Tables number"); XSSFTable inputTable = tables.get(0); - assertEquals("Table display name", outputTable.getDisplayName(), inputTable.getDisplayName()); + assertEquals(outputTable.getDisplayName(), inputTable.getDisplayName(), "Table display name"); CTTableStyleInfo inputStyleInfo = inputTable.getCTTable().getTableStyleInfo(); - assertEquals("Style name", outputStyleInfo.getName(), inputStyleInfo.getName()); - assertEquals("Show column stripes", - outputStyleInfo.getShowColumnStripes(), inputStyleInfo.getShowColumnStripes()); - assertEquals("Show row stripes", - outputStyleInfo.getShowRowStripes(), inputStyleInfo.getShowRowStripes()); + assertEquals(outputStyleInfo.getName(), inputStyleInfo.getName(), "Style name"); + assertEquals(outputStyleInfo.getShowColumnStripes(), inputStyleInfo.getShowColumnStripes(), "Show column stripes"); + assertEquals(outputStyleInfo.getShowRowStripes(), inputStyleInfo.getShowRowStripes(), "Show row stripes"); inputWorkbook.close(); outputWorkbook.close(); @@ -123,12 +122,11 @@ public final class TestXSSFTable { XSSFTable table = wb.getTable("\\_Prime.1"); assertNotNull(table); - assertEquals("column header has special escaped characters", - 0, table.findColumnIndex("calc='#*'#")); + assertEquals(0, table.findColumnIndex("calc='#*'#"), "column header has special escaped characters"); assertEquals(1, table.findColumnIndex("Name")); assertEquals(2, table.findColumnIndex("Number")); - assertEquals("case insensitive", 2, table.findColumnIndex("NuMbEr")); + assertEquals(2, table.findColumnIndex("NuMbEr"), "case insensitive"); // findColumnIndex should return -1 if no column header name matches assertEquals(-1, table.findColumnIndex(null)); @@ -323,7 +321,7 @@ public final class TestXSSFTable { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sh = wb.createSheet(); - // 1 header row + 1 data row + // 1 header row + 1 data row AreaReference tableArea = new AreaReference("C10:C11", wb.getSpreadsheetVersion()); XSSFTable table = sh.createTable(tableArea); @@ -438,18 +436,19 @@ public final class TestXSSFTable { assertEquals(2, table.getRowCount()); // column IDs start at 1, and increase in the order columns are added (see bug #62740) - assertEquals("Column c ID", 1, c1.getId()); - assertTrue("Column B ID", c1.getId() < cB.getId()); - assertTrue("Column D ID", cB.getId() < cD.getId()); - assertTrue("Column C ID", cD.getId() < cC.getId()); - assertEquals("Column 1", table.getColumns().get(0).getName()); // generated name - assertEquals("Column B", table.getColumns().get(1).getName()); - assertEquals("Column C", table.getColumns().get(2).getName()); - assertEquals("Column D", table.getColumns().get(3).getName()); + assertEquals(1, c1.getId(), "Column c ID"); + assertTrue (c1.getId() < cB.getId(), "Column B ID"); + assertTrue (cB.getId() < cD.getId(), "Column D ID"); + assertTrue (cD.getId() < cC.getId(), "Column C ID"); + // generated name + assertEquals(table.getColumns().get(0).getName(), "Column 1"); + assertEquals(table.getColumns().get(1).getName(), "Column B"); + assertEquals(table.getColumns().get(2).getName(), "Column C"); + assertEquals(table.getColumns().get(3).getName(), "Column D"); } } - @Test(expected = IllegalArgumentException.class) + @Test public void testCreateColumnInvalidIndex() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sh = wb.createSheet(); @@ -458,7 +457,8 @@ public final class TestXSSFTable { // add columns table.createColumn("Column 2", 1); - table.createColumn("Column 3", 3); // out of bounds + // out of bounds + assertThrows(IllegalArgumentException.class, () -> table.createColumn("Column 3", 3)); } } @@ -563,7 +563,7 @@ public final class TestXSSFTable { } } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetDisplayNameNull() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet(); @@ -572,11 +572,11 @@ public final class TestXSSFTable { new CellReference(0, 0), new CellReference(2, 2)); XSSFTable table1 = sheet.createTable(reference1); - table1.setDisplayName(null); + assertThrows(IllegalArgumentException.class, () -> table1.setDisplayName(null)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetDisplayNameEmpty() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet(); @@ -585,7 +585,7 @@ public final class TestXSSFTable { new CellReference(0, 0), new CellReference(2, 2)); XSSFTable table1 = sheet.createTable(reference1); - table1.setDisplayName(""); + assertThrows(IllegalArgumentException.class, () -> table1.setDisplayName("")); } } @@ -597,10 +597,11 @@ public final class TestXSSFTable { try (XSSFWorkbook workbook = new XSSFWorkbook()) { XSSFSheet sheet0 = workbook.createSheet(); XSSFTable table = addTable(sheet0, 3, 0, 2, 2); + assertNotNull(table); - final String procName = "testXSSFTableGetName"; - final String name = table.getName(); - System.out.println(String.format(Locale.ROOT, "%s: table.getName=%s", procName, name)); + // final String procName = "testXSSFTableGetName"; + // final String name = table.getName(); + // System.out.printf(Locale.ROOT, "%s: table.getName=%s%n", procName, name); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java index decc402508..8905897020 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java @@ -17,15 +17,15 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.List; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFTableColumn { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java index 75eec4feb2..bfd4814419 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.awt.Color; import java.io.IOException; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFTextParagraph { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java index 9877772c65..2fab40173a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.awt.Color; import java.io.IOException; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestXSSFTextRun { @Test @@ -58,12 +58,8 @@ public class TestXSSFTextRun { assertEquals(11.0, run.getFontSize(), 0.01); run.setFontSize(-1.0); assertEquals(11.0, run.getFontSize(), 0.01); - try { - run.setFontSize(0.9); - fail("Should fail"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("0.9")); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> run.setFontSize(0.9)); + assertTrue(e.getMessage().contains("0.9")); assertEquals(11.0, run.getFontSize(), 0.01); assertEquals(0.0, run.getCharacterSpacing(), 0.01); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java index cbb5c8d3a0..ce0f0b9fb1 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java @@ -17,12 +17,13 @@ package org.apache.poi.xssf.usermodel; +import static org.junit.jupiter.api.Assertions.assertEquals; + 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.util.TempFile; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileInputStream; @@ -32,7 +33,7 @@ import java.io.IOException; public class TestXSSFUnicodeSurrogates { // "𝝊𝝋𝝌𝝍𝝎𝝏𝝐𝝑𝝒𝝓𝝔𝝕𝝖𝝗𝝘𝝙𝝚𝝛𝝜𝝝𝝞𝝟𝝠𝝡𝝢𝝣𝝤𝝥𝝦𝝧𝝨𝝩𝝪𝝫𝝬𝝭𝝮𝝯𝝰𝝱𝝲𝝳𝝴𝝵𝝶𝝷𝝸𝝹𝝺"; - private static String unicodeText = + private static final String unicodeText = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" + "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58" + "\uD835\uDF59\uD835\uDF5A\uD835\uDF5B\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835" + @@ -57,7 +58,7 @@ public class TestXSSFUnicodeSurrogates { XSSFWorkbook wb2 = new XSSFWorkbook(fis)) { Sheet sheet2 = wb2.getSheet(sheetName); Cell cell2 = sheet2.getRow(0).getCell(0); - Assert.assertEquals(unicodeText, cell2.getStringCellValue()); + assertEquals(unicodeText, cell2.getStringCellValue()); } } finally { tf.delete(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java index 8dbd8e7a81..5e4d94b41a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java @@ -18,11 +18,11 @@ package org.apache.poi.xssf.usermodel; import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import static org.apache.poi.xssf.usermodel.XSSFVMLDrawing.QNAME_VMLDRAWING; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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 java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -46,7 +46,7 @@ import org.apache.poi.POIDataSamples; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalse; import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalseBlank; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java index c13d96bc2d..230af2331e 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java @@ -17,14 +17,15 @@ package org.apache.poi.xssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -74,7 +75,7 @@ import org.apache.poi.xddf.usermodel.chart.XDDFChartData; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.StylesTable; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook; @@ -98,7 +99,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); assertNotNull(pr); assertTrue(pr.isSetDate1904()); - assertFalse("XSSF must use the 1900 date system", pr.getDate1904()); + assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system"); Sheet sheet1 = wb1.createSheet("sheet1"); Sheet sheet2 = wb1.createSheet("sheet2"); @@ -443,45 +444,40 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test public void bug49702() throws IOException { // First try with a new file - XSSFWorkbook wb1 = new XSSFWorkbook(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - // Should have one style - assertEquals(1, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short)0); - assertNull("Shouldn't be able to get style at 0 that doesn't exist", - wb1.getCellStyleAt((short)1)); + // Should have one style + assertEquals(1, wb1.getNumCellStyles()); + wb1.getCellStyleAt((short) 0); + assertNull(wb1.getCellStyleAt((short) 1), "Shouldn't be able to get style at 0 that doesn't exist"); - // Add another one - CellStyle cs = wb1.createCellStyle(); - cs.setDataFormat((short)11); + // Add another one + CellStyle cs = wb1.createCellStyle(); + cs.setDataFormat((short) 11); - // Re-check - assertEquals(2, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short)0); - wb1.getCellStyleAt((short)1); - assertNull("Shouldn't be able to get style at 2 that doesn't exist", - wb1.getCellStyleAt((short)2)); + // Re-check + assertEquals(2, wb1.getNumCellStyles()); + wb1.getCellStyleAt((short) 0); + wb1.getCellStyleAt((short) 1); + assertNull(wb1.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); - // Save and reload - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(2, nwb.getNumCellStyles()); - nwb.getCellStyleAt((short)0); - nwb.getCellStyleAt((short)1); - assertNull("Shouldn't be able to get style at 2 that doesn't exist", - nwb.getCellStyleAt((short)2)); + // Save and reload + try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + assertEquals(2, nwb.getNumCellStyles()); + nwb.getCellStyleAt((short) 0); + nwb.getCellStyleAt((short) 1); + assertNull(nwb.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); - // Now with an existing file - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - assertEquals(3, wb2.getNumCellStyles()); - wb2.getCellStyleAt((short)0); - wb2.getCellStyleAt((short)1); - wb2.getCellStyleAt((short)2); - assertNull("Shouldn't be able to get style at 3 that doesn't exist", - wb2.getCellStyleAt((short)3)); - - wb2.close(); - wb1.close(); - nwb.close(); + // Now with an existing file + try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { + assertEquals(3, wb2.getNumCellStyles()); + wb2.getCellStyleAt((short) 0); + wb2.getCellStyleAt((short) 1); + wb2.getCellStyleAt((short) 2); + assertNull(wb2.getCellStyleAt((short) 3), "Shouldn't be able to get style at 3 that doesn't exist"); + } + } + } } @Test @@ -723,9 +719,9 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3"); XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed"); XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0); - assertTrue("should be a bar chart data series", series instanceof XDDFBarChartData.Series); - String formula = ((XDDFBarChartData.Series) series).getCategoryData().getFormula(); - assertTrue("should contain new sheet name", formula.startsWith("'Sheet1-Renamed'!")); + assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series"); + String formula = series.getCategoryData().getFormula(); + assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name"); read.close(); wb.close(); } @@ -765,7 +761,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { } } - protected void setPivotData(XSSFWorkbook wb){ + private void setPivotData(XSSFWorkbook wb){ XSSFSheet sheet = wb.createSheet(); Row row1 = sheet.createRow(0); @@ -994,7 +990,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { wb.close(); } - @SuppressWarnings("deprecation") @Test public void testBug56957CloseWorkbook() throws Exception { File file = TempFile.createTempFile("TestBug56957_", ".xlsx"); @@ -1007,30 +1002,26 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertTrue(file.exists()); // read-only mode works! - Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ)); - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; + try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ))) { + Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); + assertEquals(dateExp, dateAct); + } - workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; + try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ))) { + Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); + assertEquals(dateExp, dateAct); + } // now check read/write mode - workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; + try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE))) { + Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); + assertEquals(dateExp, dateAct); + } - workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; + try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE))) { + Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); + assertEquals(dateExp, dateAct); + } } finally { assertTrue(file.exists()); assertTrue(file.delete()); @@ -1067,18 +1058,19 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test public void testCloseBeforeWrite() throws IOException { - Workbook wb = new XSSFWorkbook(); - wb.createSheet("somesheet"); + try (Workbook wb = new XSSFWorkbook()) { + wb.createSheet("somesheet"); - // test what happens if we close the Workbook before we write it out - wb.close(); + // test what happens if we close the Workbook before we write it out + wb.close(); - try { - XSSFTestDataSamples.writeOutAndReadBack(wb); - fail("Expecting IOException here"); - } catch (RuntimeException e) { - // expected here - assertTrue("Had: " + e.getCause(), e.getCause() instanceof IOException); + assertThrows(IOException.class, () -> { + try { + XSSFTestDataSamples.writeOutAndReadBack(wb); + } catch (RuntimeException e) { + throw e.getCause(); + } + }); } } @@ -1089,27 +1081,27 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { public void getTable() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); XSSFTable table1 = wb.getTable("Tabella1"); - assertNotNull("Tabella1 was not found in workbook", table1); - assertEquals("Table name", "Tabella1", table1.getName()); - assertEquals("Sheet name", "Foglio1", table1.getSheetName()); + assertNotNull(table1, "Tabella1 was not found in workbook"); + assertEquals("Tabella1", table1.getName(), "Table name"); + assertEquals("Foglio1", table1.getSheetName(), "Sheet name"); // Table lookup should be case-insensitive - assertSame("Case insensitive table name lookup", table1, wb.getTable("TABELLA1")); + assertSame(table1, wb.getTable("TABELLA1"), "Case insensitive table name lookup"); // If workbook does not contain any data tables matching the provided name, getTable should return null - assertNull("Null table name should not throw NPE", wb.getTable(null)); - assertNull("Should not be able to find non-existent table", wb.getTable("Foglio1")); + assertNull(wb.getTable(null), "Null table name should not throw NPE"); + assertNull(wb.getTable("Foglio1"), "Should not be able to find non-existent table"); // If a table is added after getTable is called it should still be reachable by XSSFWorkbook.getTable // This test makes sure that if any caching is done that getTable never uses a stale cache XSSFTable table2 = wb.getSheet("Foglio2").createTable(null); table2.setName("Table2"); - assertSame("Did not find Table2", table2, wb.getTable("Table2")); + assertSame(table2, wb.getTable("Table2"), "Did not find Table2"); // If table name is modified after getTable is called, the table can only be found by its new name // This test makes sure that if any caching is done that getTable never uses a stale cache table1.setName("Table1"); - assertSame("Did not find Tabella1 renamed to Table1", table1, wb.getTable("TABLE1")); + assertSame(table1, wb.getTable("TABLE1"), "Did not find Tabella1 renamed to Table1"); wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java index c5244ebd55..7bb9b61e12 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -30,7 +30,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests ChartLegend diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java index 243169f3cd..c7298663b7 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; @@ -30,16 +30,16 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestXDDFManualLayout { private XSSFWorkbook wb; private XDDFManualLayout layout; - @Before + @BeforeEach public void createEmptyLayout() { wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); @@ -50,7 +50,7 @@ public final class TestXDDFManualLayout { layout = legend.getOrAddManualLayout(); } - @After + @AfterEach public void closeWB() throws IOException { wb.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java index 8a85d8b7ce..5217a11988 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.util.HashMap; @@ -42,7 +42,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSSF Area3d Charts diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java index 5b55a85b7a..f6d1709837 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.xddf.usermodel.chart.AxisCrosses; import org.apache.poi.xddf.usermodel.chart.AxisPosition; @@ -27,7 +27,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFCategoryAxis { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java index a7c912f43c..a50084b996 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java @@ -17,10 +17,10 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.List; @@ -34,9 +34,9 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestXSSFChartAxis { @@ -44,7 +44,7 @@ public final class TestXSSFChartAxis { private XSSFWorkbook wb; private XDDFChartAxis axis; - @Before + @BeforeEach public void setup() { wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); @@ -54,7 +54,7 @@ public final class TestXSSFChartAxis { axis = chart.createValueAxis(AxisPosition.BOTTOM); } - @After + @AfterEach public void teardown() throws IOException { wb.close(); wb = null; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java index a5608f447b..3d3d5c46b8 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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 java.io.IOException; import java.util.List; @@ -47,7 +47,7 @@ import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test get/set chart title. diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java index 42c59b3dcc..f8865fd01a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.xddf.usermodel.chart.AxisCrosses; import org.apache.poi.xddf.usermodel.chart.AxisPosition; @@ -27,7 +27,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFDateAxis { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java index 83a25dff64..8d83fe95c8 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -37,7 +37,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSSF Line Charts diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java index 5683bc4052..2b2b22d9fd 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -39,7 +39,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for XSSFScatterChartData. diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java index 87866259d5..0df7fb4996 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.usermodel.charts; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween; import org.apache.poi.xddf.usermodel.chart.AxisCrosses; @@ -28,7 +28,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXSSFValueAxis { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java index 67442a18d2..7ffe6a99a9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.usermodel.extensions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java index 957c835be4..4562de62d5 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java @@ -18,9 +18,9 @@ package org.apache.poi.xssf.usermodel.extensions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -30,7 +30,7 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; @@ -104,15 +104,15 @@ public class TestXSSFCellFill { assertEquals(rgbWithTint[2], -80); } } - + @Test public void testFillWithoutColors() throws IOException { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("FillWithoutColor.xlsx")) { XSSFCell cellWithFill = wb.getSheetAt(0).getRow(5).getCell(1); XSSFCellStyle style = cellWithFill.getCellStyle(); assertNotNull(style); - assertNull("had an empty background color", style.getFillBackgroundColorColor()); - assertNull("had an empty background color", style.getFillBackgroundXSSFColor()); + assertNull(style.getFillBackgroundColorColor(), "had an empty background color"); + assertNull(style.getFillBackgroundXSSFColor(), "had an empty background color"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java index 5a78f2bc10..1df48b8f67 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java @@ -17,23 +17,23 @@ package org.apache.poi.xssf.usermodel.extensions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 org.apache.poi.xssf.usermodel.XSSFOddHeader; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; public class TestXSSFHeaderFooter { - + private XSSFWorkbook wb; private XSSFSheet sheet; private XSSFHeaderFooter hO; @@ -42,8 +42,8 @@ public class TestXSSFHeaderFooter { private XSSFHeaderFooter fO; private XSSFHeaderFooter fE; private XSSFHeaderFooter fF; - - @Before + + @BeforeEach public void before() { wb = new XSSFWorkbook(); sheet = wb.createSheet(); @@ -54,15 +54,15 @@ public class TestXSSFHeaderFooter { fE = (XSSFHeaderFooter) sheet.getEvenFooter(); fF = (XSSFHeaderFooter) sheet.getFirstFooter(); } - - @After + + @AfterEach public void after() throws Exception { wb.close(); } @Test public void testGetHeaderFooter() { - CTHeaderFooter ctHf; + CTHeaderFooter ctHf; ctHf = hO.getHeaderFooter(); assertNotNull(ctHf); ctHf = hE.getHeaderFooter(); @@ -111,14 +111,12 @@ public class TestXSSFHeaderFooter { assertEquals("&CCenterFvalue1&LLeftFvalue1&RRightFvalue1", fF.getValue()); } - @Ignore("Test not yet created") + @Disabled("Test not yet created") public void testAreFieldsStripped() { - fail("Not yet implemented"); } - @Ignore("Test not yet created") + @Disabled("Test not yet created") public void testSetAreFieldsStripped() { - fail("Not yet implemented"); } @Test @@ -129,30 +127,30 @@ public class TestXSSFHeaderFooter { 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, XSSFOddHeader.stripFields(simple)); assertEquals(simple, XSSFOddHeader.stripFields(withPage)); assertEquals(simple, XSSFOddHeader.stripFields(withLots)); assertEquals(simple, XSSFOddHeader.stripFields(withFont)); assertEquals(simple + "&&", XSSFOddHeader.stripFields(withOtherAnds)); assertEquals(simple + "&a&b", XSSFOddHeader.stripFields(withOtherAnds2)); - + // Now test the default strip flag hE.setCenter("Center"); hE.setLeft("In the left"); - + assertEquals("In the left", hE.getLeft()); assertEquals("Center", hE.getCenter()); assertEquals("", hE.getRight()); - + hE.setLeft("Top &P&F&D Left"); assertEquals("Top &P&F&D Left", hE.getLeft()); assertFalse(hE.areFieldsStripped()); - + hE.setAreFieldsStripped(true); assertEquals("Top Left", hE.getLeft()); assertTrue(hE.areFieldsStripped()); - + // Now even more complex hE.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&V"); assertEquals("HEADER TEXT &V", hE.getCenter()); @@ -289,12 +287,12 @@ public class TestXSSFHeaderFooter { assertEquals("&RRightEvalue1", fE.getValue()); assertEquals("&RRightFvalue1", fF.getValue()); } - - + + @Test public void testGetSetCenterLeftRight() { - + assertEquals("", fO.getCenter()); fO.setCenter("My first center section"); assertEquals("My first center section", fO.getCenter()); @@ -304,7 +302,7 @@ public class TestXSSFHeaderFooter { fO.setRight("Finally the right section is added"); assertEquals("And add a left one", fO.getLeft()); assertEquals("Finally the right section is added", fO.getRight()); - + // Test changing the three sections value fO.setCenter("Second center version"); fO.setLeft("Second left version"); @@ -312,6 +310,6 @@ public class TestXSSFHeaderFooter { assertEquals("Second center version", fO.getCenter()); assertEquals("Second left version", fO.getLeft()); assertEquals("Second right version", fO.getRight()); - - } + + } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java index 3911d32462..075cbd21eb 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java @@ -25,21 +25,21 @@ import org.apache.poi.xssf.model.ThemesTable; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class XSSFCellBorderTest { private final XSSFWorkbook wb = new XSSFWorkbook(); private final StylesTable stylesSource = wb.getStylesSource(); private final XSSFCellBorder empty = new XSSFCellBorder(); - @Before + @BeforeEach public void setUp() { assertNotNull(stylesSource); assertEquals(1, stylesSource.getBorders().size()); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java index 9686dcf6a1..5570d91b21 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.usermodel.helpers; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -32,7 +32,7 @@ import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; @@ -255,7 +255,7 @@ public final class TestColumnHelper { /** * Creates and adds a hidden column and then a best fit column with the given min/max pairs. - * Suitable for testing handling of overlap. + * Suitable for testing handling of overlap. */ private static CTCols createHiddenAndBestFitColsWithHelper(int hiddenMin, int hiddenMax, int bestFitMin, int bestFitMax) { CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); @@ -388,7 +388,7 @@ public final class TestColumnHelper { columnHelper.setColDefaultStyle(11, cellStyle); assertEquals(0, col_2.getStyle()); assertEquals(1, columnHelper.getColDefaultStyle(10)); - + workbook.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java index c36e1fd519..ad2813d790 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.usermodel.helpers; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test the header and footer helper. diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java b/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java index dac40c9ee4..f808ad982a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java @@ -27,7 +27,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java index ec1a679d6d..4705141f4b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java @@ -17,11 +17,11 @@ package org.apache.poi.xssf.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java index c4a8b52f9a..74d323a5fb 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java @@ -17,7 +17,7 @@ package org.apache.poi.xssf.util; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -26,7 +26,7 @@ import java.nio.charset.StandardCharsets; import org.apache.poi.util.IOUtils; import org.apache.poi.util.ReplacingInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEvilUnclosedBRFixingInputStream { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java index 183098188f..cc4e62099a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java @@ -17,9 +17,9 @@ package org.apache.poi.xssf.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestNumericRanges { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java b/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java deleted file mode 100644 index 00683b6ce1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.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.xwpf; - -import org.apache.poi.xwpf.extractor.TestXWPFWordExtractor; -import org.apache.poi.xwpf.model.TestXWPFHeaderFooterPolicy; -import org.apache.poi.xwpf.usermodel.TestXWPFChart; -import org.apache.poi.xwpf.usermodel.TestXWPFDocument; -import org.apache.poi.xwpf.usermodel.TestXWPFHeader; -import org.apache.poi.xwpf.usermodel.TestXWPFHeadings; -import org.apache.poi.xwpf.usermodel.TestXWPFNumbering; -import org.apache.poi.xwpf.usermodel.TestXWPFParagraph; -import org.apache.poi.xwpf.usermodel.TestXWPFPictureData; -import org.apache.poi.xwpf.usermodel.TestXWPFRun; -import org.apache.poi.xwpf.usermodel.TestXWPFStyles; -import org.apache.poi.xwpf.usermodel.TestXWPFTable; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.xwpf and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestXWPFBugs.class, - org.apache.poi.xwpf.usermodel.TestXWPFBugs.class, - TestXWPFChart.class, - TestXWPFDocument.class, - TestXWPFWordExtractor.class, - TestXWPFHeaderFooterPolicy.class, - TestXWPFHeader.class, - TestXWPFHeadings.class, - TestXWPFParagraph.class, - TestXWPFRun.class, - TestXWPFTable.class, - TestXWPFStyles.class, - TestXWPFPictureData.class, - TestXWPFNumbering.class, - TestAllExtendedProperties.class, - TestPackageCorePropertiesGetKeywords.class -}) -public final class AllXWPFTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java index 6c2b7ae483..f243092bf5 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java @@ -17,23 +17,23 @@ package org.apache.poi.xwpf; +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.ooxml.POIXMLProperties.CoreProperties; import org.apache.poi.openxml4j.opc.PackageProperties; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorVariant; -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - /** * Tests if the {@link CoreProperties#getKeywords()} method. This test has been * submitted because even though the diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java index 550a0c18ca..082f398c71 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xwpf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.File; import java.io.FileInputStream; @@ -31,7 +31,7 @@ import org.apache.poi.util.TempFile; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestDocumentProtection { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java index 15b47927f3..93db6ce94f 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java @@ -17,8 +17,10 @@ package org.apache.poi.xwpf; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEm; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STEm; @@ -30,13 +32,13 @@ public class TestNecessaryOOXMLClasses { @Test public void testProblemClasses() { CTTblLayoutType ctTblLayoutType = CTTblLayoutType.Factory.newInstance(); - Assert.assertNotNull(ctTblLayoutType); + assertNotNull(ctTblLayoutType); STTblLayoutType stTblLayoutType = STTblLayoutType.Factory.newInstance(); - Assert.assertNotNull(stTblLayoutType); + assertNotNull(stTblLayoutType); CTEm ctEm = CTEm.Factory.newInstance(); - Assert.assertNotNull(ctEm); + assertNotNull(ctEm); STEm stEm = STEm.Factory.newInstance(); - Assert.assertNotNull(stEm); - Assert.assertEquals(STEm.CIRCLE, STEm.Enum.forString("circle")); + assertNotNull(stEm); + assertEquals(STEm.CIRCLE, STEm.Enum.forString("circle")); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java index 2295e9a5f3..bd669c39ec 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java @@ -17,14 +17,14 @@ package org.apache.poi.xwpf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; import org.apache.poi.openxml4j.opc.PackageProperties; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests if the {@link CoreProperties#getKeywords()} method. This test has been diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java index 3e293a6268..cc4ac55215 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java @@ -16,9 +16,10 @@ ==================================================================== */ package org.apache.poi.xwpf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.Assumptions.assumeTrue; import java.io.File; import java.io.IOException; @@ -38,8 +39,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.xmlbeans.XmlException; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument; public class TestXWPFBugs { @@ -71,7 +71,7 @@ public class TestXWPFBugs { // Check it can be decoded Decryptor d = Decryptor.getInstance(info); - assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell")); + assertTrue(d.verifyPassword("solrcell"), "Unable to process: document is encrypted"); // Check we can read the word document in that InputStream dataStream = d.getDataStream(filesystem); @@ -93,7 +93,7 @@ public class TestXWPFBugs { @Test public void bug53475_aes256() throws Exception { int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); + assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); File file = samples.getFile("bug53475-password-is-pass.docx"); POIFSFileSystem filesystem = new POIFSFileSystem(file, true); @@ -107,7 +107,7 @@ public class TestXWPFBugs { // Check it can be decoded Decryptor d = Decryptor.getInstance(info); - assertTrue("Unable to process: document is encrypted", d.verifyPassword("pass")); + assertTrue(d.verifyPassword("pass"), "Unable to process: document is encrypted"); // Check we can read the word document in that InputStream dataStream = d.getDataStream(filesystem); @@ -123,7 +123,7 @@ public class TestXWPFBugs { filesystem.close(); } - + @Test public void bug59058() throws IOException, XmlException { String[] files = {"bug57031.docx", "bug59058.docx"}; diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java index 6f74f01ed1..b0748455c4 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java @@ -17,14 +17,14 @@ package org.apache.poi.xwpf.extractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestExternalEntities { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java index 2ba870aed7..7975271d9d 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java @@ -21,9 +21,9 @@ import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertEndsWith; import static org.apache.poi.POITestCase.assertNotContained; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 java.util.Locale; @@ -33,7 +33,7 @@ import java.util.regex.Pattern; import org.apache.poi.util.StringUtil; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for HXFWordExtractor @@ -342,9 +342,9 @@ public class TestXWPFWordExtractor { hit = true; hits++; } - assertTrue("controlled content loading-" + targ, hit); + assertTrue(hit, "controlled content loading-" + targ); } - assertEquals("controlled content loading hit count", targs.length, hits); + assertEquals(targs.length, hits, "controlled content loading hit count"); } try (XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); @@ -365,7 +365,7 @@ public class TestXWPFWordExtractor { while (m.find()) { hit++; } - assertEquals("controlled content loading-" + targ, 1, hit); + assertEquals(1, hit, "controlled content loading-" + targ); } //"test\n" appears twice: once as the "title" and once in the text. //This also happens when you save this document as text from MSWord. @@ -374,7 +374,7 @@ public class TestXWPFWordExtractor { while (m.find()) { hit++; } - assertEquals("test", 2, hit); + assertEquals(2, hit, "test"); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java index 012b906b07..04271b14d7 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java @@ -23,13 +23,13 @@ import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for the various XWPF decorators @@ -39,14 +39,14 @@ public class TestXWPFDecorators { private XWPFDocument hyperlink; private XWPFDocument comments; - @Before + @BeforeEach public void setUp() throws IOException { simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); } - @After + @AfterEach public void tearDown() throws IOException { simple.close(); hyperlink.close(); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java index bd057008f2..21dc6751f0 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java @@ -21,15 +21,15 @@ import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFFooter; import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests for XWPF Header Footer Stuff @@ -42,7 +42,7 @@ public class TestXWPFHeaderFooterPolicy { private XWPFDocument oddEven; private XWPFDocument diffFirst; - @Before + @BeforeEach public void setUp() throws IOException { noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); @@ -52,7 +52,7 @@ public class TestXWPFHeaderFooterPolicy { diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); } - @After + @AfterEach public void tearDown() throws IOException { noHeader.close(); header.close(); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java index b43b9e6914..8abe0299d3 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestChangeTracking { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java index 309e9e9738..3976e61310 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -30,7 +30,7 @@ import java.math.BigInteger; import org.apache.poi.util.Units; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; public class TestXWPFBugs { @@ -202,9 +202,9 @@ public class TestXWPFBugs { // we removed id "2", so this one should be empty, all others not if (i == 2) { - assertNull("Failed for " + i, abstractNum); + assertNull(abstractNum, "Failed for " + i); } else { - assertNotNull("Failed for " + i, abstractNum); + assertNotNull(abstractNum, "Failed for " + i); assertEquals(i, abstractNum.getAbstractNum().getAbstractNumId().longValue()); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java index 62c9670479..be4c1af023 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java @@ -24,7 +24,7 @@ import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData; import org.apache.poi.xddf.usermodel.chart.XDDFChartData; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle; import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx; @@ -32,8 +32,8 @@ import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class TestXWPFChart { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java index 886d15c0a9..b720176a81 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java @@ -17,11 +17,11 @@ package org.apache.poi.xwpf.usermodel; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestXWPFComment { @Test diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index ed5c7ea32d..faf96df931 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -17,13 +17,14 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Assertions.fail; import java.io.IOException; import java.io.OutputStream; @@ -43,8 +44,8 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.xmlbeans.XmlCursor; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; public final class TestXWPFDocument { @@ -329,12 +330,7 @@ public final class TestXWPFDocument { assertTrue(allPackagePictures.contains(xwpfPictureData)); } - try { - allPictures.add(allPictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } + assertThrows(UnsupportedOperationException.class, () -> allPictures.add(allPictures.get(0)), "This list must be unmodifiable!"); doc.getPackage().revert(); } @@ -348,12 +344,7 @@ public final class TestXWPFDocument { assertNotNull(allPackagePictures); assertEquals(5, allPackagePictures.size()); - try { - allPackagePictures.add(allPackagePictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } + assertThrows(UnsupportedOperationException.class, () -> allPackagePictures.add(allPackagePictures.get(0)), "This list must be unmodifiable!"); doc.getPackage().revert(); } @@ -472,7 +463,7 @@ public final class TestXWPFDocument { } @Test - @Ignore("XWPF should be able to write to a new Stream when opened Read-Only") + @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") public void testWriteFromReadOnlyOPC() throws Exception { OPCPackage opc = OPCPackage.open( POIDataSamples.getDocumentInstance().getFile("SampleDoc.docx"), diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java index addfbcb6a9..e7f11fa3a1 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java @@ -16,27 +16,27 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.math.BigInteger; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; public class TestXWPFEndnote { - + private XWPFDocument docOut; private String p1Text; private String p2Text; private BigInteger endnoteId; private XWPFEndnote endnote; - @Before + @BeforeEach public void setUp() { docOut = new XWPFDocument(); p1Text = "First paragraph in footnote"; @@ -46,115 +46,112 @@ public class TestXWPFEndnote { // to XWPFEndnotes.createEndnote() so this tests // both creation of new XWPFEndnotes in document // and XWPFEndnotes.createEndnote(); - + // NOTE: Creating the endnote does not automatically // create a first paragraph. endnote = docOut.createEndnote(); endnoteId = endnote.getId(); - + } @Test public void testAddParagraphsToFootnote() throws IOException { - // Add a run to the first paragraph: - + // Add a run to the first paragraph: + XWPFParagraph p1 = endnote.createParagraph(); p1.createRun().setText(p1Text); - + // Create a second paragraph: - + XWPFParagraph p = endnote.createParagraph(); - assertNotNull("Paragraph is null", p); + assertNotNull(p, "Paragraph is null"); p.createRun().setText(p2Text); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - + XWPFEndnote testEndnote = docIn.getEndnoteByID(endnoteId.intValue()); assertNotNull(testEndnote); - + assertEquals(2, testEndnote.getParagraphs().size()); XWPFParagraph testP1 = testEndnote.getParagraphs().get(0); assertEquals(p1Text, testP1.getText()); XWPFParagraph testP2 = testEndnote.getParagraphs().get(1); - assertEquals(p2Text, testP2.getText()); - + assertEquals(p2Text, testP2.getText()); + // The first paragraph added using createParagraph() should // have the required footnote reference added to the first // run. - + // Verify that we have a footnote reference in the first paragraph and not // in the second paragraph. - + XWPFRun r1 = testP1.getRuns().get(0); assertNotNull(r1); - assertTrue("No endnote reference in testP1", r1.getCTR().getEndnoteRefList().size() > 0); - assertNotNull("No endnote reference in testP1", r1.getCTR().getEndnoteRefArray(0)); + assertTrue(r1.getCTR().getEndnoteRefList().size() > 0, "No endnote reference in testP1"); + assertNotNull(r1.getCTR().getEndnoteRefArray(0), "No endnote reference in testP1"); XWPFRun r2 = testP2.getRuns().get(0); - assertNotNull("Expected a run in testP2", r2); - assertEquals("Found an endnote reference in testP2", 0, r2.getCTR().getEndnoteRefList().size()); - + assertNotNull(r2, "Expected a run in testP2"); + assertEquals(0, r2.getCTR().getEndnoteRefList().size(), "Found an endnote reference in testP2"); + } - + @Test public void testAddTableToFootnote() throws IOException { XWPFTable table = endnote.createTable(); assertNotNull(table); - + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - + XWPFEndnote testFootnote = docIn.getEndnoteByID(endnoteId.intValue()); XWPFTable testTable = testFootnote.getTableArray(0); assertNotNull(testTable); - + table = endnote.createTable(2, 3); assertEquals(2, table.getNumberOfRows()); assertEquals(3, table.getRow(0).getTableCells().size()); - + // If the table is the first body element of the footnote then // a paragraph with the footnote reference should have been // added automatically. - - assertEquals("Expected 3 body elements", 3, endnote.getBodyElements().size()); + + assertEquals(3, endnote.getBodyElements().size(), "Expected 3 body elements"); IBodyElement testP1 = endnote.getBodyElements().get(0); - assertTrue("Expected a paragraph, got " + testP1.getClass().getSimpleName() , testP1 instanceof XWPFParagraph); + assertTrue(testP1 instanceof XWPFParagraph, "Expected a paragraph, got " + testP1.getClass().getSimpleName()); XWPFRun r1 = ((XWPFParagraph)testP1).getRuns().get(0); assertNotNull(r1); - assertTrue("No footnote reference in testP1", r1.getCTR().getEndnoteRefList().size() > 0); - assertNotNull("No footnote reference in testP1", r1.getCTR().getEndnoteRefArray(0)); + assertTrue(r1.getCTR().getEndnoteRefList().size() > 0, "No footnote reference in testP1"); + assertNotNull(r1.getCTR().getEndnoteRefArray(0), "No footnote reference in testP1"); } - + @Test public void testRemoveEndnote() { - // NOTE: XWPFDocument.removeEndnote() delegates directly to + // NOTE: XWPFDocument.removeEndnote() delegates directly to // XWPFEndnotes. docOut.createEndnote(); - assertEquals("Expected 2 endnotes", 2, docOut.getEndnotes().size()); - assertNotNull("Didn't get second endnote", docOut.getEndnotes().get(1)); + assertEquals(2, docOut.getEndnotes().size(), "Expected 2 endnotes"); + assertNotNull(docOut.getEndnotes().get(1), "Didn't get second endnote"); boolean result = docOut.removeEndnote(0); - assertTrue("Remove endnote did not return true", result); - assertEquals("Expected 1 endnote after removal", 1, docOut.getEndnotes().size()); + assertTrue(result, "Remove endnote did not return true"); + assertEquals(1, docOut.getEndnotes().size(), "Expected 1 endnote after removal"); } @Test public void testAddFootnoteRefToParagraph() { XWPFParagraph p = docOut.createParagraph(); List runs = p.getRuns(); - assertEquals("Expected no runs in new paragraph", 0, runs.size()); + assertEquals(0, runs.size(), "Expected no runs in new paragraph"); p.addFootnoteReference(endnote); XWPFRun run = p.getRuns().get(0); CTR ctr = run.getCTR(); - assertNotNull("Expected a run", run); + assertNotNull(run, "Expected a run"); List endnoteRefList = ctr.getEndnoteReferenceList(); assertNotNull(endnoteRefList); CTFtnEdnRef ref = endnoteRefList.get(0); assertNotNull(ref); - assertEquals("Endnote ID and reference ID did not match", endnote.getId(), ref.getId()); - - + assertEquals(endnote.getId(), ref.getId(), "Endnote ID and reference ID did not match"); } - } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java index 2fda6ab44d..e0a17b0c6a 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java @@ -17,15 +17,15 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +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.io.IOException; import java.math.BigInteger; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; public class TestXWPFEndnotes { diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java index 143a3ad2ad..23a6b22e82 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java @@ -16,27 +16,27 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.math.BigInteger; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; public class TestXWPFFootnote { - + private XWPFDocument docOut; private String p1Text; private String p2Text; private BigInteger footnoteId; private XWPFFootnote footnote; - @Before + @BeforeEach public void setUp() { docOut = new XWPFDocument(); p1Text = "First paragraph in footnote"; @@ -46,115 +46,114 @@ public class TestXWPFFootnote { // to XWPFFootnotes.createFootnote() so this tests // both creation of new XWPFFootnotes in document // and XWPFFootnotes.createFootnote(); - + // NOTE: Creating the footnote does not automatically // create a first paragraph. footnote = docOut.createFootnote(); footnoteId = footnote.getId(); - + } @Test public void testAddParagraphsToFootnote() throws IOException { - // Add a run to the first paragraph: - + // Add a run to the first paragraph: + XWPFParagraph p1 = footnote.createParagraph(); p1.createRun().setText(p1Text); - + // Create a second paragraph: - + XWPFParagraph p = footnote.createParagraph(); - assertNotNull("Paragraph is null", p); + assertNotNull(p, "Paragraph is null"); p.createRun().setText(p2Text); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - + XWPFFootnote testFootnote = docIn.getFootnoteByID(footnoteId.intValue()); assertNotNull(testFootnote); - + assertEquals(2, testFootnote.getParagraphs().size()); XWPFParagraph testP1 = testFootnote.getParagraphs().get(0); assertEquals(p1Text, testP1.getText()); XWPFParagraph testP2 = testFootnote.getParagraphs().get(1); - assertEquals(p2Text, testP2.getText()); - + assertEquals(p2Text, testP2.getText()); + // The first paragraph added using createParagraph() should // have the required footnote reference added to the first // run. - + // Verify that we have a footnote reference in the first paragraph and not // in the second paragraph. - + XWPFRun r1 = testP1.getRuns().get(0); assertNotNull(r1); - assertTrue("No footnote reference in testP1", r1.getCTR().getFootnoteRefList().size() > 0); - assertNotNull("No footnote reference in testP1", r1.getCTR().getFootnoteRefArray(0)); + assertTrue(r1.getCTR().getFootnoteRefList().size() > 0, "No footnote reference in testP1"); + assertNotNull(r1.getCTR().getFootnoteRefArray(0), "No footnote reference in testP1"); XWPFRun r2 = testP2.getRuns().get(0); - assertNotNull("Expected a run in testP2", r2); - assertEquals("Found a footnote reference in testP2", 0, r2.getCTR().getFootnoteRefList().size()); - + assertNotNull(r2, "Expected a run in testP2"); + assertEquals(0, r2.getCTR().getFootnoteRefList().size(), "Found a footnote reference in testP2"); + } - + @Test public void testAddTableToFootnote() throws IOException { XWPFTable table = footnote.createTable(); assertNotNull(table); - + XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - + XWPFFootnote testFootnote = docIn.getFootnoteByID(footnoteId.intValue()); XWPFTable testTable = testFootnote.getTableArray(0); assertNotNull(testTable); - + table = footnote.createTable(2, 3); assertEquals(2, table.getNumberOfRows()); assertEquals(3, table.getRow(0).getTableCells().size()); - + // If the table is the first body element of the footnote then // a paragraph with the footnote reference should have been // added automatically. - - assertEquals("Expected 3 body elements", 3, footnote.getBodyElements().size()); + + assertEquals(3, footnote.getBodyElements().size(), "Expected 3 body elements"); IBodyElement testP1 = footnote.getBodyElements().get(0); - assertTrue("Expected a paragraph, got " + testP1.getClass().getSimpleName() , testP1 instanceof XWPFParagraph); + assertTrue(testP1 instanceof XWPFParagraph, "Expected a paragraph, got " + testP1.getClass().getSimpleName()); XWPFRun r1 = ((XWPFParagraph)testP1).getRuns().get(0); assertNotNull(r1); - assertTrue("No footnote reference in testP1", r1.getCTR().getFootnoteRefList().size() > 0); - assertNotNull("No footnote reference in testP1", r1.getCTR().getFootnoteRefArray(0)); - + assertTrue(r1.getCTR().getFootnoteRefList().size() > 0, "No footnote reference in testP1"); + assertNotNull(r1.getCTR().getFootnoteRefArray(0), "No footnote reference in testP1"); } - + @Test public void testRemoveFootnote() { - // NOTE: XWPFDocument.removeFootnote() delegates directly to + // NOTE: XWPFDocument.removeFootnote() delegates directly to // XWPFFootnotes. docOut.createFootnote(); - assertEquals("Expected 2 footnotes", 2, docOut.getFootnotes().size()); - assertNotNull("Didn't get second footnote", docOut.getFootnotes().get(1)); + assertEquals(2, docOut.getFootnotes().size(), "Expected 2 footnotes"); + assertNotNull(docOut.getFootnotes().get(1), "Didn't get second footnote"); boolean result = docOut.removeFootnote(0); - assertTrue("Remove footnote did not return true", result); - assertEquals("Expected 1 footnote after removal", 1, docOut.getFootnotes().size()); + assertTrue(result, "Remove footnote did not return true"); + assertEquals(1, docOut.getFootnotes().size(), "Expected 1 footnote after removal"); } @Test public void testAddFootnoteRefToParagraph() { XWPFParagraph p = docOut.createParagraph(); List runs = p.getRuns(); - assertEquals("Expected no runs in new paragraph", 0, runs.size()); + assertEquals(0, runs.size(), "Expected no runs in new paragraph"); p.addFootnoteReference(footnote); XWPFRun run = p.getRuns().get(0); CTR ctr = run.getCTR(); - assertNotNull("Expected a run", run); + assertNotNull(run, "Expected a run"); CTFtnEdnRef ref = ctr.getFootnoteReferenceList().get(0); assertNotNull(ref); // FIXME: Verify that the footnote reference is w:endnoteReference, not w:footnoteReference - assertEquals("Footnote ID and reference ID did not match", footnote.getId(), ref.getId()); - - - + assertEquals(footnote.getId(), ref.getId(), "Footnote ID and reference ID did not match"); + + + } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java index 1f496f2840..8a71e84d2b 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java @@ -22,12 +22,12 @@ import java.math.BigInteger; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; public class TestXWPFFootnotes { @Test @@ -81,7 +81,7 @@ public class TestXWPFFootnotes { } } } - assertEquals("Load footnotes once", 1, hits); + assertEquals(1, hits, "Load footnotes once"); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java index 29fa8ba142..6ec254f3ca 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java @@ -17,16 +17,16 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; @@ -231,25 +231,25 @@ public final class TestXWPFHeader { } } - @Ignore + @Disabled @Test public void testAddPictureData() { // TODO } - @Ignore + @Disabled @Test public void testGetAllPictures() { // TODO } - @Ignore + @Disabled @Test public void testGetAllPackagePictures() { // TODO } - @Ignore + @Disabled @Test public void testGetPictureDataById() { // TODO diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java index b26360dc00..17e41b66cf 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java @@ -19,12 +19,12 @@ package org.apache.poi.xwpf.usermodel; import java.io.IOException; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Paolo Mottadelli diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java index 5b61a71cea..771c8fd80c 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java @@ -17,15 +17,15 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.IOException; import java.math.BigInteger; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java index d9985ab30f..a9f1c0a764 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java @@ -17,18 +17,18 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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 java.math.BigInteger; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument; import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl; @@ -771,7 +771,7 @@ public final class TestXWPFParagraph { str.append(par.getText()).append("\n"); } String s = str.toString(); - assertTrue("Having text: \n" + s + "\nTrimmed length: " + s.trim().length(), s.trim().length() > 0); + assertTrue(s.trim().length() > 0, "Having text: \n" + s + "\nTrimmed length: " + s.trim().length()); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java index 570d153d88..02149a7e32 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java @@ -17,11 +17,12 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -32,8 +33,8 @@ import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TestXWPFPictureData { @@ -127,9 +128,7 @@ public class TestXWPFPictureData { // Document shouldn't have any image relationships assertEquals(13, doc.getPackagePart().getRelationships().size()); for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { - if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) { - fail("Shouldn't have JPEG yet"); - } + assertNotEquals(XSSFRelation.IMAGE_JPEG.getRelation(), rel.getRelationshipType(), "Shouldn't have JPEG yet"); } // Add the image @@ -145,12 +144,11 @@ public class TestXWPFPictureData { PackageRelationship jpegRel = null; for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) { - if (jpegRel != null) - fail("Found 2 jpegs!"); + assertNull(jpegRel, "Found 2 jpegs!"); jpegRel = rel; } } - assertNotNull("JPEG Relationship not found", jpegRel); + assertNotNull(jpegRel, "JPEG Relationship not found"); // Check the details assertNotNull(jpegRel); @@ -185,7 +183,7 @@ public class TestXWPFPictureData { .map(XWPFRun::getEmbeddedPictures) .flatMap(List::stream) .map(XWPFPicture::getPictureData) - .forEach(Assert::assertNull); + .forEach(Assertions::assertNull); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java index 3bb802e344..7ccc739613 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -35,9 +35,9 @@ import org.apache.poi.util.Units; import org.apache.poi.wp.usermodel.HeaderFooterType; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; @@ -64,7 +64,7 @@ public class TestXWPFRun { private IRunBody irb; private XWPFDocument doc; - @Before + @BeforeEach public void setUp() { doc = new XWPFDocument(); p = doc.createParagraph(); @@ -73,7 +73,7 @@ public class TestXWPFRun { this.ctRun = CTR.Factory.newInstance(); } - @After + @AfterEach public void tearDown() throws Exception { doc.close(); } @@ -788,7 +788,7 @@ public class TestXWPFRun { String styleId = "bolditalic"; run.setStyle(styleId); String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal(); - assertNotNull("Expected to find a run style ID", candStyleId); + assertNotNull( candStyleId, "Expected to find a run style ID" ); assertEquals(styleId, candStyleId); assertEquals(styleId, run.getStyle()); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java index c1ca100be5..ed20affd16 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java @@ -18,15 +18,15 @@ package org.apache.poi.xwpf.usermodel; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestXWPFSDT { @@ -37,7 +37,7 @@ public final class TestXWPFSDT { public void testNestedSDTs() throws Exception { try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug64561.docx")) { XWPFAbstractSDT sdt = extractAllSDTs(doc).get(0); - assertEquals("extracted text", "Subject", sdt.getContent().getText()); + assertEquals("Subject", sdt.getContent().getText(), "extracted text"); } } @@ -58,10 +58,10 @@ public final class TestXWPFSDT { } } - assertEquals("controls size", 13, sdts.size()); + assertEquals(13, sdts.size(), "controls size"); - assertEquals("tag", "MyTag", tag); - assertEquals("title", "MyTitle", title); + assertEquals("MyTag", tag, "tag"); + assertEquals("MyTitle", title, "title"); } } @@ -86,11 +86,11 @@ public final class TestXWPFSDT { try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) { List sdts = extractAllSDTs(doc); - assertEquals("number of sdts", contents.length, sdts.size()); + assertEquals(contents.length, sdts.size(), "number of sdts"); for (int i = 0; i < contents.length; i++) { XWPFAbstractSDT sdt = sdts.get(i); - assertEquals(i + ": " + contents[i], contents[i], sdt.getContent().toString()); + assertEquals(contents[i], sdt.getContent().toString(), i + ": " + contents[i]); } } } @@ -100,7 +100,7 @@ public final class TestXWPFSDT { */ @Test public void testSDTAsCell() throws Exception { - //Bug54771a.docx and Bug54771b.docx test slightly + //Bug54771a.docx and Bug54771b.docx test slightly //different recursion patterns. Keep both! try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx")) { List sdts = extractAllSDTs(doc); @@ -146,7 +146,7 @@ public final class TestXWPFSDT { for (int i = 0; i < sdts.size(); i++) { XWPFAbstractSDT sdt = sdts.get(i); - assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText()); + assertEquals(targs.get(i), sdt.getContent().getText()); } } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java index ba9eb30ed4..466cadae65 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java @@ -21,7 +21,7 @@ import static org.apache.poi.POITestCase.assertContains; import java.io.IOException; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for reading SmartTags from Word docx. diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java index 8794798802..49fb85ea2d 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java @@ -17,19 +17,19 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; @@ -214,18 +214,14 @@ public final class TestXWPFStyles { XWPFStyles styles = doc.getStyles(); // Styles exist in the test document in this order, EmptyCellLayoutStyle // is missing a StyleId - try { - assertNotNull(styles.getStyle("NoList")); - assertNull(styles.getStyle("EmptyCellLayoutStyle")); - assertNotNull(styles.getStyle("BalloonText")); + assertNotNull(styles.getStyle("NoList")); + assertNull(styles.getStyle("EmptyCellLayoutStyle")); + assertNotNull(styles.getStyle("BalloonText")); - // Bug 64600: styleExist throws NPE - assertTrue(styles.styleExist("NoList")); - assertFalse(styles.styleExist("EmptyCellLayoutStyle")); - assertTrue(styles.styleExist("BalloonText")); - } catch (NullPointerException e) { - fail(e.toString()); - } + // Bug 64600: styleExist throws NPE + assertTrue(styles.styleExist("NoList")); + assertFalse(styles.styleExist("EmptyCellLayoutStyle")); + assertTrue(styles.styleExist("BalloonText")); } } @@ -237,7 +233,7 @@ public final class TestXWPFStyles { String styleName = "Normal Table"; XWPFStyle style = styles.getStyleWithName(styleName); - assertNotNull("Expected to find style \"" + styleName + "\"", style); + assertNotNull(style, "Expected to find style \"" + styleName + "\""); assertEquals(styleName, style.getName()); } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java index 52f2404363..d057e120ae 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.math.BigInteger; @@ -26,7 +26,7 @@ import java.util.List; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; @@ -553,15 +553,15 @@ public class TestXWPFTable { // assert the table is empty List rows = table.getRows(); - assertEquals("Table has less rows than requested.", noRows, rows.size()); + assertEquals(noRows, rows.size(), "Table has less rows than requested."); for (XWPFTableRow xwpfRow : rows) { assertNotNull(xwpfRow); for (int i = 0; i < 7; i++) { XWPFTableCell xwpfCell = xwpfRow.getCell(i); assertNotNull(xwpfCell); - assertEquals("Empty cells should not have one paragraph.", 1, xwpfCell.getParagraphs().size()); + assertEquals(1, xwpfCell.getParagraphs().size(), "Empty cells should not have one paragraph."); xwpfCell = xwpfRow.getCell(i); - assertEquals("Calling 'getCell' must not modify cells content.", 1, xwpfCell.getParagraphs().size()); + assertEquals(1, xwpfCell.getParagraphs().size(), "Calling 'getCell' must not modify cells content."); } } doc.getPackage().revert(); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java index cc6434e841..93214b4759 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java @@ -19,12 +19,12 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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 org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; @@ -132,7 +132,7 @@ public class TestXWPFTableCell { } // This is not a very useful test as written. It is not worth the execution time for a unit test - @Ignore + @Disabled @Test public void testCellVerticalAlignShouldNotThrowNPE() throws Exception { XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("TestTableCellAlign.docx"); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java index 953a82e2fc..ee532e2631 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java @@ -17,15 +17,15 @@ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.xwpf.XWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHeightRule; public class TestXWPFTableRow { @@ -51,7 +51,7 @@ public class TestXWPFTableRow { // Assert the repeat header is false by default boolean isCantSplit = tr.isCantSplitRow(); assertFalse(isCantSplit); - + // Repeat the header tr.setCantSplitRow(true); isCantSplit = tr.isCantSplitRow(); @@ -61,7 +61,7 @@ public class TestXWPFTableRow { tr.setCantSplitRow(false); isCantSplit = tr.isCantSplitRow(); assertFalse(isCantSplit); - + doc.close(); } @@ -73,11 +73,11 @@ public class TestXWPFTableRow { // table has a single row by default; grab it XWPFTableRow tr = table.getRow(0); assertNotNull(tr); - + // Assert the repeat header is false by default boolean isRpt = tr.isRepeatHeader(); assertFalse(isRpt); - + // Repeat the header tr.setRepeatHeader(true); isRpt = tr.isRepeatHeader(); @@ -87,7 +87,7 @@ public class TestXWPFTableRow { tr.setRepeatHeader(false); isRpt = tr.isRepeatHeader(); assertFalse(isRpt); - + // If the third row is set to repeat, but not the second, // isRepeatHeader should report false because Word will // ignore it. @@ -95,10 +95,10 @@ public class TestXWPFTableRow { tr.setRepeatHeader(true); isRpt = tr.isRepeatHeader(); assertFalse(isRpt); - + doc.close(); } - + // Test that validates the table header value can be parsed from a document // generated in Word @Test @@ -119,8 +119,8 @@ public class TestXWPFTableRow { assertFalse(isRpt); } } - - + + // Test that validates the table header value can be parsed from a document // generated in Word @Test diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/XWPFAbstractNumTest.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/XWPFAbstractNumTest.java index c4d0aec45d..b2909782f0 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/XWPFAbstractNumTest.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/XWPFAbstractNumTest.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class XWPFAbstractNumTest { diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java index e68cace494..8b69548f46 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java @@ -17,17 +17,17 @@ package org.apache.poi.hdgf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.POIDataSamples; import org.apache.poi.hdgf.extractor.VisioTextExtractor; import org.apache.poi.hdgf.streams.PointerContainingStream; import org.apache.poi.hdgf.streams.TrailerStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestHDGFCore { private static POIDataSamples _dgTests = POIDataSamples.getDiagramInstance(); @@ -36,11 +36,11 @@ public final class TestHDGFCore { private HDGFDiagram hdgf; private VisioTextExtractor textExtractor; - @Before + @BeforeEach public void setUp() throws Exception { fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd")); } - @After + @AfterEach public void tearDown() throws Exception { if (textExtractor != null) textExtractor.close(); if (hdgf != null) hdgf.close(); diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java index 0dc7b30aa6..6d70771657 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java @@ -17,13 +17,13 @@ package org.apache.poi.hdgf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHDGFLZW { public static final byte[] testTrailerComp = { diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/chunks/TestChunks.java b/src/scratchpad/testcases/org/apache/poi/hdgf/chunks/TestChunks.java index bfcec5d595..a187fadf42 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/chunks/TestChunks.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/chunks/TestChunks.java @@ -17,22 +17,22 @@ package org.apache.poi.hdgf.chunks; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.hdgf.chunks.ChunkFactory.CommandDefinition; import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public final class TestChunks { private static byte[] data_a, data_b; - @BeforeClass + @BeforeAll public static void setup() throws IOException { data_a = RawDataUtil.decompress( "H4sIAAAAAAAAAHNjYGD4DwRMQNqFAQygFAMTWAIbYIBqQqZRARMSOwNKMwOxChAzMoRIACkeNC3MUAwDjEjGTEISb" + diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/dev/TestVSDDumper.java b/src/scratchpad/testcases/org/apache/poi/hdgf/dev/TestVSDDumper.java index 0b3b68bc63..183342cebc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/dev/TestVSDDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/dev/TestVSDDumper.java @@ -25,20 +25,20 @@ import java.io.PrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.NullPrintStream; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestVSDDumper { private static PrintStream oldStdOut; - @BeforeClass + @BeforeAll public static void muteStdout() { oldStdOut = System.out; System.setOut(new NullPrintStream()); } - @AfterClass + @AfterAll public static void restoreStdout() { System.setOut(oldStdOut); } diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java b/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java index aaa1cb4be8..18b5e16eb9 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java @@ -17,8 +17,8 @@ package org.apache.poi.hdgf.extractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -26,7 +26,7 @@ import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hdgf.HDGFDiagram; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestVisioExtractor { private static final POIDataSamples _dgTests = POIDataSamples.getDiagramInstance(); diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/pointers/TestPointerFactory.java b/src/scratchpad/testcases/org/apache/poi/hdgf/pointers/TestPointerFactory.java index 8947533312..0e2972d6dc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/pointers/TestPointerFactory.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/pointers/TestPointerFactory.java @@ -17,11 +17,12 @@ package org.apache.poi.hdgf.pointers; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for the pointer factory, and the pointers themselves @@ -50,10 +51,10 @@ public final class TestPointerFactory { -1, 0, 0, 0, -84, -1, 79, 1, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0 }; - @Test(expected = IllegalArgumentException.class) + @Test public void testCreateV4() { PointerFactory pf = new PointerFactory(4); - pf.createPointer(new byte[]{}, 0); + assertThrows(IllegalArgumentException.class, () -> pf.createPointer(new byte[]{}, 0)); } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBasics.java b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBasics.java index 436286c07e..9e1df7aec7 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBasics.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBasics.java @@ -18,21 +18,21 @@ package org.apache.poi.hdgf.streams; import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.hdgf.pointers.Pointer; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public final class TestStreamBasics extends StreamTest { private static byte[] compressedStream, uncompressedStream; - @BeforeClass + @BeforeAll public static void init() throws IOException { compressedStream = decompress( "H4sIAAAAAAAAAAFTAaz+e8QC6/ABAAC48/BO4PsBAAPr8AoFBOvwFQnr8Gfr8CLc/zQPRg94WA/5/u"+ @@ -43,7 +43,7 @@ public final class TestStreamBasics extends StreamTest { "AA2OvwpEJ/VQFidwAA0E8S/TLvAUNVAVGBANcADgYEET/BEURVvwEeiAAAKk8SRH7r8LRFVQFmiUgl"+ "AGEhwtTYaVMBAAA=" ); - + uncompressedStream = decompress( "H4sIAAAAAAAAAGNgZGDYAcSogJGBGUjCMAsQcwJxOhAroSulEkB2Qqsogw4I41KrMU/BL23vv0cOGn"+ "v7t5eAGU7VnLlgBobUibUb0fVX5HnDrROB0mJA/GW9M2MDkA4BYjcGcSDpc8Of8QqQVgCLgkT2AEV+"+ @@ -53,7 +53,7 @@ public final class TestStreamBasics extends StreamTest { "ROmAgIAAD6SJPAdAIAAA==" ); } - + @Test public void testCompressedStream() { diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBugs.java b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBugs.java index 006021b014..f2a9579f8a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBugs.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamBugs.java @@ -27,8 +27,8 @@ import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.PointerFactory; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for bugs with streams @@ -39,7 +39,7 @@ public final class TestStreamBugs extends StreamTest { private PointerFactory ptrFactory; private POIFSFileSystem filesystem; - @Before + @BeforeEach public void setUp() throws IOException { ptrFactory = new PointerFactory(11); chunkFactory = new ChunkFactory(11); diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamComplex.java b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamComplex.java index c601a06438..19ec45d0cc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamComplex.java +++ b/src/scratchpad/testcases/org/apache/poi/hdgf/streams/TestStreamComplex.java @@ -17,11 +17,11 @@ package org.apache.poi.hdgf.streams; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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 java.io.InputStream; @@ -33,8 +33,8 @@ import org.apache.poi.hdgf.pointers.Pointer; import org.apache.poi.hdgf.pointers.PointerFactory; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestStreamComplex extends StreamTest { private byte[] contents; @@ -43,7 +43,7 @@ public final class TestStreamComplex extends StreamTest { private ChunkFactory chunkFactory; private PointerFactory ptrFactory; - @Before + @BeforeEach public void setUp() throws IOException { ptrFactory = new PointerFactory(11); chunkFactory = new ChunkFactory(11); @@ -56,7 +56,7 @@ public final class TestStreamComplex extends StreamTest { InputStream is2 = filesystem.createDocumentInputStream("VisioDocument"); contents = IOUtils.toByteArray(is2); is2.close(); - + filesystem.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/TestHemfPlusExtractor.java b/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/TestHemfPlusExtractor.java index e082c623be..e15a06ab8c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/TestHemfPlusExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/TestHemfPlusExtractor.java @@ -18,7 +18,7 @@ package org.apache.poi.hemf.hemfplus.extractor; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.InputStream; import java.util.ArrayList; @@ -32,7 +32,7 @@ import org.apache.poi.hemf.record.emfplus.HemfPlusHeader; import org.apache.poi.hemf.record.emfplus.HemfPlusRecord; import org.apache.poi.hemf.record.emfplus.HemfPlusRecordType; import org.apache.poi.hemf.usermodel.HemfPicture; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestHemfPlusExtractor { diff --git a/src/scratchpad/testcases/org/apache/poi/hemf/usermodel/TestHemfPicture.java b/src/scratchpad/testcases/org/apache/poi/hemf/usermodel/TestHemfPicture.java index 0cea2261d7..1921b37bb1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hemf/usermodel/TestHemfPicture.java +++ b/src/scratchpad/testcases/org/apache/poi/hemf/usermodel/TestHemfPicture.java @@ -19,9 +19,10 @@ package org.apache.poi.hemf.usermodel; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.awt.geom.Point2D; import java.io.ByteArrayInputStream; @@ -49,7 +50,7 @@ import org.apache.poi.hwmf.usermodel.HwmfEmbeddedType; import org.apache.poi.hwmf.usermodel.HwmfPicture; import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("StatementWithEmptyBody") public class TestHemfPicture { @@ -274,27 +275,22 @@ public class TestHemfPicture { } } - @Test(expected = RecordFormatException.class) + @Test public void testInfiniteLoopOnFile() throws Exception { try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) { HemfPicture pic = new HemfPicture(is); - for (HemfRecord ignored : pic) { - - } + assertThrows(RecordFormatException.class, () -> pic.forEach(r -> {})); } } - @Test(expected = RecordFormatException.class) + @Test public void testInfiniteLoopOnByteArray() throws Exception { try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); - is.close(); HemfPicture pic = new HemfPicture(new ByteArrayInputStream(bos.toByteArray())); - for (HemfRecord ignored : pic) { - - } + assertThrows(RecordFormatException.class, () -> pic.forEach(r -> {})); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestAttachments.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestAttachments.java index c52591bf1d..c565d0b4d7 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestAttachments.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestAttachments.java @@ -18,8 +18,8 @@ package org.apache.poi.hmef; import static org.apache.poi.hmef.TestHMEFMessage.openSample; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.text.DateFormat; @@ -28,13 +28,13 @@ import java.util.List; import java.util.Locale; import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public final class TestAttachments { private static HMEFMessage quick; - @BeforeClass + @BeforeAll public static void setUp() throws IOException { quick = openSample("quick-winmail.dat"); } diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java index 24f3259380..69c52c3c97 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java @@ -17,9 +17,9 @@ package org.apache.poi.hmef; import static org.apache.poi.hmef.TestHMEFMessage.openSample; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.util.List; @@ -29,7 +29,7 @@ import org.apache.poi.hmef.attribute.TNEFAttribute; import org.apache.poi.hmef.attribute.TNEFProperty; import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.util.LittleEndian; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestBugs { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java index 3b5b1ec0b6..a4793a2839 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java @@ -17,10 +17,10 @@ package org.apache.poi.hmef; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.InputStream; @@ -34,7 +34,7 @@ import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.StringUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestCompressedRTF { private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java index 5c60d2d69b..f2542c48c1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java @@ -17,12 +17,12 @@ package org.apache.poi.hmef; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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 static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -40,7 +40,7 @@ import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.hsmf.datatypes.Types; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHMEFMessage { private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); @@ -66,8 +66,8 @@ public final class TestHMEFMessage { int mapiAttrCount = attach.getMAPIAttributes().size(); assertEquals(6, attrCount); - assertTrue("Should be 20-25 mapi attributes, found " + mapiAttrCount, mapiAttrCount >= 20); - assertTrue("Should be 20-25 mapi attributes, found " + mapiAttrCount, mapiAttrCount <= 25); + assertTrue(mapiAttrCount >= 20, "Should be 20-25 mapi attributes, found " + mapiAttrCount); + assertTrue(mapiAttrCount <= 25, "Should be 20-25 mapi attributes, found " + mapiAttrCount); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java index be76876743..34bd7b2a18 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java @@ -17,8 +17,8 @@ package org.apache.poi.hmef.attribute; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -31,14 +31,14 @@ import org.apache.poi.hmef.HMEFMessage; import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LocaleUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestMAPIAttributes { private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); private HMEFMessage quick; - @Before + @BeforeEach public void setUp() throws Exception { try (InputStream stream = _samples.openResourceAsStream("quick-winmail.dat")) { quick = new HMEFMessage(stream); diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java index eebb48d971..858abdfcea 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java @@ -17,8 +17,8 @@ package org.apache.poi.hmef.attribute; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -33,14 +33,14 @@ import org.apache.poi.hmef.HMEFMessage; import org.apache.poi.hsmf.datatypes.MAPIProperty; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LocaleUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestTNEFAttributes { private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); private HMEFMessage quick; - @Before + @BeforeEach public void setUp() throws Exception { try (InputStream is = _samples.openResourceAsStream("quick-winmail.dat")) { quick = new HMEFMessage(is); diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java b/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java index 2ef26a66b7..fdf85a7b13 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java @@ -20,17 +20,20 @@ ==================================================================== */ package org.apache.poi.hmef.dev; + +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.NullPrintStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestHMEFDumper { - @Test(expected = IllegalArgumentException.class) - public void noArguments() throws Exception { - doMain(); + @Test + public void noArguments() { + assertThrows(IllegalArgumentException.class, TestHMEFDumper::doMain); } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java b/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java index dc8bf9fdba..80e9be6726 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java @@ -17,10 +17,10 @@ package org.apache.poi.hmef.extractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertArrayEquals; +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.ByteArrayOutputStream; import java.io.File; @@ -29,7 +29,7 @@ import java.util.Arrays; import org.apache.poi.POIDataSamples; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestHMEFContentsExtractor { @Test @@ -44,16 +44,16 @@ public class TestHMEFContentsExtractor { "message.rtf", // from extractMessageBody "quick.txt", "quick.pdf", "quick.xml", "quick.doc", "quick.html" // from extractAttachments }; - + for (String filename : contents) { File f = new File(outputDirectory, filename); - assertTrue(f + " does not exist", f.exists()); + assertTrue(f.exists(), f + " does not exist"); assertTrue(f.delete()); } String[] list = outputDirectory.list(); assertNotNull(list); - assertEquals( "Had: " + Arrays.toString(list), 0, list.length); + assertEquals( 0, list.length, "Had: " + Arrays.toString(list)); assertTrue(outputDirectory.delete()); } @@ -67,7 +67,7 @@ public class TestHMEFContentsExtractor { assertTrue(out.size() > 0); byte[] expectedMagic = new byte[] { '{', '\\', 'r', 't', 'f' }; byte[] magic = Arrays.copyOf(out.toByteArray(), 5); - assertArrayEquals("RTF magic number", expectedMagic, magic); + assertArrayEquals(expectedMagic, magic, "RTF magic number"); out.close(); } @@ -79,6 +79,6 @@ public class TestHMEFContentsExtractor { File rtf = TempFile.createTempFile("quick-winmail-message-body", ".rtf"); assertTrue(rtf.delete()); extractor.extractMessageBody(rtf); - assertTrue("RTF message body is empty", rtf.length() > 0); + assertTrue(rtf.length() > 0, "RTF message body is empty"); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java b/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java index acb5a740f7..6bd9f05342 100644 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java +++ b/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java @@ -17,15 +17,15 @@ package org.apache.poi.hpbf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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 org.apache.poi.POIDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHPBFDocument { private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java b/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java index 09dca86a51..0495040238 100644 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java @@ -18,8 +18,8 @@ package org.apache.poi.hpbf.extractor; import static org.apache.poi.POITestCase.assertEndsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -27,7 +27,7 @@ import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpbf.HPBFDocument; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestPublisherTextExtractor { private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java index 28e1eeca69..39d18df778 100644 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java +++ b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java @@ -17,15 +17,15 @@ package org.apache.poi.hpbf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.hpbf.HPBFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherParts { private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); @@ -51,7 +51,7 @@ public final class TestEscherParts { @Test public void testComplex() throws Exception { - InputStream is = _samples.openResourceAsStream("SampleBrochure.pub"); + InputStream is = _samples.openResourceAsStream("SampleBrochure.pub"); HPBFDocument doc1 = new HPBFDocument(is); is.close(); @@ -68,7 +68,7 @@ public final class TestEscherParts { doc1.close(); // Now do another complex file - InputStream is2 = _samples.openResourceAsStream("SampleNewsletter.pub"); + InputStream is2 = _samples.openResourceAsStream("SampleNewsletter.pub"); HPBFDocument doc2 = new HPBFDocument(is2); is2.close(); diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java index d386664dce..e614691577 100644 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java +++ b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java @@ -19,10 +19,10 @@ package org.apache.poi.hpbf.model; import static org.apache.poi.POITestCase.assertStartsWith; import static org.apache.poi.POITestCase.assertEndsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -33,7 +33,7 @@ import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type12; import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type4; import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type8; import org.apache.poi.hpbf.model.qcbits.QCTextBit; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestQuillContents { private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java deleted file mode 100644 index e24b093dea..0000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.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.hslf; - -import org.apache.poi.hslf.extractor.TestCruddyExtractor; -import org.apache.poi.hslf.extractor.TestExtractor; -import org.apache.poi.hslf.model.AllHSLFModelTests; -import org.apache.poi.hslf.record.AllHSLFRecordTests; -import org.apache.poi.hslf.usermodel.AllHSLFUserModelTests; -import org.apache.poi.hslf.util.TestSystemTimeUtils; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf and all sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEncryptedFile.class, - TestRecordCounts.class, - TestReWrite.class, - TestReWriteSanity.class, - TestCruddyExtractor.class, - TestExtractor.class, - AllHSLFModelTests.class, - AllHSLFRecordTests.class, - AllHSLFUserModelTests.class, - TestSystemTimeUtils.class -}) -public class AllHSLFTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java index ffecf2a58a..1fe829c2e1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java @@ -18,7 +18,8 @@ package org.apache.poi.hslf; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.InputStream; @@ -26,7 +27,7 @@ import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that HSLFSlideShow does the right thing with an encrypted file @@ -43,24 +44,24 @@ public final class TestEncryptedFile { is.close(); } - @Test(expected=EncryptedPowerPointFileException.class) + @Test public void testLoadEncrypted1() throws IOException { try (InputStream is = slTests.openResourceAsStream("Password_Protected-hello.ppt")) { - new HSLFSlideShowImpl(is).close(); + assertThrows(EncryptedPowerPointFileException.class, () -> new HSLFSlideShowImpl(is).close()); } } - - @Test(expected=EncryptedPowerPointFileException.class) + + @Test public void testLoadEncrypted2() throws IOException { try (InputStream is = slTests.openResourceAsStream("Password_Protected-np-hello.ppt")) { - new HSLFSlideShowImpl(is).close(); + assertThrows(EncryptedPowerPointFileException.class, () -> new HSLFSlideShowImpl(is).close()); } } - - @Test(expected=EncryptedPowerPointFileException.class) + + @Test public void testLoadEncrypted3() throws IOException { try (InputStream is = slTests.openResourceAsStream("Password_Protected-56-hello.ppt")) { - new HSLFSlideShowImpl(is).close(); + assertThrows(EncryptedPowerPointFileException.class, () -> new HSLFSlideShowImpl(is).close()); } } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestPOIDocumentScratchpad.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestPOIDocumentScratchpad.java index 03f3fcf823..ee74b4527f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestPOIDocumentScratchpad.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestPOIDocumentScratchpad.java @@ -21,8 +21,8 @@ package org.apache.poi.hslf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -36,8 +36,8 @@ import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that POIDocument correctly loads and saves the common @@ -55,7 +55,7 @@ public final class TestPOIDocumentScratchpad { * Set things up, using a PowerPoint document and * a Word Document for our testing */ - @Before + @BeforeEach public void setUp() throws IOException { doc = new HSLFSlideShowImpl(POIDataSamples.getSlideShowInstance().openResourceAsStream("basic_test_ppt_file.ppt")); doc2 = HWPFTestDataSamples.openSampleFile("test2.doc"); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java index cdcb89ec0d..1eb72a88bf 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -33,8 +33,8 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.TempFile; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that HSLFSlideShow writes the powerpoint bit of data back out @@ -52,11 +52,11 @@ public final class TestReWrite { private POIFSFileSystem pfsB; private POIFSFileSystem pfsC; - @Before + @BeforeEach public void setUp() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - + pfsA = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); hssA = new HSLFSlideShowImpl(pfsA); @@ -72,39 +72,39 @@ public final class TestReWrite { assertWritesOutTheSame(hssA, pfsA); assertWritesOutTheSame(hssB, pfsB); } - + public void assertWritesOutTheSame(HSLFSlideShowImpl hss, POIFSFileSystem pfs) throws Exception { // Write out to a byte array, and to a temp file ByteArrayOutputStream baos = new ByteArrayOutputStream(); hss.write(baos); - + final File file = TempFile.createTempFile("TestHSLF", ".ppt"); final File file2 = TempFile.createTempFile("TestHSLF", ".ppt"); hss.write(file); hss.write(file2); - + // Build an input stream of it, and read back as a POIFS from the stream ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); POIFSFileSystem npfS = new POIFSFileSystem(bais); - + // And the same on the temp file POIFSFileSystem npfF = new POIFSFileSystem(file); - + // And another where we do an in-place write POIFSFileSystem npfRF = new POIFSFileSystem(file2, false); HSLFSlideShowImpl hssRF = new HSLFSlideShowImpl(npfRF); hssRF.write(); hssRF.close(); npfRF = new POIFSFileSystem(file2); - + // Check all of them in turn for (POIFSFileSystem npf : new POIFSFileSystem[] { npfS, npfF, npfRF }) { // Check that the "PowerPoint Document" sections have the same size DocumentEntry oProps = (DocumentEntry)pfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); DocumentEntry nProps = (DocumentEntry)npf.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); assertEquals(oProps.getSize(),nProps.getSize()); - + // Check that they contain the same data byte[] _oData = new byte[oProps.getSize()]; byte[] _nData = new byte[nProps.getSize()]; @@ -155,7 +155,7 @@ public final class TestReWrite { // We need to identify and fix that first //assertSlideShowWritesOutTheSame(hssB, pfsB); } - + public void assertSlideShowWritesOutTheSame(HSLFSlideShowImpl hss, POIFSFileSystem pfs) throws IOException { // Create a slideshow covering it @SuppressWarnings("resource") @@ -190,7 +190,7 @@ public final class TestReWrite { } npfs.close(); } - + @Test public void test48593() throws IOException { HSLFSlideShow ppt1 = new HSLFSlideShow(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java index e9d24f4a1e..c252aff7ed 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java @@ -19,7 +19,7 @@ package org.apache.poi.hslf; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -33,9 +33,9 @@ import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.UserEditAtom; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that HSLFSlideShow writes the powerpoint bit of data back out @@ -49,14 +49,14 @@ public final class TestReWriteSanity { // POIFS primed on the test data private POIFSFileSystem pfs; - @Before + @BeforeEach public void setUp() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); pfs = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); ss = new HSLFSlideShowImpl(pfs); } - - @After + + @AfterEach public void tearDown() throws Exception { pfs.close(); ss.close(); @@ -113,7 +113,7 @@ public final class TestReWriteSanity { CurrentUserAtom cua = wss.getCurrentUserAtom(); int listedUEPos = (int)cua.getCurrentEditOffset(); assertEquals(lastUEPos,listedUEPos); - + wss.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java index 19d66525ae..db3fd24868 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java @@ -18,7 +18,7 @@ package org.apache.poi.hslf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.record.Notes; @@ -26,8 +26,8 @@ import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.Slide; import org.apache.poi.hslf.record.SlideListWithText; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that HSLFSlideShow returns the right numbers of key records when @@ -39,7 +39,7 @@ public final class TestRecordCounts { // HSLFSlideShow primed on the test data private HSLFSlideShowImpl ss; - @Before + @BeforeEach public void setup() throws Exception { ss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java index bdb5bba463..5743e34e94 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.PrintStream; @@ -29,19 +29,19 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.exceptions.OldPowerPointFormatException; import org.apache.poi.util.IOUtils; import org.apache.poi.util.NullPrintStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public abstract class BasePPTIteratingTest { protected static final Set OLD_FILES = new HashSet<>(); static { @@ -60,22 +60,21 @@ public abstract class BasePPTIteratingTest { protected static final Map> EXCLUDED = new HashMap<>(); - @Parameterized.Parameters(name="{index}: {0}") - public static Iterable files() { + public static Stream files() { String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); if(dataDirName == null) { dataDirName = "test-data"; } - List files = new ArrayList<>(); + List files = new ArrayList<>(); findFile(files, dataDirName + "/slideshow"); - return files; + return files.stream(); } private final PrintStream save = System.out; - @Before + @BeforeEach public void setUpBase() throws UnsupportedEncodingException { // set a higher max allocation limit as some test-files require more IOUtils.setByteArrayMaxOverride(5*1024*1024); @@ -84,7 +83,7 @@ public abstract class BasePPTIteratingTest { System.setOut(new NullPrintStream()); } - @After + @AfterEach public void tearDownBase() { System.setOut(save); @@ -92,21 +91,19 @@ public abstract class BasePPTIteratingTest { IOUtils.setByteArrayMaxOverride(-1); } - private static void findFile(List list, String dir) { + private static void findFile(List list, String dir) { String[] files = new File(dir).list((arg0, arg1) -> arg1.toLowerCase(Locale.ROOT).endsWith(".ppt")); - assertNotNull("Did not find any ppt files in directory " + dir, files); + assertNotNull(files, "Did not find any ppt files in directory " + dir); for(String file : files) { - list.add(new Object[] { new File(dir, file) }); + list.add(Arguments.of(new File(dir, file))); } } - @Parameterized.Parameter - public File file; - - @Test - public void testAllFiles() throws Exception { + @ParameterizedTest + @MethodSource("files") + public void testAllFiles(File file) throws Exception { String fileName = file.getName(); Class t = null; if (EXCLUDED.containsKey(fileName)) { diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPDrawingTextListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPDrawingTextListing.java index 21b63d91ec..48d983280a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPDrawingTextListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPDrawingTextListing.java @@ -17,24 +17,19 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestPPDrawingTextListing extends BasePPTIteratingTest { @Test public void testMain() throws IOException { // calls System.exit(): PPDrawingTextListing.main(new String[0]); - - try { - PPDrawingTextListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> PPDrawingTextListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java index 7ff2349fbd..114f10d2db 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.util.Collections; @@ -24,7 +24,7 @@ import java.util.Set; import org.apache.poi.EmptyFileException; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestPPTXMLDump extends BasePPTIteratingTest { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTListing.java index 4a5b30dff7..aada03506a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTListing.java @@ -16,7 +16,8 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.IOException; @@ -24,20 +25,20 @@ import java.io.PrintStream; import org.apache.poi.EmptyFileException; import org.apache.poi.util.NullPrintStream; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestSLWTListing extends BasePPTIteratingTest { private static PrintStream oldStdErr; - @BeforeClass + @BeforeAll public static void muteStdErr() { oldStdErr = System.err; System.setErr(new NullPrintStream()); } - @AfterClass + @AfterAll public static void restoreStdErr() { System.setErr(oldStdErr); } @@ -45,12 +46,7 @@ public class TestSLWTListing extends BasePPTIteratingTest { @Test public void testMain() throws IOException { // calls System.exit(): SLWTListing.main(new String[0]); - try { - SLWTListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SLWTListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTTextListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTTextListing.java index 83729e2838..ae2cf58558 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTTextListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSLWTTextListing.java @@ -17,24 +17,19 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestSLWTTextListing extends BasePPTIteratingTest { @Test public void testMain() throws IOException { // calls System.exit(): SLWTTextListing.main(new String[0]); - - try { - SLWTTextListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SLWTTextListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideAndNotesAtomListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideAndNotesAtomListing.java index 82f27e546a..395ac33687 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideAndNotesAtomListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideAndNotesAtomListing.java @@ -18,12 +18,13 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestSlideAndNotesAtomListing extends BasePPTIteratingTest { @Test @@ -32,13 +33,7 @@ public class TestSlideAndNotesAtomListing extends BasePPTIteratingTest { SlideAndNotesAtomListing.main(new String[] { HSLFTestDataSamples.getSampleFile("slide_master.ppt").getAbsolutePath() }); - - try { - SlideAndNotesAtomListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SlideAndNotesAtomListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideIdListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideIdListing.java index 4a896323bc..aeae69a5f0 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideIdListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideIdListing.java @@ -18,12 +18,13 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestSlideIdListing extends BasePPTIteratingTest { @Test @@ -32,13 +33,7 @@ public class TestSlideIdListing extends BasePPTIteratingTest { SlideIdListing.main(new String[] { HSLFTestDataSamples.getSampleFile("slide_master.ppt").getAbsolutePath() }); - - try { - SlideIdListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SlideIdListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java index 9a6445e1e2..b1bb6db958 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java @@ -16,7 +16,8 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.FileNotFoundException; @@ -28,7 +29,7 @@ import java.util.Set; import org.apache.poi.EmptyFileException; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSlideShowDumper extends BasePPTIteratingTest { private static final Set FAILING = new HashSet<>(); @@ -47,13 +48,7 @@ public class TestSlideShowDumper extends BasePPTIteratingTest { HSLFTestDataSamples.getSampleFile("slide_master.ppt").getAbsolutePath(), HSLFTestDataSamples.getSampleFile("pictures.ppt").getAbsolutePath() }); - - try { - SlideShowDumper.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SlideShowDumper.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java index dbab32a041..a4ec6ca1f8 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java @@ -16,14 +16,15 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.IOException; import org.apache.poi.EmptyFileException; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSlideShowRecordDumper extends BasePPTIteratingTest { @Test @@ -42,12 +43,7 @@ public class TestSlideShowRecordDumper extends BasePPTIteratingTest { HSLFTestDataSamples.getSampleFile("pictures.ppt").getAbsolutePath() }); - try { - SlideShowRecordDumper.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> SlideShowRecordDumper.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestTextStyleListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestTextStyleListing.java index 84991da755..8ebce9c569 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestTextStyleListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestTextStyleListing.java @@ -17,14 +17,15 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestTextStyleListing extends BasePPTIteratingTest { private static Set FAILING = new HashSet<>(); @@ -35,12 +36,7 @@ public class TestTextStyleListing extends BasePPTIteratingTest { @Test public void testMain() throws IOException { // calls System.exit(): TextStyleListing.main(new String[0]); - try { - TextStyleListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> TextStyleListing.main(new String[]{"invalidfile"})); } @Override @@ -48,7 +44,7 @@ public class TestTextStyleListing extends BasePPTIteratingTest { try { TextStyleListing.main(new String[]{pFile.getAbsolutePath()}); } catch (ArrayIndexOutOfBoundsException e) { - // some corrupted documents currently can cause this excpetion + // some corrupted documents currently can cause this exception if (!FAILING.contains(pFile.getName())) { throw e; } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestUserEditAndPersistListing.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestUserEditAndPersistListing.java index 61a9e99660..c49a4c8a3c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestUserEditAndPersistListing.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestUserEditAndPersistListing.java @@ -17,24 +17,19 @@ package org.apache.poi.hslf.dev; import org.apache.poi.EmptyFileException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; public class TestUserEditAndPersistListing extends BasePPTIteratingTest { @Test public void testMain() throws IOException { // calls System.exit(): UserEditAndPersistListing.main(new String[0]); - - try { - UserEditAndPersistListing.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> UserEditAndPersistListing.main(new String[]{"invalidfile"})); } @Override diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java b/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java index b69fc579f2..39746e2ebd 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.extractor; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.util.StringUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that the QuickButCruddyTextExtractor works correctly @@ -62,7 +62,7 @@ public final class TestCruddyExtractor { "This is page two\nIt has several blocks of text\nNone of them have formatting", }; - @Before + @BeforeEach public void setup() throws Exception { te = new QuickButCruddyTextExtractor(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestExtractor.java b/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestExtractor.java index 9cb01825e6..d787aba7d5 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestExtractor.java @@ -20,10 +20,10 @@ package org.apache.poi.hslf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertContainsIgnoreCase; import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.File; @@ -45,7 +45,7 @@ import org.apache.poi.sl.usermodel.ObjectShape; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that the extractor correctly gets the text out of our sample file @@ -74,19 +74,18 @@ public final class TestExtractor { /** * Where our embeded files live */ - private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - @SuppressWarnings("unchecked") private SlideShowExtractor openExtractor(String fileName) throws IOException { try (InputStream is = slTests.openResourceAsStream(fileName)) { - return new SlideShowExtractor(SlideShowFactory.create(is)); + return new SlideShowExtractor<>(SlideShowFactory.create(is)); } } - + @Test public void testReadSheetText() throws IOException { // Basic 2 page example - try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { + try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { assertEquals(EXPECTED_PAGE1+EXPECTED_PAGE2, ppe.getText()); } @@ -98,7 +97,7 @@ public final class TestExtractor { "Plain Text \n"; // 1 page example with text boxes - try (SlideShowExtractor ppe = openExtractor("with_textbox.ppt")) { + try (SlideShowExtractor ppe = openExtractor("with_textbox.ppt")) { assertEquals(expectText2, ppe.getText()); } } @@ -106,7 +105,7 @@ public final class TestExtractor { @Test public void testReadNoteText() throws IOException { // Basic 2 page example - try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { + try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { ppe.setNotesByDefault(true); ppe.setSlidesByDefault(false); ppe.setMasterByDefault(false); @@ -115,7 +114,7 @@ public final class TestExtractor { } // Other one doesn't have notes - try (SlideShowExtractor ppe = openExtractor("with_textbox.ppt")) { + try (SlideShowExtractor ppe = openExtractor("with_textbox.ppt")) { ppe.setNotesByDefault(true); ppe.setSlidesByDefault(false); ppe.setMasterByDefault(false); @@ -130,7 +129,7 @@ public final class TestExtractor { String[] slText = { EXPECTED_PAGE1, EXPECTED_PAGE2 }; String[] ntText = { NOTES_PAGE1, NOTES_PAGE2 }; - try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { + try (SlideShowExtractor ppe = openExtractor("basic_test_ppt_file.ppt")) { ppe.setSlidesByDefault(true); ppe.setNotesByDefault(false); assertEquals(slText[0] + slText[1], ppe.getText()); @@ -199,10 +198,10 @@ public final class TestExtractor { @Test public void testExtractFromOwnEmbeded() throws IOException { try (SlideShowExtractor ppe = openExtractor("ppt_with_embeded.ppt")) { - List shapes = ppe.getOLEShapes(); - assertEquals("Expected 6 ole shapes", 6, shapes.size()); + List> shapes = ppe.getOLEShapes(); + assertEquals(6, shapes.size(), "Expected 6 ole shapes"); int num_ppt = 0, num_doc = 0, num_xls = 0; - for (ObjectShape ole : shapes) { + for (ObjectShape ole : shapes) { String name = ((HSLFObjectShape)ole).getInstanceName(); InputStream data = ole.getObjectData().getInputStream(); if ("Worksheet".equals(name)) { @@ -220,9 +219,9 @@ public final class TestExtractor { } data.close(); } - assertEquals("Expected 2 embedded Word Documents", 2, num_doc); - assertEquals("Expected 2 embedded Excel Spreadsheets", 2, num_xls); - assertEquals("Expected 2 embedded PowerPoint Presentations", 2, num_ppt); + assertEquals(2, num_doc, "Expected 2 embedded Word Documents"); + assertEquals(2, num_xls, "Expected 2 embedded Excel Spreadsheets"); + assertEquals(2, num_ppt, "Expected 2 embedded PowerPoint Presentations"); } } @@ -232,7 +231,7 @@ public final class TestExtractor { @Test public void test52991() throws IOException { try (SlideShowExtractor ppe = openExtractor("badzip.ppt")) { - for (ObjectShape shape : ppe.getOLEShapes()) { + for (ObjectShape shape : ppe.getOLEShapes()) { IOUtils.copy(shape.getObjectData().getInputStream(), new ByteArrayOutputStream()); } } @@ -243,9 +242,9 @@ public final class TestExtractor { */ @Test public void testWithComments() throws IOException { - try (final SlideShowExtractor ppe = openExtractor("WithComments.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("WithComments.ppt")) { String text = ppe.getText(); - assertFalse("Comments not in by default", text.contains("This is a test comment")); + assertFalse(text.contains("This is a test comment"), "Comments not in by default"); ppe.setCommentsByDefault(true); @@ -255,9 +254,9 @@ public final class TestExtractor { // And another file - try (SlideShowExtractor ppe = openExtractor("45543.ppt")) { + try (SlideShowExtractor ppe = openExtractor("45543.ppt")) { String text = ppe.getText(); - assertFalse("Comments not in by default", text.contains("testdoc")); + assertFalse(text.contains("testdoc"), "Comments not in by default"); ppe.setCommentsByDefault(true); @@ -294,8 +293,8 @@ public final class TestExtractor { private void testHeaderFooterInner(final HSLFSlideShow ppt) throws IOException { try (final SlideShowExtractor ppe = new SlideShowExtractor<>(ppt)) { String text = ppe.getText(); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc")); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase")); + assertFalse(text.contains("testdoc"), "Header shouldn't be there by default\n" + text); + assertFalse(text.contains("test phrase"), "Header shouldn't be there by default\n" + text); ppe.setNotesByDefault(true); text = ppe.getText(); @@ -309,7 +308,7 @@ public final class TestExtractor { String masterTitleText = "This is the Master Title"; String masterRandomText = "This text comes from the Master Slide"; String masterFooterText = "Footer from the master slide"; - try (final SlideShowExtractor ppe = openExtractor("WithMaster.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("WithMaster.ppt")) { ppe.setMasterByDefault(true); String text = ppe.getText(); @@ -329,7 +328,7 @@ public final class TestExtractor { @Test public void testSlideMasterText2() throws IOException { - try (final SlideShowExtractor ppe = openExtractor("bug62591.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("bug62591.ppt")) { ppe.setMasterByDefault(true); String text = ppe.getText(); assertNotContained(text, "Titelmasterformat"); @@ -338,7 +337,7 @@ public final class TestExtractor { @Test public void testMasterText() throws IOException { - try (final SlideShowExtractor ppe = openExtractor("master_text.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("master_text.ppt")) { // Initially not there String text = ppe.getText(); assertFalse(text.contains("Text that I added to the master slide")); @@ -354,7 +353,7 @@ public final class TestExtractor { // Now with another file only containing master text // Will always show up - try (final SlideShowExtractor ppe = openExtractor("WithMaster.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("WithMaster.ppt")) { String masterText = "Footer from the master slide"; String text = ppe.getText(); @@ -368,7 +367,7 @@ public final class TestExtractor { */ @Test public void testChineseText() throws IOException { - try (final SlideShowExtractor ppe = openExtractor("54880_chinese.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("54880_chinese.ppt")) { String text = ppe.getText(); // Check for the english text line @@ -405,7 +404,7 @@ public final class TestExtractor { @Test public void testTable() throws Exception { - try (SlideShowExtractor ppe = openExtractor("54111.ppt")) { + try (SlideShowExtractor ppe = openExtractor("54111.ppt")) { String text = ppe.getText(); String target = "TH Cell 1\tTH Cell 2\tTH Cell 3\tTH Cell 4\n" + "Row 1, Cell 1\tRow 1, Cell 2\tRow 1, Cell 3\tRow 1, Cell 4\n" + @@ -416,7 +415,7 @@ public final class TestExtractor { assertContains(text, target); } - try (SlideShowExtractor ppe = openExtractor("54722.ppt")) { + try (SlideShowExtractor ppe = openExtractor("54722.ppt")) { String text = ppe.getText(); String target = "this\tText\tis\twithin\ta\n" + @@ -428,7 +427,7 @@ public final class TestExtractor { // bug 60003 @Test public void testExtractMasterSlideFooterText() throws Exception { - try (SlideShowExtractor ppe = openExtractor("60003.ppt")) { + try (SlideShowExtractor ppe = openExtractor("60003.ppt")) { ppe.setMasterByDefault(true); String text = ppe.getText(); @@ -438,7 +437,7 @@ public final class TestExtractor { @Test public void testExtractGroupedShapeText() throws Exception { - try (final SlideShowExtractor ppe = openExtractor("bug62092.ppt")) { + try (final SlideShowExtractor ppe = openExtractor("bug62092.ppt")) { final String text = ppe.getText(); //this tests that we're ignoring text shapes at depth=0 @@ -476,7 +475,7 @@ public final class TestExtractor { "Times New Roman", "\t\n ,-./01234679:ABDEFGILMNOPRSTVWabcdefghijklmnoprstuvwxyz\u00F3\u201C\u201D", "Arial", " Lacdilnost" }; - try (SlideShowExtractor ppt = openExtractor("45543.ppt")) { + try (SlideShowExtractor ppt = openExtractor("45543.ppt")) { for (int i=0; iorg.apache.poi.hslf.model. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestFreeform.class, - TestHeadersFooters.class, - TestHyperlink.class, - TestLine.class, - TestMovieShape.class, - TestOleEmbedding.class, - TestPPFont.class, - TestSetBoldItalic.class, - TestShapes.class, - TestSheet.class, - TestSlideChangeNotes.class, - TestSlideMaster.class, - TestSlides.class, - TestTable.class, - TestTextRunReWrite.class -}) -public class AllHSLFModelTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java index 1e3c52ddee..9fca1e4ed9 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.geom.Area; import java.awt.geom.Line2D; @@ -26,7 +26,7 @@ import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import org.apache.poi.hslf.usermodel.HSLFFreeformShape; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test Freeform object. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java index f51930ed54..3c3550fb1f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -36,7 +36,7 @@ import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextShape; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test {@link org.apache.poi.hslf.model.HeadersFooters} object @@ -127,7 +127,7 @@ public final class TestHeadersFooters assertFalse(hd1.isUserDateVisible()); assertNull(hd1.getDateTimeText()); } - + ppt.close(); } @@ -210,7 +210,7 @@ public final class TestHeadersFooters assertTrue(hdd2.isSlideNumberVisible()); assertTrue(hdd2.isFooterVisible()); assertEquals("My slide footer", hdd2.getFooterText()); - + ppt2.close(); ppt1.close(); } @@ -230,7 +230,7 @@ public final class TestHeadersFooters assertEquals("My notes footer", hdd2.getFooterText()); assertTrue(hdd2.isHeaderVisible()); assertEquals("My notes header", hdd2.getHeaderText()); - + ppt2.close(); ppt1.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java index 59a54dfe2e..d41f056042 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java @@ -19,8 +19,8 @@ package org.apache.poi.hslf.model; import static org.apache.poi.hslf.usermodel.HSLFTextParagraph.getRawText; import static org.apache.poi.hslf.usermodel.HSLFTextParagraph.toExternalString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.awt.geom.Rectangle2D; import java.io.IOException; @@ -37,8 +37,7 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFTextBox; import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test Hyperlink. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java index 4643600e5b..2b1965a892 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java @@ -25,7 +25,7 @@ import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test Line shape. @@ -126,7 +126,7 @@ public final class TestLine { line.setLineCompound(LineCompound.DOUBLE); line.setLineWidth(8.0); slide.addShape(line); - + ppt.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java index 7e96707d1b..315ca7198a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java @@ -17,9 +17,9 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; @@ -30,7 +30,7 @@ import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test MovieShape object. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java index 6236f32323..2af1fdaa41 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; @@ -30,37 +30,34 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFObjectData; +import org.apache.poi.hslf.usermodel.HSLFObjectShape; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hslf.usermodel.HSLFObjectShape; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; +/** Tests support for OLE objects. */ public final class TestOleEmbedding { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - /** - * Tests support for OLE objects. - * - * @throws Exception if an error occurs. - */ + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + @Test public void testOleEmbedding2003() throws IOException { HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(_slTests.openResourceAsStream("ole2-embedding-2003.ppt")); // Placeholder EMFs for clients that don't support the OLE components. List pictures = slideShow.getPictureData(); - assertEquals("Should be two pictures", 2, pictures.size()); + assertEquals(2, pictures.size(), "Should be two pictures"); - long[] checkSums = {0xD37A4204l, 0x26A62F68l, 0x82853169l, 0xE0E45D2Bl}; + long[] checkSums = {0xD37A4204L, 0x26A62F68L, 0x82853169L, 0xE0E45D2BL}; int checkId = 0; - + // check for checksum to be uptodate for (HSLFPictureData pd : pictures) { long checkEMF = IOUtils.calculateChecksum(pd.getData()); @@ -69,16 +66,16 @@ public final class TestOleEmbedding { // Actual embedded objects. HSLFObjectData[] objects = slideShow.getEmbeddedObjects(); - assertEquals("Should be two objects", 2, objects.length); + assertEquals(2, objects.length, "Should be two objects"); for (HSLFObjectData od : objects) { long checkEMF = IOUtils.calculateChecksum(od.getInputStream()); assertEquals(checkSums[checkId++], checkEMF); } - + slideShow.close(); } - - + + @Test public void testOLEShape() throws IOException { @@ -112,29 +109,29 @@ public final class TestOleEmbedding { } } - assertEquals("Expected 2 OLE shapes", 2, cnt); + assertEquals(2, cnt, "Expected 2 OLE shapes"); ppt.close(); } - + @Test public void testEmbedding() throws IOException { HSLFSlideShow ppt = new HSLFSlideShow(); - + File pict = POIDataSamples.getSlideShowInstance().getFile("clock.jpg"); HSLFPictureData pictData = ppt.addPicture(pict, PictureType.JPEG); - + InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("Employee.xls"); POIFSFileSystem poiData1 = new POIFSFileSystem(is); is.close(); - + int oleObjectId1 = ppt.addEmbed(poiData1); - + HSLFSlide slide1 = ppt.createSlide(); HSLFObjectShape oleShape1 = new HSLFObjectShape(pictData); oleShape1.setObjectID(oleObjectId1); slide1.addShape(oleShape1); oleShape1.setAnchor(new Rectangle2D.Double(100,100,100,100)); - + // add second slide with different order in object creation HSLFSlide slide2 = ppt.createSlide(); HSLFObjectShape oleShape2 = new HSLFObjectShape(pictData); @@ -142,30 +139,30 @@ public final class TestOleEmbedding { is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleWithImages.xls"); POIFSFileSystem poiData2 = new POIFSFileSystem(is); is.close(); - + int oleObjectId2 = ppt.addEmbed(poiData2); oleShape2.setObjectID(oleObjectId2); slide2.addShape(oleShape2); oleShape2.setAnchor(new Rectangle2D.Double(100,100,100,100)); - + ByteArrayOutputStream bos = new ByteArrayOutputStream(); ppt.write(bos); - + ppt = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); HSLFObjectShape comp = (HSLFObjectShape)ppt.getSlides().get(0).getShapes().get(0); byte[] compData = IOUtils.toByteArray(comp.getObjectData().getInputStream()); - + bos.reset(); poiData1.writeFilesystem(bos); byte[] expData = bos.toByteArray(); - + assertArrayEquals(expData, compData); - + poiData1.close(); poiData2.close(); ppt.close(); } - + } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java index bc4c61c14c..6994a2c13f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java @@ -17,7 +17,7 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -26,7 +26,7 @@ import org.apache.poi.common.usermodel.fonts.FontPitch; import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFFontInfoPredefined; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -57,7 +57,7 @@ public final class TestPPFont { assertEquals(HSLFFontInfoPredefined.WINGDINGS.getTypeface(), font3.getTypeface()); assertEquals(FontCharset.SYMBOL, font3.getCharset()); assertEquals(FontPitch.VARIABLE, font3.getPitch()); - + ppt.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java index e593eb8b56..db0114170e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java @@ -17,13 +17,13 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test setting text properties of newly added TextBoxes diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java index 25f9725ec2..bc4a5f1bf6 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.model; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.awt.Dimension; @@ -56,19 +56,19 @@ import org.apache.poi.hslf.usermodel.HSLFTextShape; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test drawing shapes via Graphics2D */ public final class TestShapes { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); private HSLFSlideShow ppt; private HSLFSlideShow pptB; - @Before + @BeforeEach public void setUp() throws Exception { try (InputStream is1 = _slTests.openResourceAsStream("empty.ppt"); InputStream is2 = _slTests.openResourceAsStream("empty_textbox.ppt")) { @@ -386,14 +386,14 @@ public final class TestShapes { HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(file)); HSLFSlide sl = ss.getSlides().get(0); List sh = sl.getShapes(); - assertEquals("expected four shaped in " + file, 4, sh.size()); + assertEquals(4, sh.size(), "expected four shaped in " + file); //remove all for (int i = 0; i < sh.size(); i++) { boolean ok = sl.removeShape(sh.get(i)); - assertTrue("Failed to delete shape #" + i, ok); + assertTrue(ok, "Failed to delete shape #" + i); } //now Slide.getShapes() should return an empty array - assertEquals("expected 0 shaped in " + file, 0, sl.getShapes().size()); + assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); //serialize and read again. The file should be readable and contain no shapes ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -403,7 +403,7 @@ public final class TestShapes { ss = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); sl = ss.getSlides().get(0); - assertEquals("expected 0 shaped in " + file, 0, sl.getShapes().size()); + assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); ss.close(); } @@ -449,9 +449,9 @@ public final class TestShapes { assertEquals(dgShapesUsed + 1, dg.getNumShapes()); //check that EscherDggRecord is updated - assertEquals("mismatch @"+i, shape.getShapeId() + 1, dgg.getShapeIdMax()); - assertEquals("mismatch @"+i, dggMaxId + 1, dgg.getShapeIdMax()); - assertEquals("mismatch @"+i, dggShapesUsed + 1, dgg.getNumShapesSaved()); + assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @"+i); + assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @"+i); + assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @"+i); dggShapesUsed = dgg.getNumShapesSaved(); dggMaxId = dgg.getShapeIdMax(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java index 1b5aa8dcc5..f0efbc09b7 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -27,7 +27,7 @@ import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.record.ColorSchemeAtom; import org.apache.poi.hslf.record.PPDrawing; import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test common functionality of the Sheet object. @@ -36,7 +36,7 @@ import org.junit.Test; * @author Yegor Kozlov */ public final class TestSheet { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); /** * For each ppt in the test directory check that all sheets are properly initialized @@ -92,7 +92,7 @@ public final class TestSheet { } List shape = sheet.getShapes(); - assertTrue("no shapes", shape != null && !shape.isEmpty()); + assertTrue(shape != null && !shape.isEmpty(), "no shapes"); for (HSLFShape s : shape) { assertNotNull(s.getSpContainer()); assertNotNull(s.getSheet()); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java index 57f6f5adb9..d7d1ab493a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.record.SlideAtom; import org.apache.poi.hslf.usermodel.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that changing a slide's idea of what notes sheet is its works right @@ -35,7 +35,7 @@ public final class TestSlideChangeNotes { // SlideShow primed on the test data private HSLFSlideShow ss; - @Before + @BeforeEach public void init() throws Exception { POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(_slTests.openResourceAsStream("basic_test_ppt_file.ppt")); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java index eb4c368bac..d2d21539c0 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java @@ -21,9 +21,9 @@ import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_TITLE; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.TITLE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -43,7 +43,7 @@ import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.hslf.usermodel.HSLFTitleMaster; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for SlideMaster @@ -103,7 +103,7 @@ public final class TestSlideMaster { return getMasterProp(ppt, masterIdx, txtype, propName, isCharacter).getValue(); } - + /** * Test we can read default text attributes for a title master sheet */ diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java index 5ced9945c8..035731f2fa 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java @@ -17,15 +17,15 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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 org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test adding new slides to a ppt. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java index 265d81af41..640360ea7a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java @@ -17,10 +17,11 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -38,7 +39,7 @@ import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.TableShape; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test Table object. @@ -108,20 +109,20 @@ public final class TestTable { } // Table(rownum, colnum) must throw IllegalArgumentException if any of the arguments is less than 1 - @Test(expected=IllegalArgumentException.class) + @Test public void testIllegalRowCnstruction() throws IOException { try (HSLFSlideShow ppt = new HSLFSlideShow()) { HSLFSlide slide = ppt.createSlide(); - slide.createTable(0, 5); + assertThrows(IllegalArgumentException.class, () -> slide.createTable(0, 5)); } } // Table(rownum, colnum) must throw IllegalArgumentException if any of the arguments is less than 1 - @Test(expected=IllegalArgumentException.class) + @Test public void testIllegalColConstruction() throws IOException { try (HSLFSlideShow ppt = new HSLFSlideShow()) { HSLFSlide slide = ppt.createSlide(); - slide.createTable(5, 0); + assertThrows(IllegalArgumentException.class, () -> slide.createTable(5, 0)); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java index d5343e1f03..3642769ccb 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.model; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -32,8 +32,8 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that if we load something up, get a TextRun, set the text @@ -47,7 +47,7 @@ public final class TestTextRunReWrite { /** * Load up a test PPT file with rich data */ - @Before + @BeforeEach public void setUp() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); String filename = "Single_Coloured_Page_With_Fonts_and_Alignments.ppt"; @@ -63,8 +63,8 @@ public final class TestTextRunReWrite { // Grab the first text run on the first sheet List tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); List tr2 = ss.getSlides().get(0).getTextParagraphs().get(1); - - + + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); @@ -112,7 +112,7 @@ public final class TestTextRunReWrite { oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); assertArrayEquals(_oData, _nData); - + npfs.close(); } @@ -159,7 +159,7 @@ public final class TestTextRunReWrite { // Check that the "PowerPoint Document" sections have the same size DirectoryNode oDir = ss.getSlideShowImpl().getDirectory(); - + DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); assertEquals(oProps.getSize(),nProps.getSize()); @@ -171,7 +171,7 @@ public final class TestTextRunReWrite { oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); assertArrayEquals(_oData, _nData); - + npfs.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java deleted file mode 100644 index 81bcefcb6e..0000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.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.hslf.record; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf.record. - * - * @author Josh Micich - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAnimationInfoAtom.class, - TestCString.class, - TestColorSchemeAtom.class, - TestComment2000.class, - TestComment2000Atom.class, - TestCurrentUserAtom.class, - TestDocument.class, - TestDocumentAtom.class, - TestDocumentEncryptionAtom.class, - TestExControl.class, - TestExHyperlink.class, - TestExHyperlinkAtom.class, - TestExMediaAtom.class, - TestExObjList.class, - TestExObjListAtom.class, - TestExOleObjAtom.class, - TestExOleObjStg.class, - TestExVideoContainer.class, - TestFontCollection.class, - TestHeadersFootersAtom.class, - TestHeadersFootersContainer.class, - TestInteractiveInfo.class, - TestInteractiveInfoAtom.class, - TestNotesAtom.class, - TestRecordContainer.class, - TestRecordTypes.class, - TestSlideAtom.class, - TestSlidePersistAtom.class, - TestSound.class, - TestStyleTextPropAtom.class, - TestTextBytesAtom.class, - TestTextCharsAtom.class, - TestTextHeaderAtom.class, - TestTextRulerAtom.class, - TestTextSpecInfoAtom.class, - TestTxInteractiveInfoAtom.class, - TestTxMasterStyleAtom.class, - TestUserEditAtom.class -}) -public class AllHSLFRecordTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java index e6de0b4952..08c5ff8c62 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link HeadersFootersAtom} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java index 124ece203e..25f94cb9af 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that CString works properly @@ -105,7 +105,7 @@ public final class TestCString { break; } } - assertFalse("Arrays should not be equals", equals); + assertFalse(equals, "Arrays should not be equals"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ca.writeOut(baos); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestColorSchemeAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestColorSchemeAtom.java index c4b6f9ab7f..6cd58a8858 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestColorSchemeAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestColorSchemeAtom.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that ColorSchemAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000.java index 70034ca6b4..f5e158aa2f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertTrue; import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; @@ -29,8 +29,8 @@ import java.util.Date; import java.util.Locale; import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests that Comment2000 works properly. @@ -41,59 +41,59 @@ import org.junit.Test; public final class TestComment2000 { // From a real file private final byte[] data_a = new byte[] { - 0x0F, 00, 0xE0-256, 0x2E, 0x9C-256, 00, 00, 00, - 00, 00, 0xBA-256, 0x0F, 0x14, 00, 00, 00, - 0x44, 00, 0x75, 00, 0x6D, 00, 0x62, 00, - 0x6C, 00, 0x65, 00, 0x64, 00, 0x6F, 00, - 0x72, 00, 0x65, 00, - 0x10, 00, 0xBA-256, 0x0F, 0x4A, 00, 00, 00, - 0x59, 00, 0x65, 00, 0x73, 00, 0x2C, 00, - 0x20, 00, 0x74, 00, 0x68, 00, 0x65, 00, - 0x79, 00, 0x20, 00, 0x63, 00, 0x65, 00, - 0x72, 00, 0x74, 00, 0x61, 00, 0x69, 00, - 0x6E, 00, 0x6C, 00, 0x79, 00, 0x20, 00, - 0x61, 00, 0x72, 00, 0x65, 00, 0x2C, 00, - 0x20, 00, 0x61, 00, 0x72, 00, 0x65, 00, - 0x6E, 00, 0x27, 00, 0x74, 00, 0x20, 00, - 0x74, 00, 0x68, 00, 0x65, 00, 0x79, 00, 0x21, 00, - 0x20, 00, 0xBA-256, 0x0F, 0x02, 00, 00, 00, - 0x44, 00, - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 07, 01, 00, - 02, 00, 0x18, 00, 0x0A, 00, 0x1A, 00, - 0x0F, 00, 0xCD-256, 00, 0x92-256, 00, - 00, 00, 0x92-256, 00, 00, 00 + 0x0F, 0, 0xE0-256, 0x2E, 0x9C-256, 0, 0, 0, + 0, 0, 0xBA-256, 0x0F, 0x14, 0, 0, 0, + 0x44, 0, 0x75, 0, 0x6D, 0, 0x62, 0, + 0x6C, 0, 0x65, 0, 0x64, 0, 0x6F, 0, + 0x72, 0, 0x65, 0, + 0x10, 0, 0xBA-256, 0x0F, 0x4A, 0, 0, 0, + 0x59, 0, 0x65, 0, 0x73, 0, 0x2C, 0, + 0x20, 0, 0x74, 0, 0x68, 0, 0x65, 0, + 0x79, 0, 0x20, 0, 0x63, 0, 0x65, 0, + 0x72, 0, 0x74, 0, 0x61, 0, 0x69, 0, + 0x6E, 0, 0x6C, 0, 0x79, 0, 0x20, 0, + 0x61, 0, 0x72, 0, 0x65, 0, 0x2C, 0, + 0x20, 0, 0x61, 0, 0x72, 0, 0x65, 0, + 0x6E, 0, 0x27, 0, 0x74, 0, 0x20, 0, + 0x74, 0, 0x68, 0, 0x65, 0, 0x79, 0, 0x21, 0, + 0x20, 0, 0xBA-256, 0x0F, 0x02, 0, 0, 0, + 0x44, 0, + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 0x01, 0, 0, 0, 0xD6-256, 0x07, 0x01, 0, + 0x02, 0, 0x18, 0, 0x0A, 0, 0x1A, 0, + 0x0F, 0, 0xCD-256, 0, 0x92-256, 0, + 0, 0, 0x92-256, 0, 0, 0 }; private final byte[] data_b = new byte[] { - 0x0F, 00, 0xE0-256, 0x2E, 0xAC-256, 00, 00, 00, - 00, 00, 0xBA-256, 0x0F, 0x10, 00, 00, 00, - 0x48, 00, 0x6F, 00, 0x67, 00, 0x77, 00, - 0x61, 00, 0x72, 00, 0x74, 00, 0x73, 00, - 0x10, 00, 0xBA-256, 0x0F, 0x5E, 00, 00, 00, - 0x43, 00, 0x6F, 00, 0x6D, 00, 0x6D, 00, - 0x65, 00, 0x6E, 00, 0x74, 00, 0x73, 00, - 0x20, 00, 0x61, 00, 0x72, 00, 0x65, 00, - 0x20, 00, 0x66, 00, 0x75, 00, 0x6E, 00, - 0x20, 00, 0x74, 00, 0x68, 00, 0x69, 00, - 0x6E, 00, 0x67, 00, 0x73, 00, 0x20, 00, - 0x74, 00, 0x6F, 00, 0x20, 00, 0x61, 00, - 0x64, 00, 0x64, 00, 0x20, 00, 0x69, 00, - 0x6E, 00, 0x2C, 00, 0x20, 00, 0x61, 00, - 0x72, 00, 0x65, 00, 0x6E, 00, 0x27, 00, - 0x74, 00, 0x20, 00, 0x74, 00, 0x68, 00, - 0x65, 00, 0x79, 00, 0x3F, 00, - 0x20, 00, 0xBA-256, 0x0F, 0x02, 00, 00, 00, - 0x48, 00, - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 0x07, 01, 00, - 02, 00, 0x18, 00, 0x16, 00, 0x19, 00, 03, - 00, 0xD5-256, 02, 0x0A, 00, 00, 00, - 0x0A, 00, 00, 00 + 0x0F, 0, 0xE0-256, 0x2E, 0xAC-256, 0, 0, 0, + 0, 0, 0xBA-256, 0x0F, 0x10, 0, 0, 0, + 0x48, 0, 0x6F, 0, 0x67, 0, 0x77, 0, + 0x61, 0, 0x72, 0, 0x74, 0, 0x73, 0, + 0x10, 0, 0xBA-256, 0x0F, 0x5E, 0, 0, 0, + 0x43, 0, 0x6F, 0, 0x6D, 0, 0x6D, 0, + 0x65, 0, 0x6E, 0, 0x74, 0, 0x73, 0, + 0x20, 0, 0x61, 0, 0x72, 0, 0x65, 0, + 0x20, 0, 0x66, 0, 0x75, 0, 0x6E, 0, + 0x20, 0, 0x74, 0, 0x68, 0, 0x69, 0, + 0x6E, 0, 0x67, 0, 0x73, 0, 0x20, 0, + 0x74, 0, 0x6F, 0, 0x20, 0, 0x61, 0, + 0x64, 0, 0x64, 0, 0x20, 0, 0x69, 0, + 0x6E, 0, 0x2C, 0, 0x20, 0, 0x61, 0, + 0x72, 0, 0x65, 0, 0x6E, 0, 0x27, 0, + 0x74, 0, 0x20, 0, 0x74, 0, 0x68, 0, + 0x65, 0, 0x79, 0, 0x3F, 0, + 0x20, 0, 0xBA-256, 0x0F, 0x02, 0, 0, 0, + 0x48, 0, + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 0x01, 0, 0, 0, 0xD6-256, 0x07, 0x01, 0, + 0x02, 0, 0x18, 0, 0x16, 0, 0x19, 0, 0x03, + 0, 0xD5-256, 0x02, 0x0A, 0, 0, 0, + 0x0A, 0, 0, 0 }; private static SimpleDateFormat sdf; - @BeforeClass + @BeforeAll public static void initDateFormat() { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); sdf.setTimeZone(LocaleUtil.getUserTimeZone()); @@ -198,7 +198,7 @@ public final class TestComment2000 { break; } } - assertFalse("Arrays should not be equals", equals); + assertFalse(equals, "Arrays should not be equals"); // Check bytes are now the same ByteArrayOutputStream baosa = new ByteArrayOutputStream(); @@ -230,7 +230,7 @@ public final class TestComment2000 { 0x00, (byte)0xBA, 0x0F, 0x02, 0x00, 0x00, 0x00, 0x4E, 0x00, 0x00, 0x00, (byte)0xE1, 0x2E, 0x1C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, (byte)0xD9, 0x07, 0x08, 0x00, 0x01, 0x00, 0x18, 0x00, 0x10, 0x00, 0x1F, 0x00, 0x05, 0x00, (byte)0x80, 0x03, - 0x0A, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 00 + 0x0A, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00 }; Comment2000 ca = new Comment2000(data, 0, data.length); Record[] ch = ca.getChildRecords(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java index 05a3a671b5..77ecc945ad 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java @@ -18,7 +18,7 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; @@ -26,8 +26,8 @@ import java.util.Date; import java.util.Locale; import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests that Comment2000Atom works properly. @@ -52,8 +52,8 @@ public final class TestComment2000Atom { }; private static SimpleDateFormat sdf; - - @BeforeClass + + @BeforeAll public static void initDateFormat() { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); sdf.setTimeZone(LocaleUtil.getUserTimeZone()); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java index e9eff122ab..f6bf8f0bea 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java @@ -17,9 +17,9 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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 java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -29,7 +29,7 @@ import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that CurrentUserAtom works properly. @@ -37,7 +37,7 @@ import org.junit.Test; * @author Nick Burch (nick at torchbox dot com) */ public final class TestCurrentUserAtom { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); /** Not encrypted */ private static final String normalFile = "basic_test_ppt_file.ppt"; /** Encrypted */ @@ -57,35 +57,33 @@ public final class TestCurrentUserAtom { // Round trip POIFSFileSystem poifs = new POIFSFileSystem(); cu.writeToFS(poifs); - + CurrentUserAtom cu2 = new CurrentUserAtom(poifs.getRoot()); assertEquals("Hogwarts", cu2.getLastEditUsername()); assertEquals(0x2942, cu2.getCurrentEditOffset()); - + poifs.close(); } - @Test(expected = EncryptedPowerPointFileException.class) + @Test public void readEnc() throws Exception { - try (POIFSFileSystem fs = new POIFSFileSystem(_slTests.getFile(encFile))) { new CurrentUserAtom(fs.getRoot()); - assertTrue(true); // not yet failed - - new HSLFSlideShowImpl(fs).close(); + assertThrows(EncryptedPowerPointFileException.class, () -> new HSLFSlideShowImpl(fs).close()); } } @Test public void writeNormal() throws Exception { // Get raw contents from a known file - POIFSFileSystem fs = new POIFSFileSystem(_slTests.getFile(normalFile)); - DocumentEntry docProps = (DocumentEntry)fs.getRoot().getEntry("Current User"); - byte[] contents = new byte[docProps.getSize()]; - InputStream in = fs.getRoot().createDocumentInputStream("Current User"); - in.read(contents); - in.close(); - fs.close(); + byte[] contents; + try (POIFSFileSystem fs = new POIFSFileSystem(_slTests.getFile(normalFile))) { + DocumentEntry docProps = (DocumentEntry) fs.getRoot().getEntry("Current User"); + contents = new byte[docProps.getSize()]; + try (InputStream in = fs.getRoot().createDocumentInputStream("Current User")) { + in.read(contents); + } + } // Now build up a new one CurrentUserAtom cu = new CurrentUserAtom(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocument.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocument.java index fa576ced48..1623b61fac 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocument.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocument.java @@ -17,14 +17,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that Document works properly (Also tests Environment while we're at it) @@ -37,7 +37,7 @@ public final class TestDocument { // POIFS primed on the test data private POIFSFileSystem pfs; - @Before + @BeforeEach public void setup() throws Exception { pfs = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); ss = new HSLFSlideShowImpl(pfs); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java index 73aea573c0..52daf6ba95 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that DocumentAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java index 49ac6d39f4..7cb1054209 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java @@ -18,11 +18,10 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -35,7 +34,6 @@ 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.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -48,7 +46,9 @@ import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIDecryptor; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Tests that DocumentEncryption works properly. @@ -56,23 +56,18 @@ import org.junit.Test; public class TestDocumentEncryption { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - @Test - public void cryptoAPIDecryptionOther() throws Exception { - String[] encPpts = { - "Password_Protected-56-hello.ppt", - "Password_Protected-hello.ppt", - "Password_Protected-np-hello.ppt", - }; - + @ParameterizedTest + @ValueSource(strings = { + "Password_Protected-56-hello.ppt", + "Password_Protected-hello.ppt", + "Password_Protected-np-hello.ppt" + }) + public void cryptoAPIDecryptionOther(String pptFile) throws Exception { Biff8EncryptionKey.setCurrentUserPassword("hello"); try { - for (String pptFile : encPpts) { - try (POIFSFileSystem fs = new POIFSFileSystem(slTests.getFile(pptFile), true); - HSLFSlideShow ppt = new HSLFSlideShow(fs)) { - assertTrue(ppt.getSlides().size() > 0); - } catch (EncryptedPowerPointFileException e) { - fail(pptFile + " can't be decrypted"); - } + try (POIFSFileSystem fs = new POIFSFileSystem(slTests.getFile(pptFile), true); + HSLFSlideShow ppt = new HSLFSlideShow(fs)) { + assertTrue(ppt.getSlides().size() > 0); } } finally { Biff8EncryptionKey.setCurrentUserPassword(null); @@ -140,10 +135,10 @@ public class TestDocumentEncryption { } finally { Biff8EncryptionKey.setCurrentUserPassword(null); } - + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); - } - + } + @Test public void cryptoAPIDecryption() throws Exception { // taken from a msdn blog: diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryptionAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryptionAtom.java index 7e394cbdeb..acdec41ef2 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryptionAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryptionAtom.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that DocumentEncryptionAtom works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExControl.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExControl.java index b72bc08dc9..8276536a17 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExControl.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExControl.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link org.apache.poi.hslf.record.ExControl} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java index 064ede9f82..454b2d3d84 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java @@ -18,9 +18,9 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.ByteArrayOutputStream; import java.io.IOException; @@ -30,7 +30,7 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that ExHyperlink works properly. @@ -45,14 +45,14 @@ public final class TestExHyperlink { ); ExHyperlink exHyperlink = new ExHyperlink(exHyperlinkBytes, 0, exHyperlinkBytes.length); - + assertEquals(4055l, exHyperlink.getRecordType()); assertEquals(3, exHyperlink.getExHyperlinkAtom().getNumber()); String expURL = "http://jakarta.apache.org/poi/hssf/"; assertEquals(expURL, exHyperlink.getLinkURL()); assertEquals(expURL, exHyperlink._getDetailsA()); assertEquals(expURL, exHyperlink._getDetailsB()); - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); exHyperlink.writeOut(baos); assertArrayEquals(exHyperlinkBytes, baos.toByteArray()); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java index f7ed7acf9e..7e5b45a517 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that ExHyperlinkAtom works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExMediaAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExMediaAtom.java index 8150941299..556e0c8efe 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExMediaAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExMediaAtom.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link org.apache.poi.hslf.record.HeadersFootersAtom} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjList.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjList.java index e3abda1d11..58290c4c6e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjList.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjList.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that ExObjList works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjListAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjListAtom.java index 7d46ed14b1..70d0786307 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjListAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExObjListAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.apache.poi.ss.formula.functions.BaseTestNumeric.assertEquals; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.apache.poi.ss.formula.functions.BaseTestNumeric; +import org.junit.jupiter.api.Test; /** * Tests that ExObjListAtom works properly. @@ -42,7 +42,7 @@ public class TestExObjListAtom { @Test public void testRecordType() { ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length); - assertEquals(1034L, eoa.getRecordType()); + BaseTestNumeric.assertDouble(1034L, eoa.getRecordType()); } @Test @@ -50,8 +50,8 @@ public class TestExObjListAtom { ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length); ExObjListAtom eob = new ExObjListAtom(data_b, 0, data_b.length); - assertEquals(1, eoa.getObjectIDSeed()); - assertEquals(4, eob.getObjectIDSeed()); + BaseTestNumeric.assertDouble(1, eoa.getObjectIDSeed()); + BaseTestNumeric.assertDouble(4, eob.getObjectIDSeed()); } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjAtom.java index 069405b5b3..6a3f71dcda 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjAtom.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link ExOleObjAtom} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjStg.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjStg.java index c38b215e8a..61c1debb0f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjStg.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExOleObjStg.java @@ -18,10 +18,9 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayOutputStream; import java.io.IOException; @@ -29,8 +28,8 @@ import java.io.InputStream; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests that {@link ExOleObjStg} works properly @@ -40,8 +39,8 @@ public final class TestExOleObjStg { // From a real file (embedded SWF control) // .... private static byte[] data; - - @BeforeClass + + @BeforeAll public static void init() throws IOException { data = org.apache.poi.poifs.storage.RawDataUtil.decompress( "H4sIAAAAAAAAAAFjAZz+EAAREFsBAAAADgAAeJy7cF7wwcKNUg8Z0IAdAzPDv/+cDGxIYoxAzATjCDAwsEDF/"+ @@ -62,12 +61,10 @@ public final class TestExOleObjStg { byte[] oledata = readAll(record.getData()); assertEquals(len, oledata.length); - POIFSFileSystem fs = new POIFSFileSystem(record.getData()); - assertTrue("Constructed POIFS from ExOleObjStg data", true); - DocumentEntry doc = (DocumentEntry)fs.getRoot().getEntry("Contents"); - assertNotNull(doc); - assertTrue("Fetched the Contents stream containing OLE properties", true); - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(record.getData())) { + DocumentEntry doc = (DocumentEntry) fs.getRoot().getEntry("Contents"); + assertNotNull(doc); + } } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java index 0f143e4fff..10b4289ce3 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +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 java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link HeadersFootersAtom} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java index 36bddee8cf..ba5ec7f4f4 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java @@ -17,9 +17,9 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +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 java.io.ByteArrayOutputStream; import java.io.IOException; @@ -30,19 +30,19 @@ import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFFontInfoPredefined; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests {@code FontCollection} and {@code FontEntityAtom} records */ public final class TestFontCollection { private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - + // From a real file private static byte[] data; - - @BeforeClass + + @BeforeAll public static void init() throws IOException { data = RawDataUtil.decompress( "H4sIAAAAAAAAAONnuMruwwAC2/ldgGQIQyZDLkMqQzGDAoMfkC4H0kEM+U"+ @@ -92,7 +92,7 @@ public final class TestFontCollection { byte[] recdata = out.toByteArray(); assertArrayEquals(recdata, data); } - + @Test public void bug61881() throws IOException { try (InputStream is = _slTests.openResourceAsStream("bug61881.ppt")) { diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java index 6819356db2..4f15f3d164 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link HeadersFootersAtom} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java index 3a0c1f5b03..2d94df3cd1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java @@ -18,14 +18,14 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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 java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link HeadersFootersContainer} works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java index 9350039c23..fba0d5802e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java @@ -21,12 +21,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that InteractiveInfoAtom works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java index 86215792ff..3b6f541eba 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that InteractiveInfoAtom works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestNotesAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestNotesAtom.java index 86c8088282..8ad95401ed 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestNotesAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestNotesAtom.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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 java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that NotesAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordContainer.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordContainer.java index 01376c17f9..eb16129256 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordContainer.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordContainer.java @@ -18,18 +18,18 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; +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 java.io.IOException; import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that the helper methods on RecordContainer work properly @@ -39,7 +39,7 @@ public final class TestRecordContainer { private RecordContainer recordContainer; private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - @Before + @BeforeEach public void setUp() throws IOException { // Find a real RecordContainer record InputStream is = slTests.openResourceAsStream("basic_test_ppt_file.ppt"); @@ -54,12 +54,12 @@ public final class TestRecordContainer { } } } - - @After + + @AfterEach public void closeResources() throws IOException { hss.close(); } - + @Test public void testIsAnAtom() { assertFalse( recordContainer.isAnAtom() ); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordTypes.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordTypes.java index be224a9d24..a0af7c8642 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordTypes.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestRecordTypes.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ddf.EscherRecordTypes; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that RecordTypes returns the right records and classes when asked diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlideAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlideAtom.java index 7915346673..23fa873cfa 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlideAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlideAtom.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that SlideAtom works properly @@ -45,7 +45,7 @@ public final class TestSlideAtom { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); assertEquals(1007l, sa.getRecordType()); } - + @Test public void testFlags() { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); @@ -79,7 +79,7 @@ public final class TestSlideAtom { sa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } - + @Test public void testSSSlideInfoAtom() throws IOException { HSLFSlideShow ss1 = new HSLFSlideShow(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlidePersistAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlidePersistAtom.java index 10e4018be2..79abd72937 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlidePersistAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSlidePersistAtom.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that SlidePersistAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSound.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSound.java index f998ef82e4..9a6f3b12f8 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSound.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestSound.java @@ -17,15 +17,15 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.IOException; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests Sound-related records: SoundCollection(2020), Sound(2022) and @@ -59,7 +59,7 @@ public final class TestSound { k++; } } - + assertNotNull(sound); assertEquals(1, k); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestStyleTextPropAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestStyleTextPropAtom.java index 08fae5145d..f52c11c9f5 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestStyleTextPropAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestStyleTextPropAtom.java @@ -17,7 +17,7 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -26,7 +26,7 @@ import java.util.List; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.hslf.model.textproperties.*; import org.apache.poi.util.HexDump; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that StyleTextPropAtom works properly @@ -37,17 +37,17 @@ public final class TestStyleTextPropAtom { /** From a real file: a paragraph with 4 different styles */ private static final byte[] data_a = new byte[] { 0, 0, 0xA1-256, 0x0F, 0x2A, 0, 0, 0, - 0x36, 00, 00, 00, // paragraph is 54 long - 00, 00, // (paragraph reserved field) - 00, 00, 00, 00, // it doesn't have any styles - 0x15, 00, 00, 00, // first char run is 21 long - 00, 00, 00, 00, // it doesn't have any styles - 0x11, 00, 00, 00, // second char run is 17 long - 00, 00, 0x04, 00, // font.color only - 00, 00, 00, 0x05, // blue - 0x10, 00, 00, 00, // third char run is 16 long - 00, 00, 0x04, 00, // font.color only - 0xFF-256, 0x33, 00, 0xFE-256 // red + 0x36, 0, 0, 0, // paragraph is 54 long + 0, 0, // (paragraph reserved field) + 0, 0, 0, 0, // it doesn't have any styles + 0x15, 0, 0, 0, // first char run is 21 long + 0, 0, 0, 0, // it doesn't have any styles + 0x11, 0, 0, 0, // second char run is 17 long + 0, 0, 0x04, 0, // font.color only + 0, 0, 0, 0x05, // blue + 0x10, 0, 0, 0, // third char run is 16 long + 0, 0, 0x04, 0, // font.color only + 0xFF-256, 0x33, 0, 0xFE-256 // red }; private static final int data_a_text_len = 0x36-1; @@ -61,51 +61,51 @@ public final class TestStyleTextPropAtom { */ private static final byte[] data_b = new byte[] { 0, 0, 0xA1-256, 0x0F, 0x80-256, 0, 0, 0, - 0x1E, 00, 00, 00, // paragraph is 30 long - 00, 00, // paragraph reserved field - 00, 0x18, 00, 00, // mask is 0x1800 - 00, 00, // left aligned - 0x50, 00, // line spacing 80 - 0x1C, 00, 00, 00, // paragprah is 28 long - 00, 00, // paragraph reserved field - 00, 0x10, 00, 00, // mask is 0x1000 - 0x50, 00, // line spacing 80 - 0x19, 00, 00, 00, // paragraph is 25 long - 00, 00, // paragraph reserved field - 00, 0x18, 00, 00, // mask is 0x1800 - 02, 00, // right aligned - 0x50, 00, // line spacing 80 - 0x61, 00, 00, 00, // paragraph is 97 long - 00, 00, // paragraph reserved field - 00, 0x18, 00, 00, // mask is 0x1800 - 00, 00, // left aligned - 0x50, 00, // line spacing 80 + 0x1E, 0, 0, 0, // paragraph is 30 long + 0, 0, // paragraph reserved field + 0, 0x18, 0, 0, // mask is 0x1800 + 0, 0, // left aligned + 0x50, 0, // line spacing 80 + 0x1C, 0, 0, 0, // paragprah is 28 long + 0, 0, // paragraph reserved field + 0, 0x10, 0, 0, // mask is 0x1000 + 0x50, 0, // line spacing 80 + 0x19, 0, 0, 0, // paragraph is 25 long + 0, 0, // paragraph reserved field + 0, 0x18, 0, 0, // mask is 0x1800 + 0x02, 0, // right aligned + 0x50, 0, // line spacing 80 + 0x61, 0, 0, 0, // paragraph is 97 long + 0, 0, // paragraph reserved field + 0, 0x18, 0, 0, // mask is 0x1800 + 0, 0, // left aligned + 0x50, 0, // line spacing 80 - 0x1E, 00, 00, 00, // character run is 30 long - 01, 00, 02, 00, // mask is 0x020001 - 01, 00, // char flags 0x0001 = bold - 0x14, 00, // font size 20 - 0x1C, 00, 00, 00, // character run is 28 long - 02, 00, 06, 00, // mask is 0x060002 - 02, 00, // char flags 0x0002 = italic - 0x14, 00, // font size 20 - 00, 00, 00, 05, // colour blue - 0x19, 00, 00, 00, // character run is 25 long - 00, 00, 06, 00, // char flags 0x060000 - 0x14, 00, // font size 20 - 0xFF-256, 0x33, 00, 0xFE-256, // colour red - 0x60, 00, 00, 00, // character run is 96 long - 04, 00, 03, 00, // mask is 0x030004 - 04, 00, // char flags 0x0004 = underlined - 01, 00, // font index is 1 - 0x18, 00, // font size 24 + 0x1E, 0, 0, 0, // character run is 30 long + 0x01, 0, 0x02, 0, // mask is 0x020001 + 0x01, 0, // char flags 0x0001 = bold + 0x14, 0, // font size 20 + 0x1C, 0, 0, 0, // character run is 28 long + 0x02, 0, 0x06, 0, // mask is 0x060002 + 0x02, 0, // char flags 0x0002 = italic + 0x14, 0, // font size 20 + 0, 0, 0, 0x05, // colour blue + 0x19, 0, 0, 0, // character run is 25 long + 0, 0, 0x06, 0, // char flags 0x060000 + 0x14, 0, // font size 20 + 0xFF-256, 0x33, 0, 0xFE-256, // colour red + 0x60, 0, 0, 0, // character run is 96 long + 0x04, 0, 0x03, 0, // mask is 0x030004 + 0x04, 0, // char flags 0x0004 = underlined + 0x01, 0, // font index is 1 + 0x18, 0, // font size 24 - 01, 00, 00, 00, // character run is 1 long - 04, 00, 07, 00, // mask is 0x070004 - 04, 00, // char flags 0x0004 = underlined - 01, 00, // font index is 1 - 0x18, 00, // font size 24 - 0xFF-256, 0x33, 00, 0xFE-256 // colour red + 0x01, 0, 0, 0, // character run is 1 long + 0x04, 0, 0x07, 0, // mask is 0x070004 + 0x04, 0, // char flags 0x0004 = underlined + 0x01, 0, // font index is 1 + 0x18, 0, // font size 24 + 0xFF-256, 0x33, 0, 0xFE-256 // colour red }; private static final int data_b_text_len = 0xB3; @@ -376,7 +376,7 @@ public final class TestStyleTextPropAtom { assertEquals(0x0003, cf_4_1.getValue()); } - @Test(expected=HSLFException.class) + @Test public void testFindAddTextProp() { StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); stpb.setParentTextSize(data_b_text_len); @@ -429,7 +429,7 @@ public final class TestStyleTextPropAtom { assertEquals(new_sa, b_p_2.getTextPropList().get(2)); // Check we get an error with a made up one - b_p_2.addWithName("madeUpOne"); + assertThrows(HSLFException.class, () -> b_p_2.addWithName("madeUpOne")); } /** @@ -692,8 +692,8 @@ public final class TestStyleTextPropAtom { byte[] bytes = out.toByteArray(); assertEquals(expected.length, bytes.length); - assertArrayEquals("Had: " + HexDump.toHex(expected) + "\nand: " + HexDump.toHex(bytes), - expected, bytes); + assertArrayEquals(expected, bytes, + "Had: " + HexDump.toHex(expected) + "\nand: " + HexDump.toHex(bytes)); } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java index a53de76457..864e330570 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that TextBytesAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextCharsAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextCharsAtom.java index 80d861f52b..8fb3ba662a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextCharsAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextCharsAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that TextCharsAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextHeaderAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextHeaderAtom.java index 417ce16693..d28af3f7fe 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextHeaderAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextHeaderAtom.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that TextHeaderAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextRulerAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextRulerAtom.java index df8db98c78..cee16c5d07 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextRulerAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextRulerAtom.java @@ -17,15 +17,15 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.ByteArrayOutputStream; import java.util.List; import org.apache.poi.hslf.model.textproperties.HSLFTabStop; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestTextRulerAtom { diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java index b97f91ad0e..56f841ceb9 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests TextSpecInfoAtom diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java index 41e24e7369..bc28ea9a79 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that TxInteractiveInfoAtom works properly. diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxMasterStyleAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxMasterStyleAtom.java index c08feff3f3..68173a50cd 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxMasterStyleAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTxMasterStyleAtom.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +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.fail; import java.util.ArrayList; import java.util.List; @@ -29,8 +29,8 @@ import org.apache.poi.hslf.model.textproperties.TextProp; import org.apache.poi.hslf.model.textproperties.TextPropCollection; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** @@ -41,7 +41,7 @@ import org.junit.Test; public final class TestTxMasterStyleAtom { private HSLFSlideShow _ppt; - @Before + @BeforeEach public void setUp() { _ppt = new HSLFSlideShow(); } @@ -116,10 +116,8 @@ public final class TestTxMasterStyleAtom { List prstyles = txmaster.getParagraphStyles(); List chstyles = txmaster.getCharacterStyles(); - assertEquals("TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE " + - "must contain styles for 5 indentation levels", 5, prstyles.size()); - assertEquals("TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE " + - "must contain styles for 5 indentation levels", 5, chstyles.size()); + assertEquals(5, prstyles.size(), "TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE must contain styles for 5 indentation levels"); + assertEquals(5, chstyles.size(), "TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE must contain styles for 5 indentation levels"); //paragraph styles props = prstyles.get(0); @@ -129,8 +127,8 @@ public final class TestTxMasterStyleAtom { for (int i = 0; i < prstyles.size(); i++) { - assertNotNull("text.offset is null for indentation level " + i, prstyles.get(i).findByName("text.offset")); - assertNotNull("bullet.offset is null for indentation level " + i, prstyles.get(i).findByName("bullet.offset")); + assertNotNull(prstyles.get(i).findByName("text.offset"), "text.offset is null for indentation level " + i); + assertNotNull(prstyles.get(i).findByName("bullet.offset"), "bullet.offset is null for indentation level " + i); } //character styles @@ -217,22 +215,22 @@ public final class TestTxMasterStyleAtom { cnt++; } } - assertEquals("MainMaster must contain 7 TxMasterStyleAtoms ", 7, cnt); + assertEquals(7, cnt, "MainMaster must contain 7 TxMasterStyleAtoms "); } else if(coreRec.getRecordType() == RecordTypes.Document.typeID){ TxMasterStyleAtom txstyle = null; Document doc = (Document)coreRec; Record[] rec = doc.getEnvironment().getChildRecords(); for (final Record atom : rec) { if (atom instanceof TxMasterStyleAtom) { - assertNull("Document.Environment must contain 1 TxMasterStyleAtom", txstyle); + assertNull(txstyle, "Document.Environment must contain 1 TxMasterStyleAtom"); txstyle = (TxMasterStyleAtom)atom; } } - assertNotNull("TxMasterStyleAtom not found in Document.Environment", txstyle); + assertNotNull(txstyle, "TxMasterStyleAtom not found in Document.Environment"); - assertEquals("Document.Environment must contain TxMasterStyleAtom with type=TextHeaderAtom.OTHER_TYPE", - TextPlaceholder.OTHER.nativeId, txstyle.getTextType()); + assertEquals(TextPlaceholder.OTHER.nativeId, txstyle.getTextType(), + "Document.Environment must contain TxMasterStyleAtom with type=TextHeaderAtom.OTHER_TYPE"); lst.add(txstyle); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java index 85fd287b39..05b43c1d70 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java @@ -18,12 +18,12 @@ package org.apache.poi.hslf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that UserEditAtom works properly diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/AllHSLFUserModelTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/AllHSLFUserModelTests.java deleted file mode 100644 index cf8dc7658d..0000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/AllHSLFUserModelTests.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.hslf.usermodel; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf.usermodel. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAddingSlides.class, - TestBackground.class, - TestBugs.class, - TestCounts.class, - TestMostRecentRecords.class, - TestNotesText.class, - TestPictures.class, - TestReOrderingSlides.class, - TestRecordSetup.class, - TestRichTextRun.class, - TestSheetText.class, - TestSlideOrdering.class, - TestSoundData.class, - TestFontRendering.class, - TestPicture.class, - TestTextRun.class, - TestTextShape.class -}) -public class AllHSLFUserModelTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java index 6466ed38e4..8edabe0cb1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.List; @@ -32,9 +32,9 @@ import org.apache.poi.hslf.record.Document; import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.RecordTypes; import org.apache.poi.hslf.record.UserEditAtom; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow adds additional sheets properly @@ -52,14 +52,14 @@ public final class TestAddingSlides { /** * Create/open the slideshows */ - @Before + @BeforeEach public void setUp() throws IOException { ss_empty = new HSLFSlideShow(); ss_one = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page.ppt"); ss_two = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); } - @After + @AfterEach public void tearDown() throws IOException { ss_two.close(); ss_one.close(); @@ -230,17 +230,8 @@ public final class TestAddingSlides { List s1 = ss_empty.getSlides(); assertEquals(2, s1.size()); - try { - ss_empty.removeSlide(-1); - fail("expected exception"); - } catch (Exception e) { - } - - try { - ss_empty.removeSlide(2); - fail("expected exception"); - } catch (Exception e) { - } + assertThrows(Exception.class, () -> ss_empty.removeSlide(-1)); + assertThrows(Exception.class, () -> ss_empty.removeSlide(2)); assertEquals(1, slide1.getSlideNumber()); @@ -252,12 +243,9 @@ public final class TestAddingSlides { assertEquals(0, slide2.getSlideNumber()); - HSLFSlideShow ss_read = HSLFTestDataSamples - .writeOutAndReadBack(ss_empty); - - List s3 = ss_read.getSlides(); - assertEquals(1, s3.size()); - ss_read.close(); + try (HSLFSlideShow ss_read = HSLFTestDataSamples.writeOutAndReadBack(ss_empty)) { + assertEquals(1, ss_read.getSlides().size()); + } } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBackground.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBackground.java index 8853530f60..97cf3216d4 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBackground.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBackground.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.io.IOException; @@ -35,7 +35,7 @@ import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.Document; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.ShapeType; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java index 1d53ee160c..3694059c36 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java @@ -20,11 +20,12 @@ package org.apache.poi.hslf.usermodel; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.awt.Graphics2D; @@ -85,7 +86,7 @@ import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.StringUtil; import org.apache.poi.util.Units; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Testcases for bugs entered in bugzilla @@ -207,8 +208,6 @@ public final class TestBugs { @Test public void bug41381() throws IOException { try (HSLFSlideShow ppt = open("alterman_security.ppt")) { - assertTrue("No Exceptions while reading file", true); - assertEquals(1, ppt.getSlideMasters().size()); assertEquals(1, ppt.getTitleMasters().size()); boolean isFirst = true; @@ -304,7 +303,7 @@ public final class TestBugs { for (List para : paras) { String text = HSLFTextParagraph.getRawText(para); - assertTrue(text, expected.contains(text)); + assertTrue(expected.contains(text), text); } } } @@ -397,13 +396,13 @@ public final class TestBugs { /** * PowerPoint 95 files should throw a more helpful exception */ - @Test(expected=OldPowerPointFormatException.class) + @Test public void bug41711() throws IOException { // New file is fine open("SampleShow.ppt").close(); // PowerPoint 95 gives an old format exception - open("PPT95.ppt").close(); + assertThrows(OldPowerPointFormatException.class, () -> open("PPT95.ppt").close()); } /** @@ -898,11 +897,11 @@ public final class TestBugs { public void bug59302() throws IOException { //add extraction from PPT Map macros = getMacrosFromHSLF("59302.ppt"); - assertNotNull("couldn't find macros", macros); - assertNotNull("couldn't find second module", macros.get("Module2")); + assertNotNull(macros, "couldn't find macros"); + assertNotNull(macros.get("Module2"), "couldn't find second module"); assertContains(macros.get("Module2"), "newMacro in Module2"); - assertNotNull("couldn't find first module", macros.get("Module1")); + assertNotNull(macros.get("Module1"), "couldn't find first module"); assertContains(macros.get("Module1"), "Italicize"); macros = getMacrosFromHSLF("SimpleMacro.ppt"); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java index baed0386d3..647ce3dbd5 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java @@ -18,13 +18,13 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.List; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow returns the right number of Sheets and MetaSheets @@ -33,7 +33,7 @@ public final class TestCounts { @Test public void testSheetsCount() throws IOException { HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - + List slides = ppt.getSlides(); // Two sheets - master sheet is separate assertEquals(2, slides.size()); @@ -49,14 +49,14 @@ public final class TestCounts { // These are slides 1+2 -> 256+257 assertEquals(256, slides.get(0)._getSheetNumber()); assertEquals(257, slides.get(1)._getSheetNumber()); - + ppt.close(); } @Test public void testNotesCount() throws IOException { HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - + List notes = ppt.getNotes(); // Two sheets -> two notes // Note: there are also notes on the slide master @@ -73,7 +73,7 @@ public final class TestCounts { // They happen to go between the two slides in Ref terms assertEquals(5, notes.get(0)._getSheetRefId()); assertEquals(7, notes.get(1)._getSheetRefId()); - + ppt.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java index c6ac218b5f..b7f9369925 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java @@ -17,8 +17,8 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.awt.Color; import java.awt.Dimension; @@ -43,13 +43,13 @@ import javax.imageio.ImageIO; import org.apache.poi.POIDataSamples; import org.apache.poi.sl.draw.Drawable; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test font rendering of alternative and fallback fonts */ public class TestFontRendering { - private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); // @Ignore2("This fails on some systems because fonts are rendered slightly different") @Test @@ -64,36 +64,36 @@ public class TestFontRendering { // for the junit test not all chars are rendered {"build/scratchpad-test-resources/mona.ttf", "fallback", "Cabin"} }; - + // setup fonts (especially needed, when run under *nix systems) GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Map fontMap = new HashMap<>(); Map fallbackMap = new HashMap<>(); - + for (String[] fontFile : fontFiles) { File f = new File(fontFile[0]); - assumeTrue("necessary font file "+f.getName()+" not downloaded.", f.exists()); - + assumeTrue(f.exists(), "necessary font file "+f.getName()+" not downloaded."); + Font font = Font.createFont(Font.TRUETYPE_FONT, f); ge.registerFont(font); - + Map map = ("mapped".equals(fontFile[1]) ? fontMap : fallbackMap); map.put(fontFile[2], font.getFamily()); } - + InputStream is = slTests.openResourceAsStream("bug55902-mixedFontChineseCharacters.ppt"); HSLFSlideShow ss = new HSLFSlideShow(is); is.close(); - + Dimension pgsize = ss.getPageSize(); - + HSLFSlide slide = ss.getSlides().get(0); - + // render it double zoom = 1; AffineTransform at = new AffineTransform(); at.setToScale(zoom, zoom); - + BufferedImage imgActual = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = imgActual.createGraphics(); graphics.setRenderingHint(Drawable.FONT_FALLBACK, fallbackMap); @@ -102,23 +102,23 @@ public class TestFontRendering { graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - graphics.setTransform(at); + graphics.setTransform(at); graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); - slide.draw(graphics); - + slide.draw(graphics); + BufferedImage imgExpected = ImageIO.read(slTests.getFile("bug55902-mixedChars.png")); DataBufferByte expectedDB = (DataBufferByte)imgExpected.getRaster().getDataBuffer(); DataBufferByte actualDB = (DataBufferByte)imgActual.getRaster().getDataBuffer(); byte[] expectedData = expectedDB.getData(0); byte[] actualData = actualDB.getData(0); - + // allow to find out what the actual difference is in CI where this fails currently if(!Arrays.equals(expectedData, actualData)) { ImageIO.write(imgActual, "PNG", TempFile.createTempFile("TestFontRendering", ".png")); } - - assertArrayEquals("Expected to have matching raster-arrays, but found differences", expectedData, actualData); + + assertArrayEquals(expectedData, actualData, "Expected to have matching raster-arrays, but found differences"); ss.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java index 8e1ad7a928..ca2953ac81 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java @@ -16,8 +16,7 @@ ==================================================================== */ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -25,29 +24,24 @@ import java.io.IOException; import org.apache.poi.sl.usermodel.BaseTestSlideShow; import org.apache.poi.sl.usermodel.SlideShow; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TestHSLFSlideShow extends BaseTestSlideShow { +public class TestHSLFSlideShow extends BaseTestSlideShow { @Override public HSLFSlideShow createSlideShow() { return new HSLFSlideShow(); } - + // make sure junit4 executes this test class @Test public void dummy() { assertNotNull(createSlideShow()); } - public HSLFSlideShow reopen(SlideShow show) { - try { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new HSLFSlideShow(new ByteArrayInputStream(bos.getBuf())); - } catch (IOException e) { - fail(e.getMessage()); - return null; - } + public HSLFSlideShow reopen(SlideShow show) throws IOException { + BufAccessBAOS bos = new BufAccessBAOS(); + show.write(bos); + return new HSLFSlideShow(new ByteArrayInputStream(bos.getBuf())); } private static class BufAccessBAOS extends ByteArrayOutputStream { diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java index 9c305ef6b4..22058e22e1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java @@ -18,7 +18,7 @@ package org.apache.poi.hslf.usermodel; import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHSLFSlideShowFactory extends BaseTestSlideShowFactory { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java index c1a5324612..0f4db784ff 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java @@ -18,12 +18,11 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.Record; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow finds the right records as its most recent ones @@ -34,7 +33,7 @@ public final class TestMostRecentRecords { // SlideShow primed on the test data private HSLFSlideShow ss; - @Before + @BeforeEach public void setup() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java index 0394f07069..7ad10ab71f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.apache.poi.POIDataSamples; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow returns MetaSheets which have the right text in them @@ -31,7 +31,7 @@ public final class TestNotesText { // SlideShow primed on the test data private HSLFSlideShow ss; - @Before + @BeforeEach public void setup() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList.java index 31778e6ba3..6cae0d00e1 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList.java @@ -19,21 +19,27 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.*; +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.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.model.textproperties.TextPFException9; import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.*; +import org.apache.poi.hslf.record.EscherTextboxWrapper; +import org.apache.poi.hslf.record.StyleTextProp9Atom; +import org.apache.poi.hslf.record.StyleTextPropAtom; import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test that checks numbered list functionality. - * + * * @author Alex Nikiforov [mailto:anikif@gmail.com] */ public final class TestNumberedList { @@ -64,7 +70,7 @@ public final class TestNumberedList { assertSame(AutoNumberingScheme.arabicPeriod, autoNumbers[0].getAutoNumberScheme()); assertNull(autoNumbers[1].getAutoNumberScheme()); assertSame(AutoNumberingScheme.alphaLcParenRight, autoNumbers[2].getAutoNumberScheme()); - + List> textParass = s.getTextParagraphs(); assertEquals(2, textParass.size()); @@ -80,7 +86,7 @@ public final class TestNumberedList { "Second paragraph first line c) ;\r" + "Second paragraph second line d) . \r"; assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - + final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); assertEquals(textParass.size(), styleAtoms.length); final EscherTextboxWrapper wrapper = styleAtoms[1]; @@ -120,15 +126,15 @@ public final class TestNumberedList { "follows the design pattern\r" + "Just a test\rWithout any paragraph\r" + "Second paragraph first line c) ;\r" + - "Second paragraph second line d) . \r"; + "Second paragraph second line d) . \r"; assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - + final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); assertEquals(textParass.size(), styleAtoms.length); final EscherTextboxWrapper wrapper = styleAtoms[1]; final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); final List textProps = styleTextPropAtom.getCharacterStyles(); - + assertEquals(33, textProps.get(0).getCharactersCovered()); assertEquals(61, textProps.get(1).getCharactersCovered()); assertEquals(68, textProps.get(2).getCharactersCovered()); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java index 2ec650ea0c..493b60dc27 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java @@ -19,10 +19,10 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.IOException; import java.util.List; @@ -34,7 +34,7 @@ import org.apache.poi.hslf.record.EscherTextboxWrapper; import org.apache.poi.hslf.record.StyleTextProp9Atom; import org.apache.poi.hslf.record.StyleTextPropAtom; import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -44,19 +44,16 @@ import org.junit.Test; * PPT: Missing TextAutoNumberScheme structure providing the style of the number bullets */ public final class TestNumberedList2 { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); @Test public void testNumberedList() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers2.ppt")); - assertTrue("No Exceptions while reading file", true); - - final List slides = ppt.getSlides(); - assertEquals(2, slides.size()); - checkSlide0(slides.get(0)); - checkSlide1(slides.get(1)); - - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers2.ppt"))) { + final List slides = ppt.getSlides(); + assertEquals(2, slides.size()); + checkSlide0(slides.get(0)); + checkSlide1(slides.get(1)); + } } private void checkSlide0(final HSLFSlide s) { @@ -69,14 +66,14 @@ public final class TestNumberedList2 { assertNotNull(numberedListInfoForTextBox1); final TextPFException9[] autoNumbersOfTextBox0 = numberedListInfoForTextBox0.getAutoNumberTypes(); assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used + assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used assertSame(AutoNumberingScheme.arabicPeriod, autoNumbersOfTextBox0[0].getAutoNumberScheme()); final TextPFException9[] autoNumbersOfTextBox1 = numberedListInfoForTextBox1.getAutoNumberTypes(); assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox1[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)6), autoNumbersOfTextBox1[0].getAutoNumberStartNumber());//Default value = 1 will be used + assertEquals(Short.valueOf((short)6), autoNumbersOfTextBox1[0].getAutoNumberStartNumber());//Default value = 1 will be used assertSame(AutoNumberingScheme.arabicPeriod, autoNumbersOfTextBox1[0].getAutoNumberScheme()); - + List> textParass = s.getTextParagraphs(); assertEquals(2, textParass.size()); @@ -90,13 +87,13 @@ public final class TestNumberedList2 { "This would be used as a continuation list on another page\r" + "This list should start with #6"; assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - + final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); assertEquals(textParass.size(), styleAtoms.length); checkSingleRunWrapper(44, styleAtoms[0]); checkSingleRunWrapper(130, styleAtoms[1]); } - + private void checkSlide1(final HSLFSlide s) { final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); assertNotNull(numberedListArray); @@ -105,9 +102,9 @@ public final class TestNumberedList2 { assertNotNull(numberedListInfoForTextBox); final TextPFException9[] autoNumbersOfTextBox = numberedListInfoForTextBox.getAutoNumberTypes(); assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox[0].getAutoNumberStartNumber());//Default value = 1 will be used + assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox[0].getAutoNumberStartNumber());//Default value = 1 will be used assertSame(AutoNumberingScheme.arabicPeriod, autoNumbersOfTextBox[0].getAutoNumberScheme()); - + List> textParass = s.getTextParagraphs(); assertEquals(3, textParass.size()); @@ -120,14 +117,14 @@ public final class TestNumberedList2 { assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); expected = "Second bulleted list \u2013 should appear after numbered list\rMore bullets"; assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(2))); - + final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); assertEquals(textParass.size(), styleAtoms.length); checkSingleRunWrapper(27, styleAtoms[0]); checkSingleRunWrapper(67, styleAtoms[1]); checkSingleRunWrapper(70, styleAtoms[2]); } - + private void checkSingleRunWrapper(final int exceptedLength, final EscherTextboxWrapper wrapper) { final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); final List textProps = styleTextPropAtom.getCharacterStyles(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java index f3a682ffe5..1dcc249584 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java @@ -19,11 +19,11 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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 java.io.IOException; import java.util.List; @@ -35,7 +35,7 @@ import org.apache.poi.hslf.record.EscherTextboxWrapper; import org.apache.poi.hslf.record.StyleTextProp9Atom; import org.apache.poi.hslf.record.StyleTextPropAtom; import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -43,22 +43,20 @@ import org.junit.Test; * if a paragraph has autonumber () * @see * PPT: Missing TextAutoNumberScheme structure providing the style of the number bullets - * + * * @author Alex Nikiforov [mailto:anikif@gmail.com] */ public final class TestNumberedList3 { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); @Test public void testNumberedList() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers3.ppt")); - assertTrue("No Exceptions while reading file", true); - - final List slides = ppt.getSlides(); - assertEquals(1, slides.size()); - final HSLFSlide slide = slides.get(0); - checkSlide(slide); - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers3.ppt"))) { + final List slides = ppt.getSlides(); + assertEquals(1, slides.size()); + final HSLFSlide slide = slides.get(0); + checkSlide(slide); + } } private void checkSlide(final HSLFSlide s) { final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); @@ -68,9 +66,9 @@ public final class TestNumberedList3 { assertNotNull(numberedListInfoForTextBox); final TextPFException9[] autoNumbersOfTextBox0 = numberedListInfoForTextBox.getAutoNumberTypes(); assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used + assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used assertSame(AutoNumberingScheme.arabicPeriod, autoNumbersOfTextBox0[0].getAutoNumberScheme()); - + final List> textParass = s.getTextParagraphs(); assertEquals(3, textParass.size()); assertEquals("Bulleted list\rMore bullets\rNo bullets here", HSLFTextParagraph.getRawText(textParass.get(0))); @@ -85,9 +83,9 @@ public final class TestNumberedList3 { final TextPFException9[] autoNumbers = textParass.get(1).get(0).getStyleTextProp9Atom().getAutoNumberTypes(); assertEquals(1, autoNumbers.length); assertEquals(Short.valueOf((short)1), autoNumbers[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbers[0].getAutoNumberStartNumber());//Default value = 1 will be used + assertEquals(Short.valueOf((short)1), autoNumbers[0].getAutoNumberStartNumber());//Default value = 1 will be used assertSame(AutoNumberingScheme.arabicPeriod, autoNumbersOfTextBox0[0].getAutoNumberScheme()); - + int chCovered = 0; for (HSLFTextParagraph htp : textParass.get(1)) { for (HSLFTextRun htr : htp.getTextRuns()) { @@ -96,9 +94,9 @@ public final class TestNumberedList3 { } } assertEquals(67, chCovered); - + assertTrue(textParass.get(0).get(0).isBullet()); - + final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); assertEquals(textParass.size(), styleAtoms.length); checkSingleRunWrapper(43, styleAtoms[0]); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java index 0b80b6e97c..fd303f3215 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +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 java.awt.Graphics2D; import java.awt.Rectangle; @@ -36,8 +36,8 @@ import javax.imageio.ImageIO; import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Test Picture shape. @@ -45,7 +45,7 @@ import org.junit.Test; public final class TestPicture { private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - @BeforeClass + @BeforeAll public static void disableImageIOCache() { ImageIO.setUseCache(false); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java index 299a71e7fc..d53469b02f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java @@ -17,9 +17,9 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.awt.Dimension; import java.io.ByteArrayInputStream; @@ -41,8 +41,8 @@ import org.apache.poi.sl.image.ImageHeaderPICT; import org.apache.poi.sl.image.ImageHeaderWMF; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.Units; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Test adding/reading pictures @@ -459,7 +459,7 @@ public final class TestPictures { * See "Please remove my file from your svn" on @poi-dev from Dec 12, 2013 */ @Test - @Ignore("requires an internet connection to a 3rd party site") + @Disabled("requires an internet connection to a 3rd party site") // As of 2017-06-20, the file still exists at the specified URL and the test passes. public void testZeroPictureLength() throws IOException { // take the data from www instead of test directory diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java index 0de5029966..ef25304b64 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java @@ -18,16 +18,14 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow can re-order slides properly @@ -48,7 +46,7 @@ public final class TestReOrderingSlides { /** * Create/open the slideshows */ - @Before + @BeforeEach public void setUp() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); @@ -90,7 +88,7 @@ public final class TestReOrderingSlides { assertEquals(256, s1._getSheetNumber()); assertEquals(3, s1._getSheetRefId()); assertEquals(1, s1.getSlideNumber()); - + ss_read.close(); } @@ -261,11 +259,11 @@ public final class TestReOrderingSlides { s1 = ss_three.getSlides().get(0); s2 = ss_three.getSlides().get(1); s3 = ss_three.getSlides().get(2); - + assertEquals(1, s1.getSlideNumber()); assertEquals(2, s2.getSlideNumber()); assertEquals(3, s3.getSlideNumber()); - + assertEquals("Slide 3", ((HSLFTextShape)s1.getShapes().get(0)).getText()); assertEquals("Slide 1", ((HSLFTextShape)s3.getShapes().get(0)).getText()); @@ -294,7 +292,7 @@ public final class TestReOrderingSlides { assertEquals(s3._getSheetNumber(), _s3._getSheetNumber()); assertEquals(s3._getSheetRefId(), _s3._getSheetRefId()); assertEquals(3, s3.getSlideNumber()); - + ss_read.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java index d79f61e411..b66f8bc71f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.record.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that the record setup done by SlideShow @@ -37,7 +37,7 @@ public final class TestRecordSetup { private HSLFSlideShow ss; private HSLFSlideShowImpl hss; - @Before + @BeforeEach public void init() throws Exception { POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java index b697ab10a8..89af70851c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.usermodel; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -35,9 +35,9 @@ import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.SlideListWithText; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test that the friendly getters and setters on RichTextRun @@ -53,27 +53,27 @@ public final class TestRichTextRun { private HSLFSlideShow ssChinese; private static String filenameC; - @Before + @BeforeEach public void setUp() throws IOException { // Basic (non rich) test file ss = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); // Rich test file A ssRichA = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page.ppt"); - + // Rich test file B ssRichB = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt"); - + // Rich test file C - has paragraph styles that run out before // the character ones do filenameC = "ParagraphStylesShorterThanCharStyles.ppt"; ssRichC = HSLFTestDataSamples.getSlideShow(filenameC); - + // Rich test file with Chinese + English text in it ssChinese = HSLFTestDataSamples.getSlideShow("54880_chinese.ppt"); } - @After + @AfterEach public void tearDown() throws IOException { ss.close(); ssRichA.close(); @@ -81,7 +81,7 @@ public final class TestRichTextRun { ssRichC.close(); ssChinese.close(); } - + /** * Test the stuff about getting/setting bold * on a non rich text run @@ -162,13 +162,16 @@ public final class TestRichTextRun { // Start off with rich one // First run has defaults + assertNotNull(rtrRa.getFontSize()); assertEquals(44, rtrRa.getFontSize(), 0); assertEquals(defaultFont, rtrRa.getFontFamily()); // Second is size 20, default font + assertNotNull(rtrRb.getFontSize()); assertEquals(20, rtrRb.getFontSize(), 0); assertEquals(defaultFont, rtrRb.getFontFamily()); // Third is size 24, alt font + assertNotNull(rtrRc.getFontSize()); assertEquals(24, rtrRc.getFontSize(), 0); assertEquals("Times New Roman", rtrRc.getFontFamily()); @@ -182,6 +185,7 @@ public final class TestRichTextRun { // Now do non rich one + assertNotNull(rtr.getFontSize()); assertEquals(44, rtr.getFontSize(), 0); assertEquals(defaultFont, rtr.getFontFamily()); assertEquals(1, ss.getFontCollection().getChildRecords().length); // Default @@ -213,7 +217,7 @@ public final class TestRichTextRun { HSLFSlide slideOne = h.getSlides().get(0); List> textParass = slideOne.getTextParagraphs(); HSLFTextRun rtr = textParass.get(0).get(0).getTextRuns().get(0); - + rtr.setBold(true); rtr.setFontSize(18d); rtr.setFontFamily("Courier"); @@ -221,6 +225,7 @@ public final class TestRichTextRun { // Check it took those assertTrue(rtr.isBold()); + assertNotNull(rtr.getFontSize()); assertEquals(18., rtr.getFontSize(), 0); assertEquals("Courier", rtr.getFontFamily()); @@ -245,6 +250,7 @@ public final class TestRichTextRun { HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); assertTrue(rtrRRa.isBold()); + assertNotNull(rtrRRa.getFontSize()); assertEquals(18., rtrRRa.getFontSize(), 0); assertEquals("Courier", rtrRRa.getFontFamily()); readS.close(); @@ -361,7 +367,6 @@ public final class TestRichTextRun { * SlideListWithText out, and compares it to the write * out of the supplied SlideShow. Also compares the * contents. - * @param s */ private void assertMatchesSLTWC(HSLFSlideShow s) throws IOException { // Grab a new copy of slideshow C @@ -409,11 +414,11 @@ public final class TestRichTextRun { is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT); byte[] raw_ss = IOUtils.toByteArray(is); is.close(); - fs.close(); - + fs.close(); + // different paragraph mask, because of sanitizing raw_ss[169030] = 0x0a; - + // Ensure they're the same assertArrayEquals(raw_file, raw_ss); } @@ -441,57 +446,58 @@ public final class TestRichTextRun { @Test public void testReadParagraphStyles() throws Exception { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("bullets.ppt"); - assertTrue("No Exceptions while reading file", true); + try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("bullets.ppt")) { + HSLFTextParagraph rt; + List> txt; + List slide = ppt.getSlides(); + assertEquals(2, slide.size()); - HSLFTextParagraph rt; - List> txt; - List slide = ppt.getSlides(); - assertEquals(2, slide.size()); + txt = slide.get(0).getTextParagraphs(); + assertEquals(2, txt.size()); - txt = slide.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); + assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); + assertEquals(1, txt.get(0).size()); + rt = txt.get(0).get(0); + assertFalse(rt.isBullet()); - assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(1, txt.get(0).size()); - rt = txt.get(0).get(0); - assertFalse(rt.isBullet()); - - String expected = - "This is a text placeholder that \r" + - "follows the design pattern\r" + - "Defined in the slide master\r" + - "and has bullets by default"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); - assertEquals(4, txt.get(1).size()); - rt = txt.get(1).get(0); - assertEquals('\u2022', (char)rt.getBulletChar()); - assertTrue(rt.isBullet()); + String expected = + "This is a text placeholder that \r" + + "follows the design pattern\r" + + "Defined in the slide master\r" + + "and has bullets by default"; + assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); + assertEquals(4, txt.get(1).size()); + rt = txt.get(1).get(0); + assertNotNull(rt.getBulletChar()); + assertEquals('\u2022', (char) rt.getBulletChar()); + assertTrue(rt.isBullet()); - txt = slide.get(1).getTextParagraphs(); - assertEquals(2, txt.size()); + txt = slide.get(1).getTextParagraphs(); + assertEquals(2, txt.size()); - expected = - "I\u2019m a text box\r" + - "With bullets\r" + - "That follow the design pattern\r" + - "From the slide master"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(4, txt.get(0).size()); - rt = txt.get(0).get(0); - assertTrue(rt.isBullet()); - assertEquals('\u2022', (char)rt.getBulletChar()); + expected = + "I\u2019m a text box\r" + + "With bullets\r" + + "That follow the design pattern\r" + + "From the slide master"; + assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(0))); + assertEquals(4, txt.get(0).size()); + rt = txt.get(0).get(0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getBulletChar()); + assertEquals('\u2022', (char) rt.getBulletChar()); - expected = - "I\u2019m a text box with user-defined\r" + - "bullet character"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); - assertEquals(2, txt.get(1).size()); - rt = txt.get(1).get(0); - assertTrue(rt.isBullet()); - assertEquals('\u263A', (char)rt.getBulletChar()); - ppt.close(); + expected = + "I\u2019m a text box with user-defined\r" + + "bullet character"; + assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); + assertEquals(2, txt.get(1).size()); + rt = txt.get(1).get(0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getBulletChar()); + assertEquals('\u263A', (char) rt.getBulletChar()); + } } @Test @@ -514,10 +520,14 @@ public final class TestRichTextRun { rt.setBulletChar('\u263A'); slide.addShape(shape); + assertNotNull(tr.getFontSize()); assertEquals(42.0, tr.getFontSize(), 0); assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); assertEquals('\u263A', (char)rt.getBulletChar()); shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); @@ -529,10 +539,14 @@ public final class TestRichTextRun { shape = (HSLFTextBox)slide.getShapes().get(0); rt = shape.getTextParagraphs().get(0); tr = rt.getTextRuns().get(0); + assertNotNull(tr.getFontSize()); assertEquals(42.0, tr.getFontSize(), 0); assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); assertEquals('\u263A', (char)rt.getBulletChar()); ppt2.close(); ppt1.close(); @@ -540,80 +554,79 @@ public final class TestRichTextRun { @Test public void testAddText() throws Exception { - HSLFSlideShow ppt1 = HSLFTestDataSamples.getSlideShow("bullets.ppt"); - assertTrue("No Exceptions while reading file", true); + try (HSLFSlideShow ppt1 = HSLFTestDataSamples.getSlideShow("bullets.ppt")) { - HSLFTextParagraph rt; - HSLFTextRun tr; - List> txt; - List slides = ppt1.getSlides(); + HSLFTextParagraph rt; + HSLFTextRun tr; + List> txt; + List slides = ppt1.getSlides(); - assertEquals(2, slides.size()); - txt = slides.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); + assertEquals(2, slides.size()); + txt = slides.get(0).getTextParagraphs(); + assertEquals(2, txt.size()); - assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(1, txt.get(0).size()); - rt = txt.get(0).get(0); - assertFalse(rt.isBullet()); + assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); + assertEquals(1, txt.get(0).size()); + rt = txt.get(0).get(0); + assertFalse(rt.isBullet()); - // Add some new text - HSLFTextParagraph.appendText(txt.get(0), "Foo! I'm new!", true); - assertEquals(2, txt.get(0).size()); + // Add some new text + HSLFTextParagraph.appendText(txt.get(0), "Foo! I'm new!", true); + assertEquals(2, txt.get(0).size()); - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Foo! I'm new!", tr.getRawText()); - tr.setBold(true); - HSLFTextParagraph.storeText(txt.get(0)); + rt = txt.get(0).get(0); + tr = rt.getTextRuns().get(0); + assertFalse(tr.isBold()); + assertEquals("Title text\r", tr.getRawText()); + rt = txt.get(0).get(1); + tr = rt.getTextRuns().get(0); + assertFalse(tr.isBold()); + assertEquals("Foo! I'm new!", tr.getRawText()); + tr.setBold(true); + HSLFTextParagraph.storeText(txt.get(0)); - // And some more, attributes will be copied from previous run - HSLFTextParagraph.appendText(txt.get(0), "Me too!", true); - HSLFTextParagraph.storeText(txt.get(0)); - assertEquals(3, txt.get(0).size()); - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Foo! I'm new!\r", tr.getRawText()); - rt = txt.get(0).get(2); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Me too!", tr.getRawText()); + // And some more, attributes will be copied from previous run + HSLFTextParagraph.appendText(txt.get(0), "Me too!", true); + HSLFTextParagraph.storeText(txt.get(0)); + assertEquals(3, txt.get(0).size()); + rt = txt.get(0).get(0); + tr = rt.getTextRuns().get(0); + assertFalse(tr.isBold()); + assertEquals("Title text\r", tr.getRawText()); + rt = txt.get(0).get(1); + tr = rt.getTextRuns().get(0); + assertTrue(tr.isBold()); + assertEquals("Foo! I'm new!\r", tr.getRawText()); + rt = txt.get(0).get(2); + tr = rt.getTextRuns().get(0); + assertTrue(tr.isBold()); + assertEquals("Me too!", tr.getRawText()); - // Save and re-open - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - slides = ppt2.getSlides(); + // Save and re-open + try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) { + slides = ppt2.getSlides(); - assertEquals(2, slides.size()); + assertEquals(2, slides.size()); - txt = slides.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); - assertEquals(3, txt.get(0).size()); - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Foo! I'm new!\r", tr.getRawText()); - rt = txt.get(0).get(2); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Me too!", tr.getRawText()); - ppt2.close(); - ppt1.close(); + txt = slides.get(0).getTextParagraphs(); + assertEquals(2, txt.size()); + assertEquals(3, txt.get(0).size()); + rt = txt.get(0).get(0); + tr = rt.getTextRuns().get(0); + assertFalse(tr.isBold()); + assertEquals("Title text\r", tr.getRawText()); + rt = txt.get(0).get(1); + tr = rt.getTextRuns().get(0); + assertTrue(tr.isBold()); + assertEquals("Foo! I'm new!\r", tr.getRawText()); + rt = txt.get(0).get(2); + tr = rt.getTextRuns().get(0); + assertTrue(tr.isBold()); + assertEquals("Me too!", tr.getRawText()); + } + } } - + @Test public void testChineseParagraphs() { List rts; @@ -623,27 +636,27 @@ public final class TestRichTextRun { // One slide assertEquals(1, slides.size()); - + // One block of text within that txt = slides.get(0).getTextParagraphs(); assertEquals(1, txt.size()); - + // One rich block of text in that - text is all the same style // TODO Is this completely correct? rts = txt.get(0).get(0).getTextRuns(); assertEquals(1, rts.size()); rt = rts.get(0); - + // Check we can get the english text out of that String text = rt.getRawText(); assertContains(text, "Single byte"); // And the chinese assertContains(txt.get(0).get(3).getTextRuns().get(0).getRawText(), "\uff8a\uff9d\uff76\uff78"); - + // It isn't bold or italic assertFalse(rt.isBold()); assertFalse(rt.isItalic()); - + // Font is Calibri assertEquals("Calibri", rt.getFontFamily()); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java index 7d2e6ed267..c46dd87f0c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java @@ -17,15 +17,15 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.List; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow returns Sheets which have the right text in them @@ -34,16 +34,16 @@ public final class TestSheetText { // SlideShow primed on the test data private HSLFSlideShow ss; - @Before + @BeforeEach public void init() throws IOException { ss = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); } - @After + @AfterEach public void tearDown() throws IOException { ss.close(); } - + @Test public void testSheetOne() { HSLFSheet slideOne = ss.getSlides().get(0); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java index d4a6e49c85..ccd3d90ee6 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java @@ -17,15 +17,15 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.List; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that SlideShow returns Sheets in the right order @@ -36,13 +36,13 @@ public final class TestSlideOrdering { // Complex slideshow, record order doesn't match slide order private HSLFSlideShow ssB; - @Before + @BeforeEach public void init() throws IOException { ssA = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); ssB = HSLFTestDataSamples.getSlideShow("incorrect_slide_order.ppt"); } - @After + @AfterEach public void tearDown() throws IOException { ssA.close(); ssB.close(); @@ -91,7 +91,7 @@ public final class TestSlideOrdering { assertEquals(titles.length, slide.size()); for (int i = 0; i < slide.size(); i++) { String title = slide.get(i).getTitle(); - assertEquals("Wrong slide title in " + filename, titles[i], title); + assertEquals(titles[i], title, "Wrong slide title in " + filename); } ppt.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java index 8a47f6568b..112e35fbe0 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java @@ -17,11 +17,11 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test reading sound data from a ppt @@ -38,7 +38,7 @@ public final class TestSoundData { HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("sound.ppt"); HSLFSoundData[] sound = ppt.getSoundData(); - assertEquals("Expected 1 sound", 1, sound.length); + assertEquals(1, sound.length, "Expected 1 sound"); assertArrayEquals(ref_data, sound[0].getData()); ppt.close(); diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java index 7fe7d269f5..40d7749af8 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java @@ -19,10 +19,10 @@ package org.apache.poi.hslf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.awt.Color; import java.awt.geom.Rectangle2D; @@ -34,7 +34,7 @@ import java.util.List; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.sl.draw.DrawTableShape; import org.apache.poi.sl.usermodel.StrokeStyle; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -50,6 +50,7 @@ public class TestTable { for (int row=0; row slides = ppt.getSlides(); - assertEquals(1, slides.size()); - checkSlide(slides.get(0)); - ppt.close(); + try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("54111.ppt")) { + List slides = ppt.getSlides(); + assertEquals(1, slides.size()); + checkSlide(slides.get(0)); + } } private void checkSlide(final HSLFSlide s) { @@ -94,9 +95,13 @@ public class TestTable { assertEquals(4, table.getNumberOfColumns()); assertEquals(6, table.getNumberOfRows()); for (int x = 0; x < 4; x ++) { - assertEquals("TH Cell " + (x + 1), HSLFTextParagraph.getRawText(table.getCell(0, x).getTextParagraphs())); + HSLFTableCell c = table.getCell(0, x); + assertNotNull(c); + assertEquals("TH Cell " + (x + 1), HSLFTextParagraph.getRawText(c.getTextParagraphs())); for (int y = 1; y < 6; y++) { - assertEquals("Row " + y + ", Cell " + (x + 1), table.getCell(y, x).getText()); + c = table.getCell(y, x); + assertNotNull(c); + assertEquals("Row " + y + ", Cell " + (x + 1), c.getText()); } } } @@ -112,6 +117,7 @@ public class TestTable { for (int row=0; rowTextShape and its sub-classes @@ -77,7 +77,7 @@ public final class TestTextShape { List lst1 = new ArrayList<>(); HSLFSlide slide = ppt.getSlides().get(0); for (HSLFShape shape : slide.getShapes()) { - assertTrue("Expected TextShape but found " + shape.getClass().getName(), shape instanceof HSLFTextShape); + assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName()); HSLFTextShape tx = (HSLFTextShape)shape; List paras = tx.getTextParagraphs(); assertNotNull(paras); @@ -196,7 +196,7 @@ public final class TestTextShape { assertEquals(28.34, tx.getRightInset(), 0.01); assertEquals(3.6, tx.getTopInset(), 0); assertEquals(3.6, tx.getBottomInset(), 0); - + ppt.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java b/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java index 776da2fc54..8e8bdeccc8 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java @@ -18,15 +18,15 @@ package org.apache.poi.hslf.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests that SystemTimeUtils works properly. @@ -49,8 +49,8 @@ public final class TestSystemTimeUtils { }; private static SimpleDateFormat sdf; - - @BeforeClass + + @BeforeAll public static void initDateFormat() { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); sdf.setTimeZone(LocaleUtil.getUserTimeZone()); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/AllHSMFTests.java b/src/scratchpad/testcases/org/apache/poi/hsmf/AllHSMFTests.java deleted file mode 100644 index d0d057c28f..0000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/AllHSMFTests.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.hsmf; - -import org.apache.poi.hsmf.datatypes.TestChunkData; -import org.apache.poi.hsmf.datatypes.TestSorters; -import org.apache.poi.hsmf.datatypes.TestTypes; -import org.apache.poi.hsmf.extractor.TestOutlookTextExtractor; -import org.apache.poi.hsmf.parsers.TestPOIFSChunkParser; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBasics.class, - TestBlankFileRead.class, - TestSimpleFileRead.class, - TestOutlook30FileRead.class, - TestFileWithAttachmentsRead.class, - TestChunkData.class, - TestTypes.class, - TestSorters.class, - TestOutlookTextExtractor.class, - TestPOIFSChunkParser.class, - TestMessageSubmissionChunkY2KRead.class, - TestMessageSubmissionChunk.class, - TestExtractEmbeddedMSG.class, - Test7BitCodepage.class -}) -public class AllHSMFTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/Test7BitCodepage.java b/src/scratchpad/testcases/org/apache/poi/hsmf/Test7BitCodepage.java index 6bc9e3530a..a30a22c43a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/Test7BitCodepage.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/Test7BitCodepage.java @@ -17,14 +17,14 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import org.apache.poi.POIDataSamples; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests to verify if code page for general properties like subject, @@ -40,7 +40,7 @@ public final class Test7BitCodepage { /** * Initialize this test, load up the messages. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); ascii_cp1251_lcid1049 = new MAPIMessage(samples.openResourceAsStream("ASCII_CP1251_LCID1049.msg")); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBasics.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestBasics.java index ffeab21c8c..077c290849 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBasics.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestBasics.java @@ -19,18 +19,18 @@ package org.apache.poi.hsmf; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.IOException; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests to verify that we can perform basic opperations on @@ -49,7 +49,7 @@ public final class TestBasics { /** * Initialize this test, load up the blank.msg mapi message. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); simple = new MAPIMessage(samples.openResourceAsStream("simple_test_msg.msg")); @@ -105,16 +105,10 @@ public final class TestBasics { assertStartsWith(simple.getHeaders()[25], "X-Antivirus-Scanner: Clean"); // Quick doesn't have them - try { - quick.getHeaders(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) {} + assertThrows(ChunkNotFoundException.class, quick::getHeaders); // Attachments doesn't have them - try { - attachments.getHeaders(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) {} + assertThrows(ChunkNotFoundException.class, attachments::getHeaders); // Outlook30 has some assertEquals(33, outlook30.getHeaders().length); @@ -165,26 +159,14 @@ public final class TestBasics { @Test public void testMissingChunks() throws Exception { assertFalse(attachments.isReturnNullOnMissingChunk()); - - try { - attachments.getHtmlBody(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) { - // Good - } + assertThrows(ChunkNotFoundException.class, attachments::getHtmlBody); attachments.setReturnNullOnMissingChunk(true); assertNull(attachments.getHtmlBody()); attachments.setReturnNullOnMissingChunk(false); - - try { - attachments.getHtmlBody(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) { - // Good - } + assertThrows(ChunkNotFoundException.class, attachments::getHtmlBody); } /** @@ -194,19 +176,8 @@ public final class TestBasics { @Test public void testMissingAddressChunk() throws Exception { assertFalse(noRecipientAddress.isReturnNullOnMissingChunk()); - - try { - noRecipientAddress.getRecipientEmailAddress(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) { - // Good - } - try { - noRecipientAddress.getRecipientEmailAddressList(); - fail("expected ChunkNotFoundException"); - } catch(ChunkNotFoundException e) { - // Good - } + assertThrows(ChunkNotFoundException.class, noRecipientAddress::getRecipientEmailAddress); + assertThrows(ChunkNotFoundException.class, noRecipientAddress::getRecipientEmailAddressList); noRecipientAddress.setReturnNullOnMissingChunk(true); @@ -258,13 +229,10 @@ public final class TestBasics { // Check with a file that has no headers - try { - chinese.getHeaders(); - fail("File doesn't have headers!"); - } catch(ChunkNotFoundException e) {} + assertThrows(ChunkNotFoundException.class, chinese::getHeaders, "File doesn't have headers!"); String html = chinese.getHtmlBody(); - assertTrue("Charset not found:\n" + html, html.contains("text/html; charset=big5")); + assertTrue(html.contains("text/html; charset=big5"), "Charset not found:\n" + html); // Defaults to CP1251 assertEquals("CP1252", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java index 256ed5ced3..a7ec74f74c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java @@ -17,14 +17,15 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** @@ -36,7 +37,7 @@ public final class TestBlankFileRead { /** * Initialize this test, load up the blank.msg mapi message. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); mapiMessage = new MAPIMessage(samples.openResourceAsStream("blank.msg")); @@ -45,9 +46,9 @@ public final class TestBlankFileRead { /** * Check if we can read the body of the blank message, we expect "". */ - @Test(expected = ChunkNotFoundException.class) - public void testReadBody() throws ChunkNotFoundException { - mapiMessage.getTextBody(); + @Test + public void testReadBody() { + assertThrows(ChunkNotFoundException.class, mapiMessage::getTextBody); } @@ -76,9 +77,9 @@ public final class TestBlankFileRead { /** * Test to see if we can read the FROM Chunk. */ - @Test(expected = ChunkNotFoundException.class) - public void testReadDisplayFrom() throws ChunkNotFoundException { - mapiMessage.getDisplayFrom(); + @Test + public void testReadDisplayFrom() { + assertThrows(ChunkNotFoundException.class, mapiMessage::getDisplayFrom); } /** @@ -106,8 +107,8 @@ public final class TestBlankFileRead { /** * Check if we can read the subject line of the blank message, we expect "" */ - @Test(expected = ChunkNotFoundException.class) - public void testReadConversationTopic() throws ChunkNotFoundException { - mapiMessage.getConversationTopic(); + @Test + public void testReadConversationTopic() { + assertThrows(ChunkNotFoundException.class, mapiMessage::getConversationTopic); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java index d44145aedc..4e459c807e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java @@ -17,8 +17,8 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -45,9 +45,9 @@ import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.EntryUtils; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestExtractEmbeddedMSG { private static MAPIMessage pdfMsgAttachments; @@ -57,13 +57,13 @@ public class TestExtractEmbeddedMSG { * * @throws Exception */ - @BeforeClass + @BeforeAll public static void setUp() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); pdfMsgAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_msg_pdf.msg")); } - @AfterClass + @AfterAll public static void tearDown() throws IOException { pdfMsgAttachments.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java index 5933e70dbf..5252f9193e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java @@ -17,19 +17,19 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests to verify that we can read attachments from msg file @@ -42,7 +42,7 @@ public class TestFileWithAttachmentsRead { /** * Initialize this test, load up the attachment_test_msg.msg mapi message. */ - @BeforeClass + @BeforeAll public static void setUp() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); twoSimpleAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_test_msg.msg")); @@ -50,7 +50,7 @@ public class TestFileWithAttachmentsRead { inlineImgMsgAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_msg_inlineImg.msg")); } - @AfterClass + @AfterAll public static void tearDown() throws IOException { twoSimpleAttachments.close(); pdfMsgAttachments.close(); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java index c559407a1a..f3b27809b7 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java @@ -18,10 +18,10 @@ package org.apache.poi.hsmf; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -45,9 +45,9 @@ import org.apache.poi.hsmf.dev.HSMFDump; import org.apache.poi.hsmf.extractor.OutlookTextExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests that we can read fixed sized properties, as well as variable @@ -66,7 +66,7 @@ public final class TestFixedSizedProperties { /** * Initialize this test, load up the messages. */ - @BeforeClass + @BeforeAll public static void initMapi() throws Exception { POIDataSamples samples = POIDataSamples.getHSMFInstance(); fsMessageSucceeds = new POIFSFileSystem(samples.getFile(messageSucceeds)); @@ -83,7 +83,7 @@ public final class TestFixedSizedProperties { } - @AfterClass + @AfterAll public static void closeFS() throws Exception { LocaleUtil.setUserTimeZone(userTimeZone); fsMessageSucceeds.close(); @@ -99,10 +99,10 @@ public final class TestFixedSizedProperties { Map> props; props = mapiMessageSucceeds.getMainChunks().getProperties(); - assertTrue(props.toString(), props.size() > 10); + assertTrue(props.size() > 10, props.toString()); props = mapiMessageFails.getMainChunks().getProperties(); - assertTrue(props.toString(), props.size() > 10); + assertTrue(props.size() > 10, props.toString()); } /** @@ -121,20 +121,20 @@ public final class TestFixedSizedProperties { seenTypes.add(pv.getClass()); } } - assertTrue(seenTypes.toString(), seenTypes.size() > 3); - assertTrue(seenTypes.toString(), seenTypes.contains(LongPropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(TimePropertyValue.class)); - assertFalse(seenTypes.toString(), seenTypes.contains(ChunkBasedPropertyValue.class)); + assertTrue(seenTypes.size() > 3, seenTypes.toString()); + assertTrue(seenTypes.contains(LongPropertyValue.class), seenTypes.toString()); + assertTrue(seenTypes.contains(TimePropertyValue.class), seenTypes.toString()); + assertFalse(seenTypes.contains(ChunkBasedPropertyValue.class), seenTypes.toString()); // Ask for the raw values seenTypes.clear(); for (PropertyValue pv : mainChunks.getRawProperties().values()) { seenTypes.add(pv.getClass()); } - assertTrue(seenTypes.toString(), seenTypes.size() > 3); - assertTrue(seenTypes.toString(), seenTypes.contains(LongPropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(TimePropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(ChunkBasedPropertyValue.class)); + assertTrue(seenTypes.size() > 3, seenTypes.toString()); + assertTrue(seenTypes.contains(LongPropertyValue.class), seenTypes.toString()); + assertTrue(seenTypes.contains(TimePropertyValue.class), seenTypes.toString()); + assertTrue(seenTypes.contains(ChunkBasedPropertyValue.class), seenTypes.toString()); } /** diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java index e82f0b5dd0..8c1bdf4c9e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java @@ -17,16 +17,16 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.util.Calendar; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestMessageSubmissionChunk { @@ -36,7 +36,7 @@ public final class TestMessageSubmissionChunk { /** * Initialise this test, load up the test messages. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); this.mapiMessageExtraHyphenSubmissionChunk = new MAPIMessage(samples.openResourceAsStream("message_extra_hyphen_submission_chunk.msg")); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java index bec75504c1..d95dfcc36d 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java @@ -17,15 +17,15 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.Calendar; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestMessageSubmissionChunkY2KRead { @@ -36,7 +36,7 @@ public final class TestMessageSubmissionChunkY2KRead { /** * Initialise this test, load up the three test messages. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); mapiMessage1979 = new MAPIMessage(samples.openResourceAsStream("message_1979.msg")); diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestNameIdChunks.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestNameIdChunks.java index 125250be20..c3ddf2b7fc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestNameIdChunks.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestNameIdChunks.java @@ -19,17 +19,17 @@ package org.apache.poi.hsmf; import static org.apache.poi.hsmf.datatypes.NameIdChunks.PredefinedPropertySet.PSETID_COMMON; import static org.apache.poi.hsmf.datatypes.NameIdChunks.PropertySetType.PS_PUBLIC_STRINGS; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.StringChunk; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests to verify that we can read properties identified by name or id in property sets. @@ -40,7 +40,7 @@ public class TestNameIdChunks { /** * Initialize this test, load up the keywords.msg mapi message. */ - @BeforeClass + @BeforeAll public static void setUp() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); try (InputStream is = samples.openResourceAsStream("keywords.msg")) { @@ -48,7 +48,7 @@ public class TestNameIdChunks { } } - @AfterClass + @AfterAll public static void tearDown() throws IOException { keywordsMsg.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java index ce8527f665..638b20f42f 100644 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java +++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java @@ -17,16 +17,16 @@ package org.apache.poi.hsmf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.POIDataSamples; import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests to verify that we can still work on the newer Outlook 3.0 files. @@ -37,7 +37,7 @@ public final class TestOutlook30FileRead { /** * Initialize this test, load up the blank.msg mapi message. */ - @Before + @BeforeEach public void setup() throws IOException { POIDataSamples samples = POIDataSamples.getHSMFInstance(); this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("outlook_30_msg.msg")); @@ -135,7 +135,7 @@ public final class TestOutlook30FileRead { assertNotNull(html); assertNotNull(rtf); - assertTrue("Wrong text:\n" + html, html.startsWith(" failingFiles = Arrays.asList( + private static final List failingFiles = Arrays.asList( /* not failing, but requires more memory */ "ex45698-22488.xls" ); - @Parameterized.Parameters(name="{index}: {0}") - public static Iterable files() { - List files = new ArrayList<>(); + public static Stream files() { + List files = new ArrayList<>(); File directory = POIDataSamples.getDocumentInstance().getFile( "../spreadsheet" ); - for ( final File child : directory.listFiles((dir,name) -> name.endsWith( ".xls" ) && !failingFiles.contains( name ))) { - files.add(new Object[] { child }); + for ( final File child : Objects.requireNonNull(directory.listFiles((dir, name) -> name.endsWith(".xls") && !failingFiles.contains(name)))) { + files.add(Arguments.of(child)); } - return files; + return files.stream(); } - - @Parameterized.Parameter - public File child; - - @Test - public void testFo() throws Exception + @ParameterizedTest + @MethodSource("files") + public void testFo(File child) throws Exception { HSSFWorkbook workbook; try { @@ -88,8 +85,9 @@ public class TestExcelConverterSuite assertNotNull(stringWriter.toString()); } - @Test - public void testHtml() throws Exception + @ParameterizedTest + @MethodSource("files") + public void testHtml(File child) throws Exception { HSSFWorkbook workbook; try { diff --git a/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java b/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java index 1e2b464015..ebb829a9b3 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java +++ b/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java @@ -18,7 +18,8 @@ package org.apache.poi.hwmf; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.FileInputStream; @@ -36,8 +37,8 @@ import org.apache.poi.hwmf.record.HwmfText; import org.apache.poi.hwmf.usermodel.HwmfPicture; import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.RecordFormatException; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestHwmfParsing { @@ -56,16 +57,16 @@ public class TestHwmfParsing { } } - @Test(expected = RecordFormatException.class) + @Test public void testInfiniteLoop() throws Exception { try (InputStream is = samples.openResourceAsStream("61338.wmf")) { - new HwmfPicture(is); + assertThrows(RecordFormatException.class, () -> new HwmfPicture(is)); } } @Test - @Ignore("If we decide we can use common crawl file specified, we can turn this back on") + @Disabled("If we decide we can use common crawl file specified, we can turn this back on") public void testCyrillic() throws Exception { //TODO: move test file to framework and fix this File dir = new File("C:/somethingOrOther"); diff --git a/src/scratchpad/testcases/org/apache/poi/hwmf/TestRasterOp.java b/src/scratchpad/testcases/org/apache/poi/hwmf/TestRasterOp.java index 4723f816ed..e064c46485 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwmf/TestRasterOp.java +++ b/src/scratchpad/testcases/org/apache/poi/hwmf/TestRasterOp.java @@ -17,10 +17,10 @@ package org.apache.poi.hwmf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwmf.record.HwmfTernaryRasterOp; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestRasterOp { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java b/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java deleted file mode 100644 index 53ab56719d..0000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.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.hwpf; - -import org.apache.poi.hwpf.converter.AbstractWordUtilsTest; -import org.apache.poi.hwpf.converter.TestWordToFoConverter; -import org.apache.poi.hwpf.converter.TestWordToHtmlConverter; -import org.apache.poi.hwpf.extractor.TestDifferentRoutes; -import org.apache.poi.hwpf.extractor.TestWordExtractor; -import org.apache.poi.hwpf.extractor.TestWordExtractorBugs; -import org.apache.poi.hwpf.model.TestBookmarksTables; -import org.apache.poi.hwpf.model.TestCHPBinTable; -import org.apache.poi.hwpf.model.TestDocumentProperties; -import org.apache.poi.hwpf.model.TestFileInformationBlock; -import org.apache.poi.hwpf.model.TestFontTable; -import org.apache.poi.hwpf.model.TestListTables; -import org.apache.poi.hwpf.model.TestNotesTables; -import org.apache.poi.hwpf.model.TestPAPBinTable; -import org.apache.poi.hwpf.model.TestPlexOfCps; -import org.apache.poi.hwpf.model.TestRevisionMarkAuthorTable; -import org.apache.poi.hwpf.model.TestSavedByTable; -import org.apache.poi.hwpf.model.TestSectionTable; -import org.apache.poi.hwpf.model.TestStyleSheet; -import org.apache.poi.hwpf.model.TestTextPieceTable; -import org.apache.poi.hwpf.sprm.TestSprms; -import org.apache.poi.hwpf.usermodel.TestBorderCode; -import org.apache.poi.hwpf.usermodel.TestBug46610; -import org.apache.poi.hwpf.usermodel.TestBug49820; -import org.apache.poi.hwpf.usermodel.TestBug50075; -import org.apache.poi.hwpf.usermodel.TestBugs; -import org.apache.poi.hwpf.usermodel.TestHWPFOldDocument; -import org.apache.poi.hwpf.usermodel.TestHeaderStories; -import org.apache.poi.hwpf.usermodel.TestLists; -import org.apache.poi.hwpf.usermodel.TestPictures; -import org.apache.poi.hwpf.usermodel.TestProblems; -import org.apache.poi.hwpf.usermodel.TestRange; -import org.apache.poi.hwpf.usermodel.TestRangeDelete; -import org.apache.poi.hwpf.usermodel.TestRangeInsertion; -import org.apache.poi.hwpf.usermodel.TestRangeProperties; -import org.apache.poi.hwpf.usermodel.TestRangeReplacement; -import org.apache.poi.hwpf.usermodel.TestRangeSymbols; -import org.apache.poi.hwpf.usermodel.TestTableRow; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - // org.apache.poi.hwpf - TestFieldsTables.class, - TestHWPFPictures.class, - TestHWPFRangeParts.class, - - // org.apache.poi.hwpf.converter - // TestWordToConverterSuite.class, - AbstractWordUtilsTest.class, - TestWordToFoConverter.class, - TestWordToHtmlConverter.class, - - // org.apache.poi.hwpf.extractor - TestDifferentRoutes.class, - TestWordExtractor.class, - TestWordExtractorBugs.class, - - // org.apache.poi.hwpf.model - TestBookmarksTables.class, - TestCHPBinTable.class, - TestDocumentProperties.class, - TestFileInformationBlock.class, - TestFontTable.class, - TestListTables.class, - TestNotesTables.class, - TestPAPBinTable.class, - TestPlexOfCps.class, - TestRevisionMarkAuthorTable.class, - TestSavedByTable.class, - TestSectionTable.class, - TestStyleSheet.class, - TestTextPieceTable.class, - - // org.apache.poi.hwpf.sprm - TestSprms.class, - - // org.apache.poi.hwpf.usermodel - TestBorderCode.class, - TestBug46610.class, - TestBug49820.class, - TestBug50075.class, - TestBugs.class, - TestHeaderStories.class, - TestHWPFOldDocument.class, - TestLists.class, - TestPictures.class, - TestProblems.class, - TestRange.class, - TestRangeDelete.class, - TestRangeInsertion.class, - TestRangeProperties.class, - TestRangeReplacement.class, - TestRangeSymbols.class, - TestTableRow.class -}) -public final class AllHWPFTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java b/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java index 4dd62318eb..594ee33646 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java @@ -21,13 +21,13 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public abstract class HWPFTestCase { protected HWPFDocFixture _hWPFDocFixture; - @Before + @BeforeEach public void setUp() throws Exception { /** @todo verify the constructors */ _hWPFDocFixture = new HWPFDocFixture(this, getTestFile()); @@ -39,7 +39,7 @@ public abstract class HWPFTestCase { return HWPFDocFixture.DEFAULT_TEST_FILE; } - @After + @AfterEach public void tearDown() throws Exception { if (_hWPFDocFixture != null) { _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java index 6209151876..e3323d6e8d 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java @@ -19,7 +19,7 @@ package org.apache.poi.hwpf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; @@ -27,7 +27,7 @@ import org.apache.poi.hwpf.model.FieldsDocumentPart; import org.apache.poi.hwpf.model.FieldsTables; import org.apache.poi.hwpf.model.FileInformationBlock; import org.apache.poi.hwpf.model.PlexOfField; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test case for the fields tables, this test is based on the test-fields.doc diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java b/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java index da84762332..09e2ae2e75 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java @@ -17,10 +17,10 @@ package org.apache.poi.hwpf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.awt.image.BufferedImage; import java.io.ByteArrayInputStream; @@ -32,8 +32,8 @@ import javax.imageio.ImageIO; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.model.PicturesTable; import org.apache.poi.hwpf.usermodel.Picture; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test picture support in HWPF @@ -49,7 +49,7 @@ public final class TestHWPFPictures { private String imgCFile; private String imgDFile; - @Before + @BeforeEach public void setUp() { docAFile = "testPictures.doc"; docBFile = "two_images.doc"; @@ -63,8 +63,7 @@ public final class TestHWPFPictures { // we use ImageIO in one of the tests here so we should ensure that the temporary directory is created correctly File tempDir = new File(System.getProperty("java.io.tmpdir")); - assertTrue("Could not create temporary directory " + tempDir.getAbsolutePath() + ": " + tempDir.exists() + "/" + tempDir.isDirectory(), - tempDir.exists() || tempDir.mkdirs()); + assertTrue( tempDir.exists() || tempDir.mkdirs(), "Could not create temporary directory " + tempDir.getAbsolutePath() + ": " + tempDir.exists() + "/" + tempDir.isDirectory() ); } /** diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFRangeParts.java b/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFRangeParts.java index 7a13e6dfb0..e085ce3564 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFRangeParts.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFRangeParts.java @@ -17,11 +17,11 @@ package org.apache.poi.hwpf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwpf.usermodel.Range; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test that we pull out the right bits of a file into the different ranges @@ -94,7 +94,7 @@ public final class TestHWPFRangeParts { */ private HWPFDocument docUnicode; - @Before + @BeforeEach public void setUp() { docUnicode = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); docAscii = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc"); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/AbstractWordUtilsTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/AbstractWordUtilsTest.java index c68d24d4d8..5e43417a85 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/AbstractWordUtilsTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/AbstractWordUtilsTest.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.hwpf.converter; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.hwpf.usermodel.Table; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link AbstractWordUtils} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestNumberFormatter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestNumberFormatter.java index 641540209f..d7ae2ce0a6 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestNumberFormatter.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestNumberFormatter.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.hwpf.converter; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestNumberFormatter { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java index ac0f30006b..74975f70f4 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java @@ -16,13 +16,17 @@ ==================================================================== */ package org.apache.poi.hwpf.converter; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; +import java.io.FilenameFilter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; @@ -32,46 +36,39 @@ import javax.xml.transform.stream.StreamResult; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocumentCore; import org.apache.poi.util.XMLHelper; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TestWordToConverterSuite { /** * YK: a quick hack to exclude failing documents from the suite. */ - private static List failingFiles = Arrays - .asList( "ProblemExtracting.doc", - "Bug50955.doc" //basic extraction works, - // but these extractors modify the document, - // which is a no-go for this Word 6.0 file - ); + private static final List failingFiles = Arrays.asList( + "ProblemExtracting.doc", + // basic extraction works, but these extractors modify the document, which is a no-go for this Word 6.0 file + "Bug50955.doc", + // password protected files + "PasswordProtected.doc", + "password_tika_binaryrc4.doc", + "password_password_cryptoapi.doc", + // WORD 2.0 file + "word2.doc" + ); - @Parameterized.Parameters(name="{index}: {0}") - public static Iterable files() { - List files = new ArrayList<>(); - File directory = POIDataSamples.getDocumentInstance().getFile( - "../document" ); - for ( final File child : directory.listFiles((dir,name) -> name.endsWith( ".doc" ) && !failingFiles.contains( name ))) { - files.add(new Object[] { child }); - } - - return files; + public static Stream files() { + File directory = POIDataSamples.getDocumentInstance().getFile("../document" ); + FilenameFilter ff = (dir, name) -> name.endsWith(".doc") && !failingFiles.contains(name); + File[] docs = directory.listFiles(ff); + assertNotNull(docs); + return Arrays.stream(docs).map(Arguments::of); } - @Parameterized.Parameter - public File child; - - @Test - public void testFo() throws Exception { - HWPFDocumentCore hwpfDocument; - try { - hwpfDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } + @ParameterizedTest + @MethodSource("files") + public void testFo(File child) throws Exception { + HWPFDocumentCore hwpfDocument = AbstractWordUtils.loadDoc( child ); WordToFoConverter wordToFoConverter = new WordToFoConverter( XMLHelper.newDocumentBuilder().newDocument() ); @@ -88,15 +85,10 @@ public class TestWordToConverterSuite assertNotNull(stringWriter.toString()); } - @Test - public void testHtml() throws Exception - { - HWPFDocumentCore hwpfDocument; - try { - hwpfDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } + @ParameterizedTest + @MethodSource("files") + public void testHtml(File child) throws Exception { + HWPFDocumentCore hwpfDocument = AbstractWordUtils.loadDoc( child ); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( XMLHelper.newDocumentBuilder().newDocument() ); @@ -114,15 +106,10 @@ public class TestWordToConverterSuite assertNotNull(stringWriter.toString()); } - @Test - public void testText() throws Exception - { - HWPFDocumentCore wordDocument; - try { - wordDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } + @ParameterizedTest + @MethodSource("files") + public void testText(File child) throws Exception { + HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc( child ); WordToTextConverter wordToTextConverter = new WordToTextConverter( XMLHelper.newDocumentBuilder().newDocument() ); @@ -140,4 +127,6 @@ public class TestWordToConverterSuite // no exceptions assertNotNull(stringWriter.toString()); } + + } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java index 54970dce8a..c12f6e978b 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java @@ -29,7 +29,7 @@ import javax.xml.transform.stream.StreamResult; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.util.XMLHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link WordToFoConverter} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java index 673ac68163..233d641758 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java @@ -17,7 +17,7 @@ package org.apache.poi.hwpf.converter; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.StringWriter; @@ -29,7 +29,7 @@ import javax.xml.transform.stream.StreamResult; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.util.XMLHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; /** diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java index c6e7e8258a..55fa2aa9e3 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java @@ -17,10 +17,10 @@ package org.apache.poi.hwpf.converter; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.hwpf.HWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestWordToTextConverter { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java b/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java index 515bb81ee3..e320422c10 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java @@ -21,26 +21,26 @@ import java.io.PrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.NullPrintStream; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +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 TestHWPFLister { private static PrintStream oldStdOut; - @BeforeClass + @BeforeAll public static void muteStdout() { oldStdOut = System.out; System.setOut(new NullPrintStream()); } - @AfterClass + @AfterAll public static void restoreStdout() { System.setOut(oldStdOut); } - @After + @AfterEach public void tearDown() { // the main-method sets these properties, we need to revert them here to not affect other tests System.clearProperty("org.apache.poi.hwpf.preserveBinTables"); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java index ca1b54e007..25a502be00 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java @@ -17,20 +17,19 @@ package org.apache.poi.hwpf.extractor; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; - import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.util.StringUtil; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test the different routes to extracting text @@ -57,12 +56,12 @@ public final class TestDifferentRoutes { private HWPFDocument doc; - @Before + @BeforeEach public void setUp() { doc = HWPFTestDataSamples.openSampleFile("test2.doc"); } - - @After + + @AfterEach public void tearDown() throws IOException { doc.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java index 5d919c7a15..39b4b5c8f9 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java @@ -19,9 +19,10 @@ package org.apache.poi.hwpf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.IOException; @@ -36,15 +37,15 @@ import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.StringUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test the different routes to extracting text */ public final class TestWordExtractor { - private static POIDataSamples docTests = POIDataSamples.getDocumentInstance(); - + private static final POIDataSamples docTests = POIDataSamples.getDocumentInstance(); + private static void assertEqualsTrim( String expected, String actual ) { String newExpected = expected.replaceAll( "\r\n", "\n" ) @@ -53,7 +54,7 @@ public final class TestWordExtractor { .replaceAll( "\r", "\n" ).trim(); assertEquals( newExpected, newActual ); } - + private static void assertExtractedContains(String[] extracted, String needle) { String endnote = StringUtil.join(extracted, ""); assertContains(endnote, needle); @@ -175,7 +176,7 @@ public final class TestWordExtractor { extractorB.close(); docB.close(); - + fs.close(); } @@ -233,7 +234,7 @@ public final class TestWordExtractor { assertExtractedContains(extractor.getFootnoteText(), "TestFootnote"); assertEquals(0x00, doc.getRange().getSection(0).getFootnoteNumberingFormat()); // msonfcArabic assertEquals(0x00, doc.getRange().getSection(0).getFootnoteRestartQualifier()); // rncCont - assertEquals(0, doc.getRange().getSection(0).getFootnoteNumberingOffset()); + assertEquals(0, doc.getRange().getSection(0).getFootnoteNumberingOffset()); assertEquals(1, doc.getFootnotes().getNotesCount()); extractor.close(); doc.close(); @@ -247,7 +248,7 @@ public final class TestWordExtractor { assertExtractedContains(extractor.getEndnoteText(), "TestEndnote"); assertEquals(0x02, doc.getRange().getSection(0).getEndnoteNumberingFormat()); // msonfcLCRoman assertEquals(0x00, doc.getRange().getSection(0).getEndnoteRestartQualifier()); // rncCont - assertEquals(0, doc.getRange().getSection(0).getEndnoteNumberingOffset()); + assertEquals(0, doc.getRange().getSection(0).getEndnoteNumberingOffset()); assertEquals(1, doc.getEndnotes().getNotesCount()); extractor.close(); doc.close(); @@ -259,13 +260,13 @@ public final class TestWordExtractor { assertExtractedContains(extractor.getCommentsText(), "TestComment"); extractor.close(); } - - @Test(expected=OldWordFileFormatException.class) - public void testWord95_WordExtractor() throws Exception { + + @Test + public void testWord95_WordExtractor() { // Too old for the default - openExtractor("Word95.doc").close(); + assertThrows(OldWordFileFormatException.class, () -> openExtractor("Word95.doc")); } - + @Test public void testWord95() throws Exception { // Can work with the special one @@ -279,7 +280,7 @@ public final class TestWordExtractor { assertContains(text, "Paragraph 2"); assertContains(text, "Paragraph 3. Has some RED text and some BLUE BOLD text in it"); assertContains(text, "Last (4th) paragraph"); - + @SuppressWarnings("deprecation") String[] tp = w6e.getParagraphText(); assertEquals(7, tp.length); @@ -293,12 +294,12 @@ public final class TestWordExtractor { w6e.close(); } - @Test(expected=OldWordFileFormatException.class) - public void testWord6_WordExtractor() throws IOException { + @Test + public void testWord6_WordExtractor() { // Too old for the default - openExtractor("Word6.doc").close(); + assertThrows(OldWordFileFormatException.class, () -> openExtractor("Word6.doc")); } - + @Test public void testWord6() throws Exception { try (InputStream is = docTests.openResourceAsStream("Word6.doc"); @@ -321,7 +322,7 @@ public final class TestWordExtractor { String text = extractor.getText(); assertContains(text, "\u0425\u0425\u0425\u0425\u0425"); assertContains(text, "\u0423\u0423\u0423\u0423\u0423"); - + extractor.close(); } @@ -334,7 +335,7 @@ public final class TestWordExtractor { assertStartsWith(text, "\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u0435"); extractor.close(); } - + /** * Tests that we can work with both {@link POIFSFileSystem} * and {@link POIFSFileSystem} @@ -400,7 +401,7 @@ public final class TestWordExtractor { assertContains(text, "COMPANY = sample company"); } } - + private WordExtractor openExtractor(String fileName) throws IOException { try (InputStream is = docTests.openResourceAsStream(fileName)) { return new WordExtractor(is); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java index 1962f2facf..a0a6da81ac 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java @@ -17,7 +17,7 @@ package org.apache.poi.hwpf.extractor; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -26,7 +26,7 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for bugs with the WordExtractor diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java index bde4c7659e..df3517820c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java @@ -18,9 +18,11 @@ */ package org.apache.poi.hwpf.model; -import org.junit.Test; +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.Assert.*; +import org.junit.jupiter.api.Test; public class PlfLfoTest { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java index 567b82e5e8..8cd150ce49 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java @@ -17,7 +17,7 @@ package org.apache.poi.hwpf.model; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -25,7 +25,7 @@ import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Bookmark; import org.apache.poi.hwpf.usermodel.Bookmarks; import org.apache.poi.hwpf.usermodel.Range; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link BookmarksTables} and default implementation of diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java index 47ef71ea51..da484011b8 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java @@ -17,16 +17,16 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.util.List; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestCHPBinTable { private CHPBinTable _cHPBinTable; @@ -73,14 +73,14 @@ public final class TestCHPBinTable { } } - @Before + @BeforeEach public void setUp() throws Exception { _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); _hWPFDocFixture.setUp(); } - @After + @AfterEach public void tearDown() throws Exception { _cHPBinTable = null; _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java index 05ca7d64aa..fed128d6bc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java @@ -17,13 +17,13 @@ package org.apache.poi.hwpf.model; +import static org.apache.poi.POITestCase.assertReflectEquals; + import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.model.types.DOPAbstractType; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.apache.poi.POITestCase.assertReflectEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; // TODO: Add DocumentProperties#equals ??? @@ -31,7 +31,7 @@ public final class TestDocumentProperties { private DocumentProperties _documentProperties; private HWPFDocFixture _hWPFDocFixture; - @Before + @BeforeEach public void setUp() throws Exception { // TODO verify the constructors _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); @@ -39,7 +39,7 @@ public final class TestDocumentProperties { _documentProperties = new DocumentProperties(_hWPFDocFixture._tableStream, _hWPFDocFixture._fib.getFcDop(), _hWPFDocFixture._fib.getLcbDop()); } - @After + @AfterEach public void tearDown() throws Exception { _documentProperties = null; _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java index a2fa09e12f..e32b23a70c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java @@ -18,12 +18,12 @@ package org.apache.poi.hwpf.model; import static org.apache.poi.POITestCase.assertReflectEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.hwpf.HWPFDocFixture; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestFileInformationBlock { private FileInformationBlock _fileInformationBlock; @@ -43,7 +43,7 @@ public final class TestFileInformationBlock { assertNotNull(_fileInformationBlock.toString()); } - @Before + @BeforeEach public void setUp() throws Exception { /** @todo verify the constructors */ _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); @@ -51,7 +51,7 @@ public final class TestFileInformationBlock { _fileInformationBlock = _hWPFDocFixture._fib; } - @After + @AfterEach public void tearDown() throws Exception { _fileInformationBlock = null; _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java index 488e28f2d3..f3b656513b 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java @@ -17,17 +17,16 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestFontTable { private FontTable _fontTable; @@ -58,13 +57,13 @@ public final class TestFontTable { } - @Before + @BeforeEach public void setUp() throws IOException { _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); _hWPFDocFixture.setUp(); } - @After + @AfterEach public void tearDown() throws IOException { _hWPFDocFixture.tearDown(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java index ecf22578a1..2a93a32ca2 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java @@ -17,14 +17,14 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.hwpf.HWPFTestCase; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestListTables extends HWPFTestCase { @@ -36,21 +36,21 @@ public final class TestListTables extends HWPFTestCase { int listOffset = fib.getFcPlfLst(); int lfoOffset = fib.getFcPlfLfo(); int bLfoOffset = fib.getLcbPlfLfo(); - + if (listOffset != 0 && bLfoOffset != 0) { // TODO: this is actually never executed ... - + ListTables listTables = new ListTables(tableStream, listOffset, lfoOffset, bLfoOffset); HWPFFileSystem fileSys = new HWPFFileSystem(); - + ByteArrayOutputStream tableOut = fileSys.getStream("1Table"); - + listTables.writeListDataTo(fib, tableOut); listTables.writeListOverridesTo(fib, tableOut); - + ListTables newTables = new ListTables(tableOut.toByteArray(), fib.getFcPlfLst(), fib.getFcPlfLfo(), fib.getLcbPlfLfo()); - + assertEquals(listTables, newTables); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java index 3b7ef6f7e3..56248c7730 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.usermodel.Notes; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link NotesTables} and default implementation of diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java index bf2a196dc0..d9ec8226d4 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java @@ -17,8 +17,8 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -27,7 +27,7 @@ import java.util.List; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestPAPBinTable { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java index abe2ae09d1..26beb16031 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java @@ -17,13 +17,13 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.util.LittleEndian; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestPlexOfCps { private PlexOfCps _plexOfCps; @@ -59,7 +59,7 @@ public final class TestPlexOfCps { } } - @Before + @BeforeEach public void setUp() throws Exception { /**@todo verify the constructors*/ _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); @@ -67,7 +67,7 @@ public final class TestPlexOfCps { _hWPFDocFixture.setUp(); } - @After + @AfterEach public void tearDown() throws Exception { _plexOfCps = null; _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java index 58eba421ca..9cfe9176af 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java @@ -19,11 +19,11 @@ package org.apache.poi.hwpf.model; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Test the table which handles author revision marks diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java index e10640a91d..3b1d55e3eb 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java @@ -17,7 +17,7 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -28,7 +28,7 @@ import java.util.List; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit test for {@link SavedByTable} and {@link SavedByEntry}. @@ -64,8 +64,7 @@ public final class TestSavedByTable { HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc"); // Check what we just read. - assertEquals("List of saved-by entries was not as expected", expected, - doc.getSavedByTable().getEntries()); + assertEquals( expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected" ); // Now write the entire document out, and read it back in... ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); @@ -75,9 +74,8 @@ public final class TestSavedByTable { HWPFDocument copy = new HWPFDocument(copyStream); // And check again. - assertEquals("List of saved-by entries was incorrect after writing", - expected, copy.getSavedByTable().getEntries()); - + assertEquals( expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing" ); + copy.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java index a50320963b..56ff4d116a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java @@ -17,16 +17,16 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.util.List; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestSectionTable { private HWPFDocFixture _hWPFDocFixture; @@ -85,7 +85,7 @@ public final class TestSectionTable { } } - @Before + @BeforeEach public void setUp() throws Exception { /*@todo verify the constructors*/ _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); @@ -93,7 +93,7 @@ public final class TestSectionTable { _hWPFDocFixture.setUp(); } - @After + @AfterEach public void tearDown() { _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java index 328e5d428b..c32d1ea0a3 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java @@ -17,16 +17,16 @@ package org.apache.poi.hwpf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestStyleSheet { private StyleSheet _styleSheet; @@ -64,7 +64,7 @@ public final class TestStyleSheet { assertEquals(newStyleSheet, _styleSheet); } - @Before + @BeforeEach public void setUp() throws IOException { /**@todo verify the constructors*/ _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); @@ -77,7 +77,7 @@ public final class TestStyleSheet { _styleSheet = new StyleSheet(tableStream, fib.getFcStshf()); } - @After + @AfterEach public void tearDown() throws Exception { _styleSheet = null; _hWPFDocFixture.tearDown(); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java index 89dde27330..913ab206f0 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java @@ -18,9 +18,9 @@ package org.apache.poi.hwpf.model; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -29,15 +29,15 @@ import org.apache.poi.hwpf.HWPFDocFixture; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public final class TestTextPieceTable { private HWPFDocFixture _hWPFDocFixture; - @Before + @BeforeEach public void setUp() throws Exception { System.setProperty("org.apache.poi.hwpf.preserveTextTable", Boolean.TRUE.toString()); @@ -47,7 +47,7 @@ public final class TestTextPieceTable { _hWPFDocFixture.setUp(); } - @After + @AfterEach public void tearDown() throws Exception { _hWPFDocFixture.tearDown(); _hWPFDocFixture = null; diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java index 450e873fbb..470d0b6d3c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.hwpf.model.types; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link LFOLVLBaseAbstractType} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java index 9a64a33698..fbc8ab648e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.hwpf.model.types; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link LVLFAbstractType} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java index 881a7b2e43..1df6e45cd4 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java @@ -18,10 +18,10 @@ */ package org.apache.poi.hwpf.sprm; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hwpf.usermodel.TableProperties; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TableSprmUncompressorTest { @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java index 9af5ff57c0..c9d57b3a27 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java @@ -19,8 +19,8 @@ package org.apache.poi.hwpf.sprm; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -32,7 +32,7 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSprms { private static HWPFDocument reload( HWPFDocument hwpfDocument ) diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java index b66f814e35..9ada74499e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java @@ -17,13 +17,13 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * API for BorderCode, see Bugzill 49919 diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java index 0707f0db9b..739fb7b498 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java @@ -17,13 +17,12 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertNotNull; import static org.apache.poi.POITestCase.assertContains; - -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; +import org.junit.jupiter.api.Test; public final class TestBug46610 { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java index 87193b9250..4a74bb9a35 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java @@ -16,49 +16,44 @@ ==================================================================== */ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.util.HexDump; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Bug 47563 - Exception when working with table */ -@RunWith(Parameterized.class) public class TestBug47563 { - @Parameterized.Parameter() - public int rows; - @Parameterized.Parameter(1) - public int columns; - @Parameterized.Parameters(name="rows: {0}, columns: {1}") - public static Collection data() { - List data = new ArrayList<>(); + public static Stream data() { + List data = new ArrayList<>(); - data.add(new Object[] {1, 5}); - data.add(new Object[] {1, 6}); - data.add(new Object[] {5, 1}); - data.add(new Object[] {6, 1}); - data.add(new Object[] {2, 2}); - data.add(new Object[] {3, 2}); - data.add(new Object[] {2, 3}); // - data.add(new Object[] {3, 3}); + data.add(Arguments.of( 1, 5 )); + data.add(Arguments.of( 1, 6 )); + data.add(Arguments.of( 5, 1 )); + data.add(Arguments.of( 6, 1 )); + data.add(Arguments.of( 2, 2 )); + data.add(Arguments.of( 3, 2 )); + data.add(Arguments.of( 2, 3 )); + data.add(Arguments.of( 3, 3 )); - return data; + return data.stream(); } - @Test - public void test() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void test(int rows, int columns) throws Exception { // POI apparently can't create a document from scratch, // so we need an existing empty dummy document try (HWPFDocument doc = HWPFTestDataSamples.openSampleFile("empty.doc")) { @@ -93,10 +88,8 @@ public class TestBug47563 { int mustBeAfter = 0; for (int i = 0; i < rows * columns; i++) { int next = text.indexOf(Integer.toString(i), mustBeAfter); - assertTrue("Test with " + rows + "/" + columns + ": Should find " + i + - " but did not find it (" + next + ") with " + mustBeAfter + " in " + textBytes + "\n" + - text.indexOf(Integer.toString(i), mustBeAfter), - next != -1); + assertTrue( next != -1, "Test with " + rows + "/" + columns + ": Should find " + i + + " but did not find it (" + next + ") with " + mustBeAfter + " in " + textBytes + "\n" + next); mustBeAfter = next; } } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java index e4e0c33b47..f50ccdf3ac 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java @@ -17,14 +17,14 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.StyleSheet; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestBug49820 { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug50075.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug50075.java index 535f9be52d..e46e873ffa 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug50075.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug50075.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -25,7 +25,7 @@ import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.LFO; import org.apache.poi.hwpf.model.ListLevel; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestBug50075 { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBugs.java index 0c3dac7240..89198d2758 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBugs.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBugs.java @@ -18,9 +18,10 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -41,17 +42,15 @@ import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.hwpf.converter.WordToTextConverter; import org.apache.poi.hwpf.extractor.Word6Extractor; import org.apache.poi.hwpf.extractor.WordExtractor; -import org.apache.poi.hwpf.model.FieldsDocumentPart; import org.apache.poi.hwpf.model.FileInformationBlock; import org.apache.poi.hwpf.model.PicturesTable; -import org.apache.poi.hwpf.model.PlexOfField; import org.apache.poi.hwpf.model.SubdocumentType; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.util.XMLHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; /** @@ -78,9 +77,8 @@ public class TestBugs{ Paragraph actParagraph = actual.getParagraph(p); assertEqualsIgnoreNewline(expParagraph.text(), actParagraph.text()); - assertEquals("Different isInTable flags for paragraphs #" + p - + " -- " + expParagraph + " -- " + actParagraph + ".", - expParagraph.isInTable(), actParagraph.isInTable()); + assertEquals( expParagraph.isInTable(), actParagraph.isInTable(), "Different isInTable flags for paragraphs #" + p + + " -- " + expParagraph + " -- " + actParagraph + "." ); assertEquals(expParagraph.isTableRowEnd(), actParagraph.isTableRowEnd()); @@ -476,7 +474,7 @@ public class TestBugs{ for (String filename : filenames) { HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile(filename); - assertNotNull(filename, hwpfDocument.getPicturesTable().getAllPictures()); + assertNotNull( hwpfDocument.getPicturesTable().getAllPictures(), filename ); hwpfDocument.close(); } @@ -832,13 +830,11 @@ public class TestBugs{ assertNotNull(hwpfDocument); } - @Test(expected=ArrayIndexOutOfBoundsException.class) + @Test public void test57603SevenRowTable() throws Exception { - HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("57603-seven_columns.doc"); - HWPFDocument hwpfDocument2 = HWPFTestDataSamples.writeOutAndReadBack(hwpfDocument); - assertNotNull(hwpfDocument2); - hwpfDocument2.close(); - hwpfDocument.close(); + try (HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("57603-seven_columns.doc")) { + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HWPFTestDataSamples.writeOutAndReadBack(hwpfDocument)); + } } @Test diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java index d5702d9a9c..a5ca067fec 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java @@ -18,7 +18,10 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openOldSampleFile; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.nio.charset.Charset; @@ -27,10 +30,9 @@ import org.apache.poi.OldFileFormatException; import org.apache.poi.common.usermodel.fonts.FontCharset; import org.apache.poi.hwpf.HWPFOldDocument; import org.apache.poi.hwpf.HWPFTestCase; -import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.extractor.Word6Extractor; import org.apache.poi.hwpf.model.OldFontTable; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for Word 6 and Word 95 support @@ -39,16 +41,16 @@ public final class TestHWPFOldDocument extends HWPFTestCase { /** * Test a simple Word 6 document */ - @Test(expected=OldFileFormatException.class) - public void testWord6hwpf() throws IOException { + @Test + public void testWord6hwpf() { // Can't open as HWPFDocument - HWPFTestDataSamples.openSampleFile("Word6.doc"); + assertThrows(OldFileFormatException.class, () -> openSampleFile("Word6.doc")); } @Test public void testWord6hwpfOld() throws IOException { // Open - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6.doc"); + HWPFOldDocument doc = openOldSampleFile("Word6.doc"); // Check assertEquals(1, doc.getRange().numSections()); @@ -63,32 +65,31 @@ public final class TestHWPFOldDocument extends HWPFTestCase { /** * Test a simple Word 2 document */ - @Test(expected=IllegalArgumentException.class) - public void testWord2hwpf() throws IOException { + @Test + public void testWord2hwpf() { // Can't open as HWPFDocument - HWPFTestDataSamples.openSampleFile("word2.doc"); + assertThrows(IllegalArgumentException.class, () -> openSampleFile("word2.doc")); } - @Test(expected=RuntimeException.class) - public void testWord2hwpfOld() throws IOException { + @Test + public void testWord2hwpfOld() { // Open - HWPFTestDataSamples.openOldSampleFile("word2.doc"); + assertThrows(RuntimeException.class, () -> openOldSampleFile("word2.doc")); } /** * Test a simple Word 95 document */ - @Test(expected=OldFileFormatException.class) - public void testWord95hwpf() throws IOException { + @Test + public void testWord95hwpf() { // Can't open as HWPFDocument - HWPFTestDataSamples.openSampleFile("Word95.doc"); + assertThrows(OldFileFormatException.class, () -> openSampleFile("Word95.doc")); } - + @Test public void testWord95hwpfOld() throws IOException { // Open - HWPFOldDocument doc = HWPFTestDataSamples - .openOldSampleFile("Word95.doc"); + HWPFOldDocument doc = openOldSampleFile("Word95.doc"); // Check assertEquals(1, doc.getRange().numSections()); @@ -126,7 +127,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { */ @Test public void testWord6Sections() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6_sections.doc"); + HWPFOldDocument doc = openOldSampleFile("Word6_sections.doc"); assertEquals(3, doc.getRange().numSections()); assertEquals(6, doc.getRange().numParagraphs()); @@ -135,7 +136,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { doc.getRange().getParagraph(0).text()); assertEquals("\r", doc.getRange().getParagraph(1).text()); // Section / line? - assertEquals("\u000c", doc.getRange().getParagraph(2).text()); + assertEquals("\u000c", doc.getRange().getParagraph(2).text()); assertEquals("This is a new section.\r", doc.getRange().getParagraph(3).text()); // Section / line? @@ -150,8 +151,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { */ @Test public void testWord6Sections2() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples - .openOldSampleFile("Word6_sections2.doc"); + HWPFOldDocument doc = openOldSampleFile("Word6_sections2.doc"); assertEquals(1, doc.getRange().numSections()); assertEquals(57, doc.getRange().numParagraphs()); @@ -164,7 +164,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { @Test public void testDefaultCodePageEncoding() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60942.doc"); + HWPFOldDocument doc = openOldSampleFile("Bug60942.doc"); Word6Extractor ex = new Word6Extractor(doc); String txt = ex.getText(); assertContains(txt, "BERTHOD"); @@ -179,7 +179,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { @Test public void testCodePageBug50955() throws IOException { //windows 1251 - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug50955.doc"); + HWPFOldDocument doc = openOldSampleFile("Bug50955.doc"); Word6Extractor ex = new Word6Extractor(doc); StringBuilder sb = new StringBuilder(); @@ -197,7 +197,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { //see https://bz.apache.org/ooo/show_bug.cgi?id=12445 for the inspiration - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60936.doc"); + HWPFOldDocument doc = openOldSampleFile("Bug60936.doc"); Word6Extractor ex = new Word6Extractor(doc); StringBuilder sb = new StringBuilder(); for (String p : ex.getParagraphText()) { @@ -210,7 +210,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { @Test public void testOldFontTableEncoding() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); + HWPFOldDocument doc = openOldSampleFile("Bug51944.doc"); OldFontTable oldFontTable = doc.getOldFontTable(); assertEquals(5, oldFontTable.getFontNames().length); assertEquals("\u7D30\u660E\u9AD4", oldFontTable.getFontNames()[0].getMainFontName()); @@ -221,8 +221,8 @@ public final class TestHWPFOldDocument extends HWPFTestCase { } @Test - public void testOldFontTableAltName() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60942b.doc"); + public void testOldFontTableAltName() { + HWPFOldDocument doc = openOldSampleFile("Bug60942b.doc"); OldFontTable oldFontTable = doc.getOldFontTable(); assertEquals(5, oldFontTable.getFontNames().length); assertEquals("Roboto", oldFontTable.getFontNames()[3].getMainFontName()); @@ -234,7 +234,7 @@ public final class TestHWPFOldDocument extends HWPFTestCase { @Test public void test51944() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); + HWPFOldDocument doc = openOldSampleFile("Bug51944.doc"); Word6Extractor ex = new Word6Extractor(doc); StringBuilder sb = new StringBuilder(); for (String p : ex.getParagraphText()) { diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java index 19504bd108..822672b461 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java @@ -17,7 +17,8 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -34,14 +35,14 @@ import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test various write situations */ public final class TestHWPFWrite extends HWPFTestCase { private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - + /** * Write to a stream */ @@ -124,26 +125,22 @@ public final class TestHWPFWrite extends HWPFTestCase { poifs.close(); } - @Test(expected=IllegalStateException.class) + @Test public void testInvalidInPlaceWriteInputStream() throws IOException { // Can't work for InputStream opened files try (InputStream is = SAMPLES.openResourceAsStream("SampleDoc.doc"); HWPFDocument doc = new HWPFDocument(is)) { - doc.write(); + assertThrows(IllegalStateException.class, doc::write); } } - - @Test(expected=IllegalStateException.class) + + @Test public void testInvalidInPlaceWritePOIFS() throws Exception { // Can't work for Read-Only files - POIFSFileSystem fs = new POIFSFileSystem(SAMPLES.getFile("SampleDoc.doc"), true); - HWPFDocument doc = new HWPFDocument(fs.getRoot()); - try { - doc.write(); - } finally { - doc.close(); - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(SAMPLES.getFile("SampleDoc.doc"), true); + HWPFDocument doc = new HWPFDocument(fs.getRoot())) { + assertThrows(IllegalStateException.class, doc::write); } } } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java index e35b5aa910..f8167e0608 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java @@ -18,13 +18,13 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +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 org.apache.poi.hwpf.HWPFDocument; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for the handling of header stories into headers, footers etc @@ -40,7 +40,7 @@ public final class TestHeaderStories { private HWPFDocument unicode; private HWPFDocument withFields; - @Before + @BeforeEach public void setUp() { none = openSampleFile("NoHeadFoot.doc"); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java index 7290b0cf95..93e76fc80a 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java @@ -18,16 +18,16 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.ListLevel; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for our handling of lists diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java index 2dd5737bd9..5358ba4ecc 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java @@ -17,14 +17,14 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ddf.EscherComplexProperty; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherOptRecord; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.util.StringUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test cases for {@link OfficeDrawing} and {@link OfficeDrawingsImpl} classes. diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java index 8c829c0fff..061ba37729 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java @@ -17,10 +17,10 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.FileOutputStream; import java.io.OutputStream; @@ -30,8 +30,8 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.PicturesTable; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Test the picture handling @@ -165,23 +165,23 @@ public final class TestPictures { // This file has two embeded excel files, an embeded powerpoint // file and an embeded word file, in that order HWPFDocument doc = HWPFTestDataSamples.openSampleFile("word_with_embeded.doc"); - + // Check we don't break loading the pictures doc.getPicturesTable().getAllPictures(); PicturesTable pictureTable = doc.getPicturesTable(); - + // Check the text, and its embeded images Paragraph p; Range r = doc.getRange(); assertEquals(1, r.numSections()); assertEquals(5, r.numParagraphs()); - + p = r.getParagraph(0); assertEquals(2, p.numCharacterRuns()); assertEquals("I have lots of embedded files in me\r", p.text()); assertFalse(pictureTable.hasPicture(p.getCharacterRun(0))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(1))); - + p = r.getParagraph(1); assertEquals(5, p.numCharacterRuns()); assertEquals("\u0013 EMBED Excel.Sheet.8 \u0014\u0001\u0015\r", p.text()); @@ -190,7 +190,7 @@ public final class TestPictures { assertFalse(pictureTable.hasPicture(p.getCharacterRun(2))); assertTrue(pictureTable.hasPicture(p.getCharacterRun(3))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(4))); - + p = r.getParagraph(2); assertEquals(6, p.numCharacterRuns()); assertEquals("\u0013 EMBED Excel.Sheet.8 \u0014\u0001\u0015\r", p.text()); @@ -200,7 +200,7 @@ public final class TestPictures { assertTrue(pictureTable.hasPicture(p.getCharacterRun(3))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(4))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(5))); - + p = r.getParagraph(3); assertEquals(6, p.numCharacterRuns()); assertEquals("\u0013 EMBED PowerPoint.Show.8 \u0014\u0001\u0015\r", p.text()); @@ -210,7 +210,7 @@ public final class TestPictures { assertTrue(pictureTable.hasPicture(p.getCharacterRun(3))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(4))); assertFalse(pictureTable.hasPicture(p.getCharacterRun(5))); - + p = r.getParagraph(4); assertEquals(6, p.numCharacterRuns()); assertEquals("\u0013 EMBED Word.Document.8 \\s \u0014\u0001\u0015\r", p.text()); @@ -276,15 +276,15 @@ public final class TestPictures { public void testFloatingPictures() { HWPFDocument doc = HWPFTestDataSamples.openSampleFile("FloatingPictures.doc"); PicturesTable pictures = doc.getPicturesTable(); - + // There are 19 images in the picture, but some are // duplicate floating ones assertEquals(17, pictures.getAllPictures().size()); - + int plain8s = 0; int escher8s = 0; int image1s = 0; - + Range r = doc.getRange(); for(int np=0; np < r.numParagraphs(); np++) { Paragraph p = r.getParagraph(np); @@ -316,7 +316,7 @@ public final class TestPictures { assertEquals(2, pics.size()); Picture pic1 = pics.get(0); - assertEquals("FIXME: unable to get image width", -1, pic1.getWidth()); + assertEquals( -1, pic1.getWidth(), "FIXME: unable to get image width" ); assertEquals(270, pic1.getHorizontalScalingFactor()); assertEquals(271, pic1.getVerticalScalingFactor()); assertEquals(12000, pic1.getDxaGoal()); // 21.17 cm / 2.54 cm/inch * 72dpi * 20 = 12000 @@ -327,7 +327,7 @@ public final class TestPictures { assertEquals(0, pic1.getDyaCropBottom()); Picture pic2 = pics.get(1); - assertEquals("FIXME: unable to get image width", -1, pic2.getWidth()); + assertEquals( -1, pic2.getWidth(), "FIXME: unable to get image width" ); assertEquals(764, pic2.getHorizontalScalingFactor()); assertEquals(685, pic2.getVerticalScalingFactor()); assertEquals(12000, pic2.getDxaGoal()); // 21.17 cm / 2.54 cm/inch * 72dpi * 20 = 12000 @@ -342,14 +342,14 @@ public final class TestPictures { public void testPictureDetectionWithPNG() { HWPFDocument document = HWPFTestDataSamples.openSampleFile("PngPicture.doc"); PicturesTable pictureTable = document.getPicturesTable(); - + assertEquals(1, pictureTable.getAllPictures().size()); - + Picture p = pictureTable.getAllPictures().get(0); assertEquals(PictureType.PNG, p.suggestPictureType()); assertEquals("png", p.suggestFileExtension()); } - + @Test public void testPictureWithAlternativeText() { HWPFDocument document = HWPFTestDataSamples.openSampleFile("Picture_Alternative_Text.doc"); @@ -358,12 +358,12 @@ public final class TestPictures { assertEquals("This is the alternative text for the picture.", picture.getDescription()); } - - @Ignore("This bug is not fixed yet") + + @Disabled("This bug is not fixed yet") @Test public void test58804_1() throws Exception { HWPFDocument docA = HWPFTestDataSamples.openSampleFile("58804_1.doc"); - + expectImages(docA, 1); HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); @@ -375,11 +375,11 @@ public final class TestPictures { expectImages(docB, 1); } - @Ignore("This bug is not fixed yet") + @Disabled("This bug is not fixed yet") @Test public void test58804() throws Exception { HWPFDocument docA = HWPFTestDataSamples.openSampleFile("58804.doc"); - + expectImages(docA, 7); HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java index ab3145e067..8fa639ac0b 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java @@ -17,8 +17,9 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -28,7 +29,7 @@ import org.apache.poi.hwpf.HWPFTestCase; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.hwpf.model.StyleSheet; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test various problem documents @@ -49,7 +50,7 @@ public final class TestProblems extends HWPFTestCase { s.getParagraph(y); } } - + doc.close(); } @@ -62,7 +63,7 @@ public final class TestProblems extends HWPFTestCase { StyleSheet styleSheet = doc.getStyleSheet(); assertNotNull(styleSheet); - + Range r = doc.getRange(); for (int x = 0; x < r.numSections(); x++) { Section s = r.getSection(x); @@ -144,7 +145,7 @@ public final class TestProblems extends HWPFTestCase { assertEquals(4, cell._parEnd); assertEquals(65, cell.getStartOffset()); assertEquals(85, cell.getEndOffset()); - + doc.close(); } @@ -181,16 +182,17 @@ public final class TestProblems extends HWPFTestCase { } assertEquals(newLength, totalLength - deletedLength); - + doc.close(); } /** * With an encrypted file, we should give a suitable exception, and not OOM */ - @Test(expected=EncryptedDocumentException.class) - public void testEncryptedFile() throws IOException { - HWPFTestDataSamples.openSampleFile("PasswordProtected.doc"); + @Test + public void testEncryptedFile() { + assertThrows(EncryptedDocumentException.class, () -> HWPFTestDataSamples.openSampleFile("PasswordProtected.doc")); + } @Test @@ -240,7 +242,7 @@ public final class TestProblems extends HWPFTestCase { assertEquals(offset, para.text().indexOf(shorter)); } } - + doc.close(); } @@ -280,7 +282,7 @@ public final class TestProblems extends HWPFTestCase { doc.getRange().getParagraph(0).text()); assertEquals("After Crashing Part\r", doc.getRange().getParagraph(13).text()); - + doc.close(); } @@ -428,7 +430,7 @@ public final class TestProblems extends HWPFTestCase { assertEquals(106, cell.getStartOffset()); assertEquals(119, cell.getEndOffset()); assertEquals("Row 3/Cell 3\u0007", cell.text()); - + doc.close(); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java index 2fa5aa292b..6f45170fd9 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java @@ -17,8 +17,8 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -27,7 +27,7 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.model.SEPX; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for Range which aren't around deletion, insertion, text replacement or @@ -35,7 +35,7 @@ import org.junit.Test; */ public final class TestRange { private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - + @Test public void testFieldStripping() { String exp = "This is some text."; diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java index 012b4cbff1..acf6b5597d 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java @@ -18,13 +18,13 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.model.PAPX; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test to see if Range.delete() works even if the Range contains a diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java index 9271ef2c64..4c60d97a7c 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java @@ -18,12 +18,12 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test to see if Range.insertBefore() works even if the Range contains a diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java index 423aa9081c..ad194b3032 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java @@ -17,9 +17,9 @@ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.List; @@ -27,8 +27,8 @@ import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.PAPX; import org.apache.poi.hwpf.model.StyleSheet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests to ensure that our ranges end up with @@ -68,7 +68,7 @@ public final class TestRangeProperties { private HWPFDocument u; private HWPFDocument a; - @Before + @BeforeEach public void setUp() { u = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); a = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeReplacement.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeReplacement.java index 7e4f1584f5..c9de0ffe31 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeReplacement.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeReplacement.java @@ -18,12 +18,12 @@ package org.apache.poi.hwpf.usermodel; import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test to see if Range.replaceText() works even if the Range contains a diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeSymbols.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeSymbols.java index 49902b77cd..c7e9485594 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeSymbols.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeSymbols.java @@ -22,9 +22,9 @@ import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.model.Ffn; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * API for processing of symbols, see Bugzilla 49908 diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java index 9c1127a12c..268931a68e 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java @@ -16,18 +16,18 @@ ==================================================================== */ package org.apache.poi.hwpf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestTableRow { private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - + @Test public void testInnerTableCellsDetection() throws IOException { InputStream is = SAMPLES.openResourceAsStream( "innertable.doc" ); @@ -62,7 +62,7 @@ public class TestTableRow { assertEquals( 3, outerTable.getRow( 0 ).numCells() ); assertEquals( 3, outerTable.getRow( 1 ).numCells() ); assertEquals( 3, outerTable.getRow( 2 ).numCells() ); - + hwpfDocument.close(); } diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/util/TestLittleEndianCP950Reader.java b/src/scratchpad/testcases/org/apache/poi/hwpf/util/TestLittleEndianCP950Reader.java index b6c7fd201a..310b714516 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/util/TestLittleEndianCP950Reader.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/util/TestLittleEndianCP950Reader.java @@ -17,12 +17,12 @@ package org.apache.poi.hwpf.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.Reader; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestLittleEndianCP950Reader { @@ -63,6 +63,6 @@ public class TestLittleEndianCP950Reader { int c = reader.read(); assertEquals((int) expected, c); int eof = reader.read(); - assertEquals("should be end of stream", -1, eof); + assertEquals(-1, eof, "should be end of stream"); } } diff --git a/src/testcases/org/apache/poi/AllPOITests.java b/src/testcases/org/apache/poi/AllPOITests.java deleted file mode 100644 index 40454c0473..0000000000 --- a/src/testcases/org/apache/poi/AllPOITests.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; - -import org.apache.poi.ddf.AllPOIDDFTests; -import org.apache.poi.hpsf.basic.AllPOIHPSFBasicTests; -import org.apache.poi.hssf.HSSFTests; -import org.apache.poi.poifs.AllPOIFSTests; -import org.apache.poi.util.AllPOIUtilTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Root Test Suite for entire POI project. (Includes all sub-packages of org.apache.poi)
- */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestPOIDocumentMain.class, - AllPOIDDFTests.class, - AllPOIHPSFBasicTests.class, - HSSFTests.class, - AllPOIFSTests.class, - AllPOIUtilTests.class -}) -public final class AllPOITests { -} diff --git a/src/testcases/org/apache/poi/POITestCase.java b/src/testcases/org/apache/poi/POITestCase.java index 7907012cfb..5dac0dc90f 100644 --- a/src/testcases/org/apache/poi/POITestCase.java +++ b/src/testcases/org/apache/poi/POITestCase.java @@ -23,10 +23,10 @@ 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.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNoException; +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; @@ -84,9 +84,7 @@ public final class POITestCase { assertNotNull(needle); String hay = haystack.toLowerCase(locale); String n = needle.toLowerCase(locale); - assertTrue("Unable to find expected text '" + needle + "' in text:\n" + haystack, - hay.contains(n) - ); + 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); @@ -103,17 +101,11 @@ public final class POITestCase { * @param key needle */ public static void assertContains(Map map, T key) { - if (map.containsKey(key)) { - return; - } - fail("Unable to find " + key + " in " + map); + assertTrue(map.containsKey(key), "Unable to find " + key + " in " + map); } public static void assertNotContained(Set set, T element) { - assertThat(set, not(hasItem(element))); - /*if (set.contains(element)) { - fail("Set should not contain " + element); - }*/ + assertThat("Set should not contain " + element, set, not(hasItem(element))); } /** @@ -123,7 +115,7 @@ public final class POITestCase { @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("Reflection of private fields is only allowed for POI classes.", clazz.getName().startsWith("org.apache.poi.")); + 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); @@ -193,7 +185,7 @@ public final class POITestCase { * be raised when the bug is fixed */ public static void skipTest(Throwable e) { - assumeNoException("This test currently fails with", e); + assumeTrue(e != null, "This test currently fails with"); } /** * @see #skipTest(Throwable) @@ -205,9 +197,7 @@ public final class POITestCase { } public static void assertBetween(String message, int value, int min, int max) { - assertTrue(message + ": " + value + " is less than the minimum value of " + min, - min <= value); - assertTrue(message + ": " + value + " is greater than the maximum value of " + max, - value <= 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 index dfac092f04..d2736ed1a0 100644 --- a/src/testcases/org/apache/poi/TestJDK12.java +++ b/src/testcases/org/apache/poi/TestJDK12.java @@ -23,7 +23,7 @@ import java.awt.font.TextLayout; import java.awt.image.BufferedImage; import java.text.AttributedString; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Minimal Test-Class found when running the Apache POI regression tests. diff --git a/src/testcases/org/apache/poi/TestPOIDocumentMain.java b/src/testcases/org/apache/poi/TestPOIDocumentMain.java index 8717d4c291..fc57f8eae5 100644 --- a/src/testcases/org/apache/poi/TestPOIDocumentMain.java +++ b/src/testcases/org/apache/poi/TestPOIDocumentMain.java @@ -17,9 +17,9 @@ package org.apache.poi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -31,8 +31,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests that POIDocument correctly loads and saves the common @@ -49,7 +49,7 @@ public final class TestPOIDocumentMain { /** * Set things up, two spreadsheets for our testing */ - @Before + @BeforeEach public void setUp() { doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls"); doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls"); @@ -114,7 +114,7 @@ public final class TestPOIDocumentMain { // Check they're still there POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS); doc3.readProperties(); - + // Delegate test readPropertiesHelper(doc3); doc3.close(); @@ -144,7 +144,7 @@ public final class TestPOIDocumentMain { assertNotNull(doc.getSummaryInformation()); assertNotNull(doc.getDocumentSummaryInformation()); - + doc.close(); } @@ -159,9 +159,9 @@ public final class TestPOIDocumentMain { // 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); @@ -176,7 +176,7 @@ public final class TestPOIDocumentMain { // Save and re-load baos = new ByteArrayOutputStream(); doc.write(baos); - + doc.close(); bais = new ByteArrayInputStream(baos.toByteArray()); diff --git a/src/testcases/org/apache/poi/TestPOITestCase.java b/src/testcases/org/apache/poi/TestPOITestCase.java index 60f5fb9cb7..f1b695611a 100644 --- a/src/testcases/org/apache/poi/TestPOITestCase.java +++ b/src/testcases/org/apache/poi/TestPOITestCase.java @@ -17,7 +17,7 @@ package org.apache.poi; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.util.Collections; @@ -26,7 +26,7 @@ import java.util.Map; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.property.PropertyTable; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * A class for testing the POI Junit TestCase utility class diff --git a/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java b/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java deleted file mode 100644 index 2088e9760e..0000000000 --- a/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.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.ddf; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEscherBSERecord.class, - TestEscherBlipRecord.class, - TestEscherBoolProperty.class, - TestEscherChildAnchorRecord.class, - TestEscherClientAnchorRecord.class, - TestEscherClientDataRecord.class, - TestEscherContainerRecord.class, - TestEscherDgRecord.class, - TestEscherDggRecord.class, - TestEscherOptRecord.class, - TestEscherPropertyFactory.class, - TestEscherSpRecord.class, - TestEscherSpgrRecord.class, - TestEscherSplitMenuColorsRecord.class, - TestUnknownEscherRecord.class -}) -public final class AllPOIDDFTests { -} diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java index 184486b3bd..82d573df18 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java @@ -17,8 +17,8 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -26,7 +26,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestEscherBSERecord { @Test @@ -56,7 +56,7 @@ public final class TestEscherBSERecord { 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); diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java index 818a5cb97b..d1644f052e 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java @@ -17,14 +17,14 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Test read/serialize of escher blip records diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java b/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java index 96083e4d84..4f34ab1fb8 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java @@ -17,9 +17,9 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherBoolProperty { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java index 457accfa4d..c6d67052be 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherChildAnchorRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java index 5077118286..1cca9dd476 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEscherClientAnchorRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java index 3c0285931e..e10a86ef84 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - + package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEscherClientDataRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java index 2f77f6c28f..832e66afd9 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java @@ -17,18 +17,18 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link EscherContainerRecord} diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java index c3d07958ed..8de2256f58 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherDgRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java index d06979dab9..8666fd5693 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherDggRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDump.java b/src/testcases/org/apache/poi/ddf/TestEscherDump.java index b18a7cc790..d53bb9496c 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherDump.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherDump.java @@ -17,9 +17,9 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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; @@ -33,8 +33,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestEscherDump { private static final String recordData = @@ -67,7 +67,7 @@ public class TestEscherDump { private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private PrintStream stream; - @Before + @BeforeEach public void setup() throws UnsupportedEncodingException { stream = new PrintStream(baos, true, StandardCharsets.UTF_8.name()); } diff --git a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java index 33af04b3ba..79fcd66ad4 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java @@ -17,15 +17,15 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestEscherOptRecord { diff --git a/src/testcases/org/apache/poi/ddf/TestEscherProperty.java b/src/testcases/org/apache/poi/ddf/TestEscherProperty.java index 62c6879f7f..a7a4774b0a 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherProperty.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherProperty.java @@ -17,17 +17,17 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public class TestEscherProperty { /** * assure that EscherProperty.getName() returns correct name for complex properties - * See Bugzilla 50401 + * See Bugzilla 50401 */ @Test public void testPropertyNames() throws Exception { diff --git a/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java b/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java index 803b3bdf01..dd64bd5e7c 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherPropertyFactory.java @@ -17,13 +17,13 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public class TestEscherPropertyFactory { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java index 786cf0917b..8f1826c18c 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEscherSpRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java index 0e8e356ff2..54c7589b81 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherSpgrRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java index 6df9fd6122..3180b6ddaa 100644 --- a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexDump; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEscherSplitMenuColorsRecord { @Test diff --git a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java b/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java index d354c5d887..2b7217de1c 100644 --- a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java +++ b/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java @@ -17,13 +17,13 @@ package org.apache.poi.ddf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public final class TestUnknownEscherRecord { @Test @@ -81,7 +81,7 @@ public final class TestUnknownEscherRecord { 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 @@ -91,7 +91,7 @@ public final class TestUnknownEscherRecord { r = new UnknownEscherRecord(); r.fillFields( HexRead.readFromString( testData ), factory ); - + assertEquals( 0x0200, r.getOptions() ); assertEquals( (short) 0xF111, r.getRecordId() ); assertEquals( 12, r.getRecordSize() ); @@ -102,7 +102,7 @@ public final class TestUnknownEscherRecord { assertEquals( 2, r.getData()[1] ); assertEquals( 3, r.getData()[2] ); assertEquals( 4, r.getData()[3] ); - + testData = "0F 02 " + // options "11 F1 " + // record id @@ -113,7 +113,7 @@ public final class TestUnknownEscherRecord { r = new UnknownEscherRecord(); r.fillFields( HexRead.readFromString( testData ), factory ); - + assertEquals( 0x020F, r.getOptions() ); assertEquals( (short) 0xF111, r.getRecordId() ); assertEquals( 8, r.getRecordSize() ); diff --git a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java b/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java index 26ca734f77..6fcc2a89b4 100644 --- a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java +++ b/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java @@ -18,19 +18,19 @@ */ package org.apache.poi.hpsf; -import static org.junit.Assert.*; -import static org.junit.Assert.assertNotNull; +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.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestVariantSupport { @Test @@ -52,10 +52,10 @@ public class TestVariantSupport { 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); + LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream((byte[])hdrs, 0); v.read(lei); TypedPropertyValue[] items = v.getValues(); @@ -70,7 +70,7 @@ public class TestVariantSupport { assertEquals(1, i); } - + @Test public void newNumberTypes() throws Exception { ClipboardData cd = new ClipboardData(); @@ -90,8 +90,7 @@ public class TestVariantSupport { {Variant.VT_R4, -999.99f}, {Variant.VT_R8, -999.99d}, }; - - HSSFWorkbook wb = new HSSFWorkbook(); + POIFSFileSystem poifs = new POIFSFileSystem(); DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation(); CustomProperties cpList = new CustomProperties(); @@ -99,7 +98,7 @@ public class TestVariantSupport { 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); @@ -108,14 +107,15 @@ public class TestVariantSupport { 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("property "+i, (byte[])o[1], (byte[])obj); + assertArrayEquals((byte[])o[1], (byte[])obj, "property "+i); } else { - assertEquals("property "+i, o[1], obj); + assertEquals(o[1], obj, "property "+i); } i++; } diff --git a/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java b/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java deleted file mode 100644 index dbb56451ac..0000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.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.hpsf.basic; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Test suite for org.apache.poi.hpsf.basic - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBasic.class, - TestClassID.class, - TestEmptyProperties.class, - TestHPSFBugs.class, - TestMetaDataIPI.class, - TestUnicode.class, - TestWrite.class, - TestWriteWellKnown.class -}) -public class AllPOIHPSFBasicTests { -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java b/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java index 13cce30251..dfccfdc235 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java @@ -17,9 +17,9 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -42,8 +42,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** *

Tests the basic HPSF functionality.

@@ -76,7 +76,7 @@ public final class TestBasic { * @exception FileNotFoundException if the file to be read does not exist. * @exception IOException if any other I/O exception occurs. */ - @Before + @BeforeEach public void setUp() throws IOException { final File data = samples.getFile("TestGermanWord90.doc"); poiFiles = Util.readPOIFiles(data); diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java b/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java index 7be9bbf3f7..5ded0baa1d 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java @@ -17,14 +17,15 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests ClassID structure. @@ -52,14 +53,14 @@ public final class TestClassID { * Try to write to a buffer that is too small. This should * throw an Exception */ - @Test(expected = ArrayStoreException.class) + @Test public void testWriteArrayStoreException1() { - new ClassID(BUF16, 0).write(new byte[15], 0); + assertThrows(ArrayStoreException.class, () -> new ClassID(BUF16, 0).write(new byte[15], 0)); } - @Test(expected = ArrayIndexOutOfBoundsException.class) + @Test public void testWriteArrayStoreException2() { - new ClassID(BUF16, 0).write(new byte[16], 1); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ClassID(BUF16, 0).write(new byte[16], 1)); } @Test diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java index bdc7c5b6de..dd1bf74e0b 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java @@ -17,9 +17,9 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -38,8 +38,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test case for OLE2 files with empty properties. @@ -69,7 +69,7 @@ public final class TestEmptyProperties { * does not exist * @exception IOException if an I/O exception occurs */ - @Before + @BeforeEach public void setUp() throws IOException { final File data = samples.getFile(POI_FS); poiFiles = Util.readPOIFiles(data); diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java b/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java index c5d4937239..a8cbbbbd95 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java @@ -17,9 +17,9 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -38,7 +38,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests various bugs have been fixed diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java index 9347699566..f3f0d35cd3 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java @@ -17,12 +17,11 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -38,9 +37,10 @@ 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.After; -import org.junit.Before; -import org.junit.Test; +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 @@ -52,7 +52,7 @@ public final class TestMetaDataIPI { private DocumentSummaryInformation dsi; private SummaryInformation si; - @After + @AfterEach public void tearDown() throws Exception { poifs.close(); } @@ -61,7 +61,7 @@ public final class TestMetaDataIPI { * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the * SummaryInformation to reasonable values */ - @Before + @BeforeEach public void setUp() throws Exception { poifs = new POIFSFileSystem(); dsi = PropertySetFactory.newDocumentSummaryInformation(); @@ -113,15 +113,15 @@ public final class TestMetaDataIPI { assertNotNull(dsi); assertNotNull(si); - assertEquals("Category", "xxxCategoryxxx", dsi.getCategory()); - assertEquals("Company", "xxxCompanyxxx", dsi.getCompany()); - assertEquals("Manager", "xxxManagerxxx", dsi.getManager()); + 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()); + 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, @@ -133,21 +133,21 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ String a1 = (String) customProperties.get("Key1"); - assertEquals("Key1", "Value1", a1); + assertEquals("Value1", a1, "Key1"); String a2 = (String) customProperties.get("Schl\u00fcssel2"); - assertEquals("Schl\u00fcssel2", "Wert2", a2); + assertEquals("Wert2", a2, "Schl\u00fcssel2"); Integer a3 = (Integer) customProperties.get("Sample Integer"); - assertEquals("Sample Number", 12345, (int)a3); + assertEquals(12345, (int)a3, "Sample Number"); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue("Sample Boolean", a4); + assertTrue(a4, "Sample Boolean"); Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); + assertEquals(date, a5, "Custom Date:"); Double a6 = (Double) customProperties.get("Sample Double"); - assertEquals("Custom Float", -1.0001, a6, 0); + assertEquals(-1.0001, a6, 0, "Custom Float"); Integer a7 = (Integer) customProperties.get("Sample Negative Integer"); - assertEquals("Neg", -100000, (int)a7); + assertEquals(-100000, (int)a7, "Neg"); } /** @@ -201,15 +201,15 @@ public final class TestMetaDataIPI { * 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", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); + 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()); + 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, @@ -217,21 +217,19 @@ public final class TestMetaDataIPI { * serve as a container for custom properties. */ customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } + assertNotNull(customProperties); /* Insert some custom properties into the container. */ String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); + assertEquals(p1, a1, "Key1"); String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); + assertEquals(p2, a2, "Schl\u00fcssel2"); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", 12345, (int)a3); + assertEquals(12345, (int)a3, "Sample Number"); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue("Sample Boolean", a4); + assertTrue(a4, "Sample Boolean"); Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); + assertEquals(date, a5, "Custom Date:"); } @@ -287,15 +285,15 @@ public final class TestMetaDataIPI { * 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", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); + 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()); + 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, @@ -303,22 +301,20 @@ public final class TestMetaDataIPI { * serve as a container for custom properties. */ customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } + assertNotNull(customProperties); /* Insert some custom properties into the container. */ // System.out.println(k1); String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); + assertEquals(p1, a1, "Key1"); String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); + assertEquals(p2, a2, "Schl\u00fcssel2"); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", 12345, (int)a3); + assertEquals(12345, (int)a3, "Sample Number"); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertFalse("Sample Boolean", a4); + assertFalse(a4, "Sample Boolean"); Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); + assertEquals(date, a5, "Custom Date:"); } @@ -380,15 +376,15 @@ public final class TestMetaDataIPI { * 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", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); + 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()); + 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, @@ -401,15 +397,15 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ // System.out.println(k1); String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); + assertEquals(p1, a1, "Key1"); String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); + assertEquals(p2, a2, "Schl\u00fcssel2"); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", 12345, (int)a3); + assertEquals(12345, (int)a3, "Sample Number"); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertTrue("Sample Boolean", a4); + assertTrue(a4, "Sample Boolean"); Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); + assertEquals(date, a5, "Custom Date:"); } @@ -479,38 +475,36 @@ public final class TestMetaDataIPI { * serve as a container for custom properties. */ customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } + assertNotNull(customProperties); /* Insert some custom properties into the container. */ Integer a3 = (Integer) customProperties.get("int"); - assertEquals("int", 12345, (int)a3); + assertEquals(12345, (int)a3, "int"); a3 = (Integer) customProperties.get("negint"); - assertEquals("negint", -12345, (int)a3); + assertEquals(-12345, (int)a3, "negint"); Long al = (Long) customProperties.get("neglong"); - assertEquals("neglong", -12345L, (long)al); + assertEquals(-12345L, (long)al, "neglong"); al = (Long) customProperties.get("long"); - assertEquals("long", 12345L, (long)al); + assertEquals(12345L, (long)al, "long"); Boolean a4 = (Boolean) customProperties.get("boolean"); - assertTrue("boolean", a4); + assertTrue(a4, "boolean"); Date a5 = (Date) customProperties.get("date"); - assertEquals("Custom Date:", date, a5); + assertEquals(date, a5, "Custom Date:"); Double d = (Double) customProperties.get("double"); - assertEquals("int", 12345.2, d, 0); + assertEquals(12345.2, d, 0, "int"); d = (Double) customProperties.get("negdouble"); - assertEquals("string", -12345.3, d, 0); + assertEquals(-12345.3, d, 0, "string"); String s = (String) customProperties.get("string"); - assertEquals("sring", "a String", s); + assertEquals("a String", s, "string"); assertTrue(customProperties.get("string") instanceof String); diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java b/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java index 4b6884165a..cc40ccd3d1 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java @@ -17,8 +17,8 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -29,7 +29,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; -import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.CustomProperties; @@ -42,43 +42,35 @@ 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.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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. */ -@RunWith(Parameterized.class) public class TestReadAllFiles { private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - @Parameters(name="{index}: {0} using {1}") - public static Iterable files() { + 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(file1 -> new Object[] {file1}). - collect(Collectors.toList()); + return Arrays.stream(files).map(Arguments::of); } - @Parameter() - public File file; - /** * This test methods reads all property set streams from all POI * filesystems in the "data" directory. */ - @Test - public void read() throws IOException, NoPropertySetStreamException, MarkUnsupportedException { + @ParameterizedTest + @MethodSource("files") + public 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())) { @@ -102,8 +94,9 @@ public class TestReadAllFiles { * the origin file and check whether they are equal. * */ - @Test - public void recreate() throws IOException, HPSFException { + @ParameterizedTest + @MethodSource("files") + public void recreate(File file) throws IOException, HPSFException { /* Read the POI filesystem's property set streams: */ Map psMap = new HashMap<>(); @@ -135,7 +128,7 @@ public class TestReadAllFiles { 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("Equality for file " + file.getName(), ps1str, ps2str); + assertEquals(ps1str, ps2str, "Equality for file " + file.getName()); } poiFs.close(); } @@ -147,8 +140,9 @@ public class TestReadAllFiles { * the document summary information stream in the root directory and calling * its get... methods. */ - @Test - public void readDocumentSummaryInformation() throws Exception { + @ParameterizedTest + @MethodSource("files") + public 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(); @@ -189,8 +183,9 @@ public class TestReadAllFiles { * * @throws Exception if anything goes wrong. */ - @Test - public void readCustomPropertiesFromFiles() throws Exception { + @ParameterizedTest + @MethodSource("files") + public void readCustomPropertiesFromFiles(File file) throws Exception { /* Read a test document doc into a POI filesystem. */ try (POIFSFileSystem poifs = new POIFSFileSystem(file)) { /* diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java b/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java index 3e3eafd495..498c9119e0 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java @@ -17,8 +17,8 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; @@ -33,8 +33,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests whether Unicode string can be read from a DocumentSummaryInformation. @@ -55,7 +55,7 @@ public class TestUnicode { * @exception FileNotFoundException if the file to be read does not exist. * @exception IOException if any other I/O exception occurs */ - @Before + @BeforeEach public void setUp() { POIDataSamples samples = POIDataSamples.getHPSFInstance(); data = samples.getFile(POI_FS); diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java index 688ea0088d..b8f59dfa67 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java @@ -19,12 +19,14 @@ package org.apache.poi.hpsf.basic; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -71,8 +73,8 @@ 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.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; /** * Tests HPSF's writing functionality @@ -120,7 +122,7 @@ public class TestWrite { * * @exception IOException if an I/O exception occurs */ - @Test(expected=NoFormatIDException.class) + @Test public void withoutAFormatID() throws Exception { final File filename = TempFile.createTempFile(POI_FS, ".doc"); @@ -134,7 +136,7 @@ public class TestWrite { try (OutputStream out = new FileOutputStream(filename); POIFSFileSystem poiFs = new POIFSFileSystem(); ByteArrayOutputStream psStream = new ByteArrayOutputStream()) { - ps.write(psStream); + assertThrows(NoFormatIDException.class, () -> ps.write(psStream)); poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); } @@ -270,11 +272,7 @@ public class TestWrite { final PropertySet[] psa = new PropertySet[1]; final POIFSReader r = new POIFSReader(); final POIFSReaderListener listener = (event) -> { - try { - psa[0] = PropertySetFactory.create(event.getStream()); - } catch (Exception ex) { - fail(ex.getMessage()); - } + assertDoesNotThrow(() -> psa[0] = PropertySetFactory.create(event.getStream())); }; r.registerListener(listener,STREAM_NAME); @@ -291,13 +289,7 @@ public class TestWrite { } private static POIFSReaderListener getListener(List psa) { - return event -> { - try { - psa.add(PropertySetFactory.create(event.getStream())); - } catch (Exception ex) { - fail(ex.getMessage()); - } - }; + return event -> assertDoesNotThrow(() -> psa.add(PropertySetFactory.create(event.getStream()))); } /** @@ -307,7 +299,7 @@ public class TestWrite { @Test public void variantTypes() throws Exception { final int codepage = CODEPAGE_DEFAULT; - Assume.assumeTrue(IMPROPER_DEFAULT_CHARSET_MESSAGE, hasProperDefaultCharset()); + Assumptions.assumeTrue(hasProperDefaultCharset(), IMPROPER_DEFAULT_CHARSET_MESSAGE); check(Variant.VT_EMPTY, null, codepage); check(Variant.VT_BOOL, Boolean.TRUE, codepage); @@ -358,12 +350,9 @@ public class TestWrite { final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815}; for (int cp : invalidCodepages) { - try { - checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - fail("UnsupportedEncodingException for codepage " + cp + " expected."); - } catch (UnsupportedEncodingException ex) { - /* This is the expected behaviour. */ - } + assertThrows(UnsupportedEncodingException.class, + () -> checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp), + "UnsupportedEncodingException for codepage " + cp + " expected."); } } @@ -683,7 +672,7 @@ public class TestWrite { * Tests writing and reading back a proper dictionary with an invalid * codepage. (HPSF writes Unicode dictionaries only.) */ - @Test(expected=UnsupportedEncodingException.class) + @Test public void dictionaryWithInvalidCodepage() throws IOException, HPSFException { final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); copy.deleteOnExit(); @@ -703,7 +692,7 @@ public class TestWrite { s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]); int codepage = 12345; s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); - poiFs.createDocument(ps1.toInputStream(), "Test"); + assertThrows(UnsupportedEncodingException.class, () -> poiFs.createDocument(ps1.toInputStream(), "Test")); poiFs.writeFilesystem(out); } } diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java index 152e04cf88..3d3c962a82 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java @@ -17,11 +17,11 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -51,8 +51,8 @@ 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.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** *

Tests HPSF's high-level writing functionality for the well-known property @@ -62,7 +62,7 @@ public class TestWriteWellKnown { private static final String POI_FS = "TestWriteWellKnown.doc"; - @BeforeClass + @BeforeAll public static void setUp() { VariantSupport.setLogUnsupportedTypes(false); } @@ -125,7 +125,7 @@ public class TestWriteWellKnown { 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 @@ -172,7 +172,7 @@ public class TestWriteWellKnown { @Test public 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"); @@ -182,14 +182,14 @@ public class TestWriteWellKnown { 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 @@ -268,17 +268,17 @@ public class TestWriteWellKnown { 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)); @@ -286,7 +286,7 @@ public class TestWriteWellKnown { // 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); @@ -298,10 +298,10 @@ public class TestWriteWellKnown { 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 @@ -419,10 +419,10 @@ public class TestWriteWellKnown { 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 @@ -491,7 +491,7 @@ public class TestWriteWellKnown { dis.close(); return si; } - + static DocumentSummaryInformation getDocumentSummaryInformation(POIFSFileSystem poifs) throws IOException, NoPropertySetStreamException, UnexpectedPropertySetTypeException { if (!poifs.getRoot().hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { diff --git a/src/testcases/org/apache/poi/hpsf/basic/Util.java b/src/testcases/org/apache/poi/hpsf/basic/Util.java index af4e4462a9..c6ef7ae6c7 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/Util.java +++ b/src/testcases/org/apache/poi/hpsf/basic/Util.java @@ -18,7 +18,8 @@ package org.apache.poi.hpsf.basic; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.FileNotFoundException; @@ -47,7 +48,7 @@ final class Util { * 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".) * @@ -55,28 +56,24 @@ final class Util { * * @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 + * + * @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 -> { - try { - 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); - } catch (IOException ex) { - fail(ex.getMessage()); - } - }; + 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); @@ -98,32 +95,28 @@ final class Util { *

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 -> { - try { - 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); - } - } catch (Exception ex) { - fail(ex.getMessage()); + 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); diff --git a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java b/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java index 9ea2fdd074..4c697074fa 100644 --- a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java +++ b/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java @@ -18,8 +18,8 @@ package org.apache.poi.hpsf.extractor; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -30,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestHPSFPropertiesExtractor { private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); diff --git a/src/testcases/org/apache/poi/hssf/HSSFTests.java b/src/testcases/org/apache/poi/hssf/HSSFTests.java deleted file mode 100644 index fa87897da8..0000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFTests.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; - -import org.apache.poi.hssf.eventmodel.TestEventRecordFactory; -import org.apache.poi.hssf.eventusermodel.AllEventUserModelTests; -import org.apache.poi.hssf.extractor.TestExcelExtractor; -import org.apache.poi.hssf.model.AllModelTests; -import org.apache.poi.hssf.record.AllRecordTests; -import org.apache.poi.hssf.usermodel.AllUserModelTests; -import org.apache.poi.hssf.util.AllHSSFUtilTests; -import org.apache.poi.ss.formula.AllSSFormulaTests; -import org.apache.poi.ss.util.AllSSUtilTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test Suite for all sub-packages of org.apache.poi.hssf
- */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllEventUserModelTests.class, - AllModelTests.class, - AllUserModelTests.class, - AllRecordTests.class, - AllHSSFUtilTests.class, - TestExcelExtractor.class, - TestEventRecordFactory.class, - AllSSFormulaTests.class, - AllSSUtilTests.class -}) -public final class HSSFTests { -} diff --git a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java index 823dc4418e..9eb7ffac66 100644 --- a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java +++ b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.hssf.dev; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.util.ArrayList; @@ -25,53 +25,45 @@ 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.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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. - * - * This test uses {@link Parameterized} to run the test for each file separatedely. */ -@RunWith(Parameterized.class) public abstract class BaseTestIteratingXLS { protected static final Map> EXCLUDED = new HashMap<>(); - @Parameters(name="{index}: {0}") - public static Iterable files() { + private static Stream files() { String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); if(dataDirName == null) { dataDirName = "test-data"; } - List files = new ArrayList<>(); + List files = new ArrayList<>(); findFile(files, dataDirName + "/spreadsheet"); findFile(files, dataDirName + "/hpsf"); - return files; + return files.stream(); } - private static void findFile(List list, String dir) { + private static void findFile(List list, String dir) { String[] files = new File(dir).list((arg0, arg1) -> arg1.toLowerCase(Locale.ROOT).endsWith(".xls")); - - assertNotNull("Did not find any xls files in directory " + dir, files); + assertNotNull(files, "Did not find any xls files in directory " + dir); for(String file : files) { - list.add(new Object[]{new File(dir, file)}); - } + list.add(Arguments.of(new File(dir, file))); } + } - @Parameter - public File file; - - @Test - public void testMain() throws Exception { + @ParameterizedTest + @MethodSource("files") + public void testMain(File file) throws Exception { String fileName = file.getName(); Class t = EXCLUDED.get(fileName); diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java index 406266d902..8724122f1f 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java @@ -25,10 +25,10 @@ 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.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class TestBiffDrawingToXml extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java index f5cce1b268..6130b1566d 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java @@ -27,10 +27,10 @@ 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.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class TestBiffViewer extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("35897-type4.xls", IllegalArgumentException.class); // unsupported crypto api header diff --git a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java index 20a7a635c9..f05167dcf7 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java @@ -25,10 +25,10 @@ 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.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class TestEFBiffViewer extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header diff --git a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java index a3eae963c8..a5b952396c 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.hssf.dev; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.io.PrintStream; @@ -26,10 +26,10 @@ 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.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class TestFormulaViewer extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header diff --git a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java index 8ab108378f..b03de96459 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.hssf.dev; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.PrintStream; @@ -27,12 +27,12 @@ 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.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestReSave extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header @@ -84,7 +84,7 @@ public class TestReSave extends BaseTestIteratingXLS { } } - @Ignore("Only used for local testing") + @Disabled("Only used for local testing") @Test public void testOneFile() throws Exception { String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); diff --git a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java index 3a1b9bb2fe..0950553125 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java @@ -23,10 +23,10 @@ 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.BeforeClass; +import org.junit.jupiter.api.BeforeAll; public class TestRecordLister extends BaseTestIteratingXLS { - @BeforeClass + @BeforeAll public static void setup() { EXCLUDED.clear(); EXCLUDED.put("46904.xls", OldExcelFormatException.class); diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java index 8a80b78393..973da0839f 100644 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java +++ b/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.eventmodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -31,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link AbortableHSSFListener} diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java index f579c4097e..0c93ffe5e1 100644 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java +++ b/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.eventmodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -40,8 +40,8 @@ import org.apache.poi.hssf.record.StandardRecord; import org.apache.poi.hssf.record.TestcaseRecordInputStream; import org.apache.poi.hssf.record.UnknownRecord; import org.apache.poi.util.NotImplemented; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * enclosing_type describe the purpose here @@ -65,7 +65,7 @@ public final class TestEventRecordFactory { ERFListener listener = rec -> { wascalled[0] = true; - assertEquals("must be BOFRecord got SID=" + rec.getSid(), rec.getSid(), BOFRecord.sid); + assertEquals(rec.getSid(), BOFRecord.sid, "must be BOFRecord got SID=" + rec.getSid()); return true; }; EventRecordFactory factory = new EventRecordFactory(listener, new short[] {BOFRecord.sid}); @@ -85,7 +85,7 @@ public final class TestEventRecordFactory { eof.serialize(offset,bytes); factory.processRecords(new ByteArrayInputStream(bytes)); - assertTrue("The record listener must be called", wascalled[0]); + assertTrue(wascalled[0], "The record listener must be called"); } @@ -107,7 +107,7 @@ public final class TestEventRecordFactory { Record[] records = RecordFactory.createRecord(TestcaseRecordInputStream.create(bytes)); - assertEquals("record.length must be 1, was =" + records.length, 1, records.length); + assertEquals(1, records.length, "record.length must be 1, was =" + records.length); byte[] rec1 = bof.serialize(); byte[] rec2 = records[0].serialize(); @@ -121,9 +121,8 @@ public final class TestEventRecordFactory { */ @NotImplemented @Test - @Ignore + @Disabled public void testCreateContinuedRecord() { - // fail("not implemented"); } @@ -145,7 +144,7 @@ public final class TestEventRecordFactory { } @Test - @Ignore("same as testContinuedUnknownRecord but with SequenceInputStream which causes the available() bug 59893") + @Disabled("same as testContinuedUnknownRecord but with SequenceInputStream which causes the available() bug 59893") public void bug59893() { Iterator iter = Stream.of(CONTINUE_DATA).map(ByteArrayInputStream::new).iterator(); SequenceInputStream sis = new SequenceInputStream(IteratorUtils.asEnumeration(iter)); @@ -164,6 +163,6 @@ public final class TestEventRecordFactory { }; EventRecordFactory factory = new EventRecordFactory(listener, new short[] {-256, 0x3C}); factory.processRecords(data); - assertFalse("left over input data", expectedData.hasNext()); + assertFalse(expectedData.hasNext(), "left over input data"); } } diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java b/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java deleted file mode 100644 index a5d9073759..0000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.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.eventusermodel; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.eventusermodel. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEventWorkbookBuilder.class, - TestFormatTrackingHSSFListener.class, - TestHSSFEventFactory.class, - TestMissingRecordAwareHSSFListener.class -}) -public class AllEventUserModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java index d639c2c3f8..df64164d0c 100644 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java +++ b/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.eventusermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -31,14 +31,13 @@ import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollec 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.record.Record; 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link EventWorkbookBuilder} @@ -47,7 +46,7 @@ public final class TestEventWorkbookBuilder { private final List fRecs = new ArrayList<>(); private SheetRecordCollectingListener listener; - @Before + @BeforeEach public void setUp() throws IOException { HSSFRequest req = new HSSFRequest(); fRecs.clear(); diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java index ad9640647d..e3ca90ca92 100644 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java +++ b/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.hssf.eventusermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -28,9 +28,9 @@ 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.hssf.record.Record; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; + /** * Tests for FormatTrackingHSSFListener */ @@ -43,14 +43,14 @@ public final class TestFormatTrackingHSSFListener { 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 public void testFormats() throws Exception { processFile("MissingBits.xls"); @@ -60,7 +60,7 @@ public final class TestFormatTrackingHSSFListener { 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. @@ -70,40 +70,40 @@ public final class TestFormatTrackingHSSFListener { */ @Test public void testTurnToString() throws Exception { - String[] files = new String[] { - "45365.xls", "45365-2.xls", "MissingBits.xls" + 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 + // 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<>(); diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java index cb1015f729..4cf5f77ae2 100644 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java +++ b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java @@ -17,10 +17,11 @@ package org.apache.poi.hssf.eventusermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -40,7 +41,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Testing for {@link HSSFEventFactory} @@ -115,11 +116,11 @@ public final class TestHSSFEventFactory { openSample("WORKBOOK_in_capitals.xls"); } - @Test(expected = EncryptedDocumentException.class) + @Test @SuppressWarnings("java:S2699") - public void testWithPasswordProtectedWorkbooksNoPass() throws Exception { + public void testWithPasswordProtectedWorkbooksNoPass() { // Without a password, can't be read - openSample("xor-encryption-abc.xls"); + assertThrows(EncryptedDocumentException.class, () -> openSample("xor-encryption-abc.xls")); } @Test @@ -157,10 +158,10 @@ public final class TestHSSFEventFactory { } } - assertTrue("Sheet record not found", hasSheet); - assertTrue("Numeric record for A1 not found", hasA1); - assertTrue("Numeric record for A2 not found", hasA2); - assertTrue("Numeric record for A3 not found", hasA3); + 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 index 29be9baab2..d89584cbf3 100644 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java +++ b/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.eventusermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -36,12 +36,11 @@ 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.Record; 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for MissingRecordAwareHSSFListener diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java index 139b03fb03..6d32039836 100644 --- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java +++ b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java @@ -19,9 +19,9 @@ package org.apache.poi.hssf.extractor; import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -34,7 +34,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java index 6403fe4e74..708cf2e94d 100644 --- a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java +++ b/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.extractor; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -38,8 +38,9 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Unit tests for the Excel 5/95 and Excel 4 (and older) text @@ -228,38 +229,31 @@ public final class TestOldExcelExtractor { } } - @Test(expected=OfficeXmlFileException.class) + @Test public void testOpenInvalidFile1() throws IOException { // a file that exists, but is a different format - createExtractor("WithVariousData.xlsx").close(); - } + assertThrows(OfficeXmlFileException.class, () -> createExtractor("WithVariousData.xlsx").close()); - - @Test(expected=RecordFormatException.class) - public void testOpenInvalidFile2() throws IOException { // a completely different type of file - createExtractor("48936-strings.txt").close(); - } + assertThrows(RecordFormatException.class, () -> createExtractor("48936-strings.txt").close()); - @Test(expected=FileNotFoundException.class) - public void testOpenInvalidFile3() throws IOException { // a POIFS file which is not a Workbook try (InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("47304.doc")) { - new OldExcelExtractor(is).close(); + assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(is).close()); } } - @Test(expected=EmptyFileException.class) - public void testOpenNonExistingFile() throws IOException { + @Test + public void testOpenNonExistingFile() { // a file that exists, but is a different format - new OldExcelExtractor(new File("notexistingfile.xls")).close(); + assertThrows(EmptyFileException.class, () -> new OldExcelExtractor(new File("notexistingfile.xls")).close()); } @Test public void testInputStream() throws IOException { File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); try (InputStream stream = new FileInputStream(file); - OldExcelExtractor extractor = new OldExcelExtractor(stream);) { + OldExcelExtractor extractor = new OldExcelExtractor(stream)) { String text = extractor.getText(); assertNotNull(text); } @@ -299,27 +293,23 @@ public final class TestOldExcelExtractor { } } - @Test(expected = FileNotFoundException.class) + @Test public void testDirectoryNodeInvalidFile() throws IOException { File file = POIDataSamples.getDocumentInstance().getFile("test.doc"); - try (POIFSFileSystem fs = new POIFSFileSystem(file); - OldExcelExtractor extractor = new OldExcelExtractor(fs.getRoot())) { - fail("Should throw exception here"); + try (POIFSFileSystem fs = new POIFSFileSystem(file)) { + assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(fs.getRoot())); } } - @Test(expected = ExitException.class) - public void testMainUsage() throws IOException { + @Test + public void testMainUsage() { PrintStream save = System.err; SecurityManager sm = System.getSecurityManager(); System.setSecurityManager(new NoExitSecurityManager()); try { - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - PrintStream str = new PrintStream(out, false, "UTF-8"); - System.setErr(str); - // calls System.exit() - OldExcelExtractor.main(new String[]{}); - } + System.setErr(new NullPrintStream()); + // calls System.exit() + assertThrows(ExitException.class, () -> OldExcelExtractor.main(new String[]{})); } finally { System.setSecurityManager(sm); System.setErr(save); @@ -336,13 +326,13 @@ public final class TestOldExcelExtractor { System.setOut(str); OldExcelExtractor.main(new String[] {file.getAbsolutePath()}); String string = out.toString("UTF-8"); - assertTrue("Had: " + string, string.contains("Table C-13--Lemons")); + assertTrue(string.contains("Table C-13--Lemons"), "Had: " + string); } finally { System.setOut(save); } } - @Test(expected = EncryptedDocumentException.class) + @Test public void testEncryptionException() throws IOException { //test file derives from Common Crawl File file = HSSFTestDataSamples.getSampleFile("60284.xls"); @@ -350,7 +340,7 @@ public final class TestOldExcelExtractor { try (OldExcelExtractor ex = new OldExcelExtractor(file)) { assertEquals(5, ex.getBiffVersion()); assertEquals(5, ex.getFileType()); - ex.getText(); + assertThrows(EncryptedDocumentException.class, ex::getText); } } diff --git a/src/testcases/org/apache/poi/hssf/model/AllModelTests.java b/src/testcases/org/apache/poi/hssf/model/AllModelTests.java deleted file mode 100644 index 419b7309b8..0000000000 --- a/src/testcases/org/apache/poi/hssf/model/AllModelTests.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.model; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.model. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDrawingManager2.class, - TestFormulaParser.class, - TestFormulaParserEval.class, - TestFormulaParserIf.class, - TestLinkTable.class, - TestOperandClassTransformer.class, - TestRowBlocksReader.class, - TestRVA.class, - TestSheet.class, - TestSheetAdditional.class, - TestWorkbook.class -}) -public final class AllModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java index 47918cfb0e..cac09fd549 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java +++ b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java @@ -17,12 +17,11 @@ package org.apache.poi.hssf.model; import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -32,6 +31,7 @@ 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; @@ -55,7 +55,10 @@ 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.Test; +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; public class TestDrawingAggregate { /** @@ -123,82 +126,69 @@ public class TestDrawingAggregate { } } + 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. */ - private static void assertWriteAndReadBack(HSSFWorkbook wb) throws IOException { - // 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(); + @ParameterizedTest + @MethodSource("samples") + public void testAllTestSamples(File file) throws IOException { + boolean ignoreParse = true; + try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(file.getName())) { + ignoreParse = false; - // compare aggregate.serialize() with raw bytes from the record stream - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(p); + // 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(); - byte[] dgBytes1 = info.getRawBytes(); - byte[] dgBytes2 = agg.serialize(); + // compare aggregate.serialize() with raw bytes from the record stream + EscherAggregate agg = HSSFTestHelper.getEscherAggregate(p); - assertEquals("different size of raw data ande aggregate.serialize()", dgBytes1.length, dgBytes2.length); - assertArrayEquals("raw drawing data (" + dgBytes1.length + " bytes) and aggregate.serialize() are different.", dgBytes1, dgBytes2); - } - } + byte[] dgBytes1 = info.getRawBytes(); + byte[] dgBytes2 = agg.serialize(); - if(aggs.size() != 0){ - 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("different size of drawing data before and after save", dgBytes1.length, dgBytes2.length); - assertArrayEquals("drawing data (" + dgBytes1.length + " bytes) before and after save is different.", dgBytes1, dgBytes2); + 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."); } } - wb2.close(); - } - } - /** - * test that we correctly read and write drawing aggregates - * in all .xls files in POI test samples - */ - @Test - public void testAllTestSamples() throws IOException { - File[] xls = new File(System.getProperty("POI.testdata.path"), "spreadsheet").listFiles( - (dir, name) -> name.endsWith(".xls") - ); - assertNotNull( - "Need to find files in test-data path, had path: " + new File(System.getProperty("POI.testdata.path"), "spreadsheet"), - xls); - for(File file : xls) { - HSSFWorkbook wb; - try { - wb = HSSFTestDataSamples.openSampleWorkbook(file.getName()); - } catch (Throwable e){ - // don't bother about files we cannot read - they are different bugs - // System.out.println("[WARN] Cannot read " + file.getName()); - continue; + 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."); + } + } + } } - try { - assertWriteAndReadBack(wb); - } catch (Exception e) { - String filename = file.getName(); - System.out.println("Drawing Aggregate re-write test failed for " + filename); - e.printStackTrace(System.out); - fail("Error when writing and re-reading workbook " + filename + "\n" + e); + } catch (Throwable e) { + // don't bother about files we cannot read - they are different bugs + if (!ignoreParse) { + throw e; } - wb.close(); } } @@ -223,7 +213,7 @@ public class TestDrawingAggregate { records.add(r); pos += bytesRead; } - assertEquals("data was not fully read", dgBytes.length, pos); + assertEquals(dgBytes.length, pos, "data was not fully read"); // serialize to byte array ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -292,8 +282,8 @@ public class TestDrawingAggregate { agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); assertNotNull(agg); byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } } @@ -313,8 +303,8 @@ public class TestDrawingAggregate { EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); assertNotNull(agg); byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } @@ -333,13 +323,13 @@ public class TestDrawingAggregate { EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); assertNotNull(agg); byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); + 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("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different"); } } @@ -357,11 +347,10 @@ public class TestDrawingAggregate { List records = isheet.getRecords(); // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 394, records.size()); + assertEquals(394, records.size(), "wrong size of sheet records stream"); // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); + 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); @@ -381,9 +370,7 @@ public class TestDrawingAggregate { } // the first record after the drawing block - assertTrue( - "records.get(389) is expected to be Window2", - records.get(389) instanceof WindowTwoRecord); + 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 @@ -391,18 +378,17 @@ public class TestDrawingAggregate { int loc = isheet.aggregateDrawingRecords(drawingManager, false); EscherAggregate agg = (EscherAggregate) records.get(loc); - assertEquals("wrong size of the aggregated sheet records stream", 25, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } @@ -425,11 +411,10 @@ public class TestDrawingAggregate { List records = isheet.getRecords(); // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 32, records.size()); + assertEquals(32, records.size(), "wrong size of sheet records stream"); // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); + 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); @@ -449,9 +434,7 @@ public class TestDrawingAggregate { byte[] dgBytes = toByteArray(dgRecords); // the first record after the drawing block - assertTrue( - "records.get(26) is expected to be Window2", - records.get(26) instanceof WindowTwoRecord); + 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 @@ -459,18 +442,17 @@ public class TestDrawingAggregate { int loc = isheet.aggregateDrawingRecords(drawingManager, false); EscherAggregate agg = (EscherAggregate) records.get(loc); - assertEquals("wrong size of the aggregated sheet records stream", 26, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } @@ -510,11 +492,10 @@ public class TestDrawingAggregate { List records = isheet.getRecords(); // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 46, records.size()); + assertEquals(46, records.size(), "wrong size of sheet records stream"); // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); + 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); @@ -534,9 +515,7 @@ public class TestDrawingAggregate { byte[] dgBytes = toByteArray(dgRecords); // the first record after the drawing block - assertTrue( - "records.get(39) is expected to be Window2", - records.get(39) instanceof WindowTwoRecord); + 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 @@ -544,18 +523,17 @@ public class TestDrawingAggregate { int loc = isheet.aggregateDrawingRecords(drawingManager, false); EscherAggregate agg = (EscherAggregate) records.get(loc); - assertEquals("wrong size of the aggregated sheet records stream", 27, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } @@ -571,11 +549,10 @@ public class TestDrawingAggregate { List records = isheet.getRecords(); // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 315, records.size()); + assertEquals(315, records.size(), "wrong size of sheet records stream"); // the last record before the drawing block - assertTrue( - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName(), - records.get(21) instanceof RowRecordsAggregate); + 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); @@ -594,9 +571,7 @@ public class TestDrawingAggregate { byte[] dgBytes = toByteArray(dgRecords); // the first record after the drawing block - assertTrue( - "records.get(300) is expected to be Window2", - records.get(300) instanceof WindowTwoRecord); + 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 @@ -604,18 +579,17 @@ public class TestDrawingAggregate { int loc = isheet.aggregateDrawingRecords(drawingManager, false); EscherAggregate agg = (EscherAggregate) records.get(loc); - assertEquals("wrong size of the aggregated sheet records stream", 38, records.size()); - assertTrue( - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName(), - records.get(21) instanceof RowRecordsAggregate); - assertTrue("records.get(22) is expected to be EscherAggregate but was " + records.get(22).getClass().getSimpleName(), - records.get(22) instanceof EscherAggregate); - assertTrue("records.get(23) is expected to be Window2 but was " + records.get(23).getClass().getSimpleName(), - records.get(23) instanceof WindowTwoRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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"); } } @@ -739,7 +713,7 @@ public class TestDrawingAggregate { }; int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray(); - assertArrayEquals("unexpected record.sid", expectedSids, actualSids); + assertArrayEquals(expectedSids, actualSids, "unexpected record.sid"); DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); @@ -752,14 +726,14 @@ public class TestDrawingAggregate { sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals("drawing was not fully aggregated", 2, records.size()); - assertTrue("expected EscherAggregate", records.get(0) instanceof EscherAggregate); - assertTrue("expected EOFRecord", records.get(1) instanceof EOFRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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 @@ -905,7 +879,7 @@ public class TestDrawingAggregate { }; int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray(); - assertArrayEquals("unexpected record.sid", expectedSids, actualSids); + assertArrayEquals(expectedSids, actualSids, "unexpected record.sid"); DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); @@ -917,14 +891,14 @@ public class TestDrawingAggregate { records.add(EOFRecord.instance); sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals("drawing was not fully aggregated", 2, records.size()); - assertTrue("expected EscherAggregate", records.get(0) instanceof EscherAggregate); - assertTrue("expected EOFRecord", records.get(1) instanceof EOFRecord); + 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data brefpore and after save is different", dgBytes, dgBytesAfterSave); + 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 index ca4e8cf230..13ca011eb1 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java +++ b/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java @@ -17,18 +17,18 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDggRecord; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestDrawingManager2 { private DrawingManager2 drawingManager2; private EscherDggRecord dgg; - @Before + @BeforeEach public void setUp() { dgg = new EscherDggRecord(); dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[0] ); diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java index a6ef067cf2..16cfe133e1 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java +++ b/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -60,12 +60,12 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test escher drawing - * + * * optionally the system setting "poi.deserialize.escher" can be set to {@code true} */ public class TestDrawingShapes { @@ -107,7 +107,7 @@ public class TestDrawingShapes { assertEquals(HSSFShape.LINEWIDTH_DEFAULT, shape.getLineWidth()); assertEquals(HSSFShape.LINESTYLE_SOLID, shape.getLineStyle()); assertFalse(shape.isNoFill()); - + EscherOptRecord opt = shape.getOptRecord(); assertEquals(7, opt.getEscherProperties().size()); @@ -284,7 +284,7 @@ public class TestDrawingShapes { assertFalse(shape.isNoFill()); assertEquals(shape.getLineStyle(), HSSFShape.LINESTYLE_DASHDOTGEL); assertEquals(shape.getLineStyleColor(), 0x616161); - assertEquals(HexDump.toHex(shape.getFillColor()), shape.getFillColor(), 0x2CE03D); + 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); @@ -307,8 +307,8 @@ public class TestDrawingShapes { EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1); // last shape ID cached in EscherDgRecord - EscherDgRecord dg1 = - agg1.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); + EscherDgRecord dg1 = agg1.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); + assertNotNull(dg1); assertEquals(1026, dg1.getLastMSOSPID()); // iterate over shapes and check shapeId @@ -319,14 +319,17 @@ public class TestDrawingShapes { 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(); } @@ -380,22 +383,23 @@ public class TestDrawingShapes { assertSame(opt1, opt2); wb.close(); } - + @Test public 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()); @@ -689,7 +693,7 @@ public class TestDrawingShapes { @Test public void testShapeContainerImplementsIterable() throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); - + HSSFSheet sheet = wb.createSheet(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); @@ -737,13 +741,13 @@ public class TestDrawingShapes { assertEquals(patriarch.getChildren().size(), 0); wb2.close(); } - + @Test public 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); @@ -771,7 +775,7 @@ public class TestDrawingShapes { shape1.setFlipHorizontal(true); shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); } - + checkWorkbookBack(wb); } } @@ -779,13 +783,13 @@ public class TestDrawingShapes { 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); @@ -843,7 +847,7 @@ public class TestDrawingShapes { 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 index a3776e5bdc..72e9e55941 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java +++ b/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java @@ -17,17 +17,18 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherTextboxRecord; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -37,7 +38,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestEscherRecordFactory { @@ -57,30 +58,30 @@ public class TestEscherRecordFactory { @Test public void testDetectContainer() { Random rnd = new Random(); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER)); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER)); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER)); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER)); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER)); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER)); + 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(DefaultEscherRecordFactory.isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i)); + for (short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){ + assertTrue(isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i)); } - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue())); + assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); + assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue())); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertTrue(DefaultEscherRecordFactory.isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID)); - assertFalse(DefaultEscherRecordFactory.isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID)); + 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 - public void testDgContainerMustBeRootOfHSSFSheetEscherRecords() throws IOException { + public void testDgContainerMustBeRootOfHSSFSheetEscherRecords() { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls"); HSSFSheet sh = wb.getSheetAt(0); InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); @@ -90,12 +91,14 @@ public class TestEscherRecordFactory { 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("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertArrayEquals("drawing data before and after save is different", dgBytes, dgBytesAfterSave); + 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 index 5a88f460b8..db7f6f1862 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java +++ b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java @@ -17,11 +17,14 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -48,7 +51,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test the low level formula parser functionality. High level tests are to @@ -61,7 +64,7 @@ public final class TestFormulaParser { */ /* package */ static Ptg[] parseFormula(String formula) { Ptg[] result = HSSFFormulaParser.parse(formula, null); - assertNotNull("Ptg array should not be null", result); + assertNotNull(result, "Ptg array should not be null"); return result; } private static String toFormulaString(Ptg[] ptgs) { @@ -279,18 +282,18 @@ public final class TestFormulaParser { String value = " hi "; Ptg[] ptgs = parseFormula("\"" + value + "\""); confirmTokenClasses(ptgs, StringPtg.class); - assertEquals("ptg0 contains exact value", ((StringPtg) ptgs[0]).getValue(), value); + assertEquals(((StringPtg) ptgs[0]).getValue(), value, "ptg0 contains exact value"); } @Test public void testLookupAndMatchFunctionArgs() { Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)"); confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class); - assertEquals("ptg0 has Value class", ptgs[0].getPtgClass(), Ptg.CLASS_VALUE); + 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("ptg0 has Value class", ptgs[0].getPtgClass(), Ptg.CLASS_VALUE); + assertEquals(ptgs[0].getPtgClass(), Ptg.CLASS_VALUE, "ptg0 has Value class"); } /** bug 33160*/ @@ -394,63 +397,63 @@ public final class TestFormulaParser { cell.setCellFormula("1.3E21/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1.3E+21/3", formula); + assertEquals("1.3E+21/3", formula); cell.setCellFormula("-1.3E21/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1.3E+21/3", formula); + assertEquals("-1.3E+21/3", formula); cell.setCellFormula("1322E21/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1.322E+24/3", formula); + assertEquals("1.322E+24/3", formula); cell.setCellFormula("-1322E21/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1.322E+24/3", formula); + assertEquals("-1.322E+24/3", formula); cell.setCellFormula("1.3E1/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "13/3", formula); + assertEquals("13/3", formula); cell.setCellFormula("-1.3E1/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-13/3", formula); + assertEquals("-13/3", formula); cell.setCellFormula("1.3E-4/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "0.00013/3", formula); + assertEquals("0.00013/3", formula); cell.setCellFormula("-1.3E-4/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-0.00013/3", formula); + assertEquals("-0.00013/3", formula); cell.setCellFormula("13E-15/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "0.000000000000013/3", formula); + assertEquals("0.000000000000013/3", formula); cell.setCellFormula("-13E-15/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-0.000000000000013/3", formula); + assertEquals("-0.000000000000013/3", formula); cell.setCellFormula("1.3E3/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1300/3", formula); + assertEquals("1300/3", formula); cell.setCellFormula("-1.3E3/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1300/3", formula); + assertEquals("-1300/3", formula); cell.setCellFormula("1300000000000000/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1300000000000000/3", formula); + assertEquals("1300000000000000/3", formula); cell.setCellFormula("-1300000000000000/3"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1300000000000000/3", formula); + assertEquals("-1300000000000000/3", formula); cell.setCellFormula("-10E-1/3.1E2*4E3/3E4"); formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1/310*4000/30000", formula); + assertEquals("-1/310*4000/30000", formula); wb.close(); } @@ -653,11 +656,10 @@ public final class TestFormulaParser { private static void confirmTokenClasses(Ptg[] ptgs, Class...expectedClasses) { assertEquals(expectedClasses.length, ptgs.length); for (int i = 0; i < expectedClasses.length; i++) { - if(expectedClasses[i] != ptgs[i].getClass()) { - fail("difference at token[" + i + "]: expected (" - + expectedClasses[i].getName() + ") but got (" - + ptgs[i].getClass().getName() + ")"); - } + assertEquals(expectedClasses[i], ptgs[i].getClass(), + "difference at token[" + i + "]: expected (" + + expectedClasses[i].getName() + ") but got (" + + ptgs[i].getClass().getName() + ")"); } } @@ -763,9 +765,7 @@ public final class TestFormulaParser { HSSFCell cell = row.createCell(0); cell.setCellFormula("right(\"test\"\"ing\", 3)"); String actualCellFormula = cell.getCellFormula(); - if ("RIGHT(\"test\"ing\",3)".equals(actualCellFormula)) { - fail("Identified bug 28754b"); - } + assertNotEquals("RIGHT(\"test\"ing\",3)", actualCellFormula, "Identified bug 28754b"); assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula); } } @@ -819,13 +819,8 @@ public final class TestFormulaParser { } private static void parseExpectedException(String formula) { - try { - parseFormula(formula); - fail("Expected FormulaParseException: " + formula); - } catch (FormulaParseException e) { - // expected during successful test - assertNotNull(e.getMessage()); - } + FormulaParseException e = assertThrows(FormulaParseException.class, () -> parseFormula(formula)); + assertNotNull(e.getMessage()); } @Test @@ -838,9 +833,7 @@ public final class TestFormulaParser { HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellFormula("SUM(A32769:A32770)"); - if("SUM(A-32767:A-32766)".equals(cell.getCellFormula())) { - fail("Identified bug 44539"); - } + assertNotEquals("SUM(A-32767:A-32766)", cell.getCellFormula(), "Identified bug 44539"); assertEquals("SUM(A32769:A32770)", cell.getCellFormula()); wb.close(); @@ -883,14 +876,10 @@ public final class TestFormulaParser { new IntPtg(1), DividePtg.instance, }; - try { - toFormulaString(ptgs); - fail("Expected exception was not thrown"); - } catch (IllegalStateException e) { - // expected during successful test - assertTrue(e.getMessage().startsWith("Too few arguments supplied to operation")); - } + 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.

@@ -904,9 +893,7 @@ public final class TestFormulaParser { Ptg[] ptgs = parseFormula("countif(A1:A2, 1)"); assertEquals(3, ptgs.length); - if(ptgs[2] instanceof FuncVarPtg) { - fail("Identified bug 44675"); - } + assertFalse(ptgs[2] instanceof FuncVarPtg, "Identified bug 44675"); confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class); confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class); @@ -921,34 +908,20 @@ public final class TestFormulaParser { } private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - try { - HSSFFormulaParser.parse(formula, book); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { + try (HSSFWorkbook book = new HSSFWorkbook()) { + FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, book)); confirmParseException(e, expectedMessage); } - book.close(); } @Test public 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 ')'"); - try { - parseFormula("round(3.14;2)"); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { - confirmParseException(e, - "Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'"); - } - - try { - parseFormula(" =2+2"); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { - confirmParseException(e, - "The specified formula ' =2+2' starts with an equals sign which is not allowed."); - } + e = assertThrows(FormulaParseException.class, () -> parseFormula(" =2+2")); + confirmParseException(e, "The specified formula ' =2+2' starts with an equals sign which is not allowed."); } /** @@ -972,36 +945,30 @@ public final class TestFormulaParser { @Test public void testNamedRangeThatLooksLikeCell() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFName name = wb.createName(); - name.setRefersToFormula("Sheet1!B1"); - name.setNameName("pfy1"); + 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"); + 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; } - wb.close(); - throw e; - } - confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class); + confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class); - HSSFCell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("count(pfy1)"); - assertEquals("COUNT(pfy1)", cell.getCellFormula()); - try { - cell.setCellFormula("count(pf1)"); - fail("Expected formula parse execption"); - } catch (FormulaParseException e) { - confirmParseException(e, - "Specified named range 'pf1' does not exist in the current workbook."); + 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 } - cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range - wb.close(); } @Test @@ -1014,9 +981,7 @@ public final class TestFormulaParser { ptgs = HSSFFormulaParser.parse("Sheet1!A10:A40000", book); aptg = (AreaI) ptgs[0]; - if (aptg.getLastRow() == -25537) { - fail("Identified bug 45358"); - } + assertNotEquals(-25537, aptg.getLastRow(), "Identified bug 45358"); assertEquals(39999, aptg.getLastRow()); ptgs = HSSFFormulaParser.parse("Sheet1!A10:A65536", book); @@ -1050,10 +1015,8 @@ public final class TestFormulaParser { ptgs = parseFormula("MAX({\"5\"},3)"); confirmTokenClasses(ptgs, ArrayPtg.class, IntPtg.class, FuncVarPtg.class); Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - if (element instanceof UnicodeString) { - // this would cause ClassCastException below - fail("Wrong encoding of array element value"); - } + // 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 @@ -1354,28 +1317,27 @@ public final class TestFormulaParser { @Test public void testRangeFuncOperand_bug46951() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse("SUM(C1:OFFSET(C1,0,B1))", wb); - } catch (RuntimeException e) { - if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) { - fail("Identified bug 46951"); + 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; } - wb.close(); - 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 ] + ); } - 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 ] - ); - wb.close(); } @Test @@ -1507,13 +1469,8 @@ public final class TestFormulaParser { } private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) { - - try { - HSSFFormulaParser.parse(formula, wb); - fail("Expected formula parse execption"); - } catch (FormulaParseException e) { - confirmParseException(e, expectedMessage); - } + FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, wb)); + confirmParseException(e, expectedMessage); } /** @@ -1524,29 +1481,27 @@ public final class TestFormulaParser { public void testParseComplexName() throws IOException { // Mock up a spreadsheet to match the critical details of the sample - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - HSSFName definedName = wb.createName(); - definedName.setNameName("foo"); - definedName.setRefersToFormula("Sheet1!B2"); + 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 + // 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"); + 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; } - wb.close(); - throw e; + confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class); } - confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class); - - wb.close(); } /** @@ -1562,23 +1517,16 @@ public final class TestFormulaParser { String leadingZeroCellRef = "B000001"; // this should get parsed as "B1" HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFFormulaParser.parse(badCellRef, wb); - fail("Identified bug 47312b - Shouldn't be able to parse cell ref '" - + badCellRef + "'."); - } catch (FormulaParseException e) { - // expected during successful test - confirmParseException(e, "Specified named range '" - + badCellRef + "' does not exist in the current workbook."); - } + 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 e) { - confirmParseException(e, "Specified named range '" - + leadingZeroCellRef + "' does not exist in the current workbook."); + } 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'."); } @@ -1601,7 +1549,7 @@ public final class TestFormulaParser { public void test57196_Formula() throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); Ptg[] ptgs = HSSFFormulaParser.parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1); - assertNotNull("Ptg array should not be null", ptgs); + assertNotNull(ptgs, "Ptg array should not be null"); confirmTokenClasses(ptgs, NameXPtg.class, // ?? diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java index aba91ad718..d948695620 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java +++ b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -30,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test the low level formula parser functionality, @@ -70,7 +70,7 @@ public final class TestFormulaParserEval { */ private static void confirmParseFormula(HSSFWorkbook workbook) { Ptg[] ptgs = HSSFFormulaParser.parse("SUM(testName)", workbook); - assertEquals("two tokens expected, got " + ptgs.length, 2, ptgs.length); + assertEquals(2, ptgs.length, "two tokens expected, got " + ptgs.length); assertEquals(NamePtg.class, ptgs[0].getClass()); assertEquals(AttrPtg.class, ptgs[1].getClass()); } diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java index 6897ccb88c..42f650a549 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java +++ b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -33,7 +33,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests FormulaParser specifically with respect to IF() functions @@ -49,7 +49,7 @@ public final class TestFormulaParserIf { private static void confirmAttrData(Ptg[] ptgs, int i, int expectedData) { Ptg ptg = ptgs[i]; - assertTrue("Token[" + i + "] was not AttrPtg as expected", ptg instanceof AttrPtg); + assertTrue(ptg instanceof AttrPtg, "Token[" + i + "] was not AttrPtg as expected"); AttrPtg attrPtg = (AttrPtg) ptg; assertEquals(expectedData, attrPtg.getData()); } @@ -164,24 +164,24 @@ public final class TestFormulaParserIf { Ptg[] ptgs = parseFormula("IF(3>=1,\"*\",IF(4<>1,\"first\",\"second\"))"); assertEquals(17, ptgs.length); - assertEquals("6th Ptg is not a goto (Attr) ptg",AttrPtg.class,ptgs[5].getClass()); - assertEquals("9th Ptg is not a not equal ptg",NotEqualPtg.class,ptgs[8].getClass()); - assertEquals("15th Ptg is not the inner IF variable function ptg",FuncVarPtg.class,ptgs[14].getClass()); + 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 public void testSimpleLogical() { Ptg[] ptgs = parseFormula("IF(A1OperandClassTransformer. @@ -41,7 +41,7 @@ public final class TestOperandClassTransformer { private static Ptg[] parseFormula(String formula) { Ptg[] result = HSSFFormulaParser.parse(formula, null); - assertNotNull("Ptg array should not be null", result); + assertNotNull(result, "Ptg array should not be null"); return result; } @@ -79,7 +79,7 @@ public final class TestOperandClassTransformer { * This test has been added but disabled in order to document this issue. */ @Test - @Ignore + @Disabled public void testIndexPi1() { String formula = "INDEX(PI(),1)"; Ptg[] ptgs = parseFormula(formula); @@ -144,7 +144,7 @@ public final class TestOperandClassTransformer { private void confirmTokenClass(Ptg[] ptgs, int i, byte operandClass) { Ptg ptg = ptgs[i]; - assertFalse("ptg[" + i + "] is a base token", ptg.isBaseToken()); + 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 index 20bc884622..8ca28bb6fc 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestRVA.java +++ b/src/testcases/org/apache/poi/hssf/model/TestRVA.java @@ -17,12 +17,13 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.stream.Stream; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.FormulaExtractor; @@ -34,19 +35,16 @@ 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.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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). */ -@RunWith(Parameterized.class) public final class TestRVA { private static final String NEW_LINE = System.getProperty("line.separator"); @@ -54,25 +52,19 @@ public final class TestRVA { private static HSSFWorkbook workbook; - @Parameter(value = 0) - public HSSFCell formulaCell; - @Parameter(value = 1) - public String formula; - - @AfterClass + @AfterAll public static void closeResource() throws Exception { workbook.close(); poifs.close(); } - @Parameters(name="{1}") - public static Collection data() throws Exception { + 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<>(); - + List data = new ArrayList<>(); + for (int rowIdx = 0; true; rowIdx++) { HSSFRow row = sheet.getRow(rowIdx); if (row == null) { @@ -84,29 +76,29 @@ public final class TestRVA { } String formula = cell.getCellFormula(); - data.add(new Object[]{cell,formula}); + data.add(Arguments.of(cell,formula)); } - - return data; + + return data.stream(); } - - @Test - public void confirmCell() { + + @ParameterizedTest + @MethodSource("data") + public 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) { - if (nExcelTokens == nPoiTokens + 1 && excelPtgs[0].getClass() == AttrPtg.class) { - // 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; - } else { - fail("Expected " + nExcelTokens + " tokens but got " + 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(); diff --git a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java b/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java index bf1fce7996..aa9b4c4c6a 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java +++ b/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java @@ -17,10 +17,11 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; @@ -31,7 +32,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RowBlocksReader} @@ -51,10 +52,9 @@ public final class TestRowBlocksReader { }; RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); RowBlocksReader rbr = new RowBlocksReader(rs); - if (rs.peekNextClass() == WindowTwoRecord.class) { - // Should have stopped at the SXVIEW record - fail("Identified bug 46280b"); - } + 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()); diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheet.java b/src/testcases/org/apache/poi/hssf/model/TestSheet.java index 8042be6e0e..bdc27459c6 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestSheet.java +++ b/src/testcases/org/apache/poi/hssf/model/TestSheet.java @@ -17,12 +17,13 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -44,7 +45,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Unit test for the {@link InternalSheet} class. @@ -112,7 +113,7 @@ public final class TestSheet { for (int n = 0; n < regionsToAdd; n++) { int index = sheet.addMergedRegion(0, (short) 0, 1, (short) 1); - assertEquals("Merged region index expected to be " + n + " got " + index, index, n); + assertEquals(index, n, "Merged region index expected to be " + n + " got " + index); } //test all the regions were indeed added @@ -127,23 +128,16 @@ public final class TestSheet { if ((regionsToAdd % 1027) != 0) { recordsExpected++; } - assertEquals("The " + regionsToAdd + " merged regions should have been spread out over " - + recordsExpected + " records, not " + recordsAdded, recordsAdded, 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 - try { - sheet.addMergedRegion(10, (short)10, 9, (short)12); - fail("Expected an exception to occur"); - } catch(IllegalArgumentException e) { - // occurs during successful test - assertEquals("The 'to' row (9) must not be less than the 'from' row (10)", e.getMessage()); - } - try { - sheet.addMergedRegion(10, (short)10, 12, (short)9); - fail("Expected an exception to occur"); - } catch(IllegalArgumentException e) { - // occurs during successful test - assertEquals("The 'to' col (9) must not be less than the 'from' col (10)", e.getMessage()); - } + 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 @@ -162,12 +156,12 @@ public final class TestSheet { { sheet.removeMergedRegion(0); //assert they have been deleted - assertEquals("Num of regions", regionsToAdd - n - 1, sheet.getNumMergedRegions()); + 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("Sheet Records", nSheetRecords, sheet.getRecords().size()); + assertEquals(nSheetRecords, sheet.getRecords().size(), "Sheet Records"); } /** @@ -199,7 +193,7 @@ public final class TestSheet { //stub object to throw off list INDEX operations sheet.removeMergedRegion(0); - assertEquals("Should be no more merged regions", 0, sheet.getNumMergedRegions()); + assertEquals(0, sheet.getNumMergedRegions(), "Should be no more merged regions"); } // @Test @@ -233,7 +227,7 @@ public final class TestSheet { records.add(EOFRecord.instance); InternalSheet sheet = createSheet(records); - assertNotNull("Row [2] was skipped", sheet.getRow(2)); + assertNotNull(sheet.getRow(2), "Row [2] was skipped"); } /** @@ -249,21 +243,21 @@ public final class TestSheet { PageSettingsBlock sheet = worksheet.getPageSettings(); sheet.setRowBreak(0, colFrom, colTo); - assertTrue("no row break at 0", sheet.isRowBroken(0)); - assertEquals("1 row break available", 1, sheet.getNumRowBreaks()); + 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("no row break at 0", sheet.isRowBroken(0)); - assertEquals("1 row break available", 1, sheet.getNumRowBreaks()); + 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("no row break at 10", sheet.isRowBroken(10)); - assertTrue("no row break at 11", sheet.isRowBroken(11)); - assertEquals("3 row break available", 3, sheet.getNumRowBreaks()); + 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; @@ -272,24 +266,24 @@ public final class TestSheet { int[] rowBreaks = sheet.getRowBreaks(); for (int main : rowBreaks) { - if (main != 0 && main != 10 && main != 11) fail("Invalid page break"); + assertTrue(main == 0 || main == 10 || main == 11, "Invalid page break"); if (main == 0) is0 = true; - if (main == 10) is10= true; + if (main == 10) is10 = true; if (main == 11) is11 = true; } - assertTrue("one of the breaks didnt make it", is0 && is10 && is11); + assertTrue(is0 && is10 && is11, "one of the breaks didnt make it"); sheet.removeRowBreak(11); - assertFalse("row should be removed", sheet.isRowBroken(11)); + assertFalse(sheet.isRowBroken(11), "row should be removed"); sheet.removeRowBreak(0); - assertFalse("row should be removed", sheet.isRowBroken(0)); + assertFalse(sheet.isRowBroken(0), "row should be removed"); sheet.removeRowBreak(10); - assertFalse("row should be removed", sheet.isRowBroken(10)); + assertFalse(sheet.isRowBroken(10), "row should be removed"); - assertEquals("no more breaks", 0, sheet.getNumRowBreaks()); + assertEquals(0, sheet.getNumRowBreaks(), "no more breaks"); } /** @@ -305,22 +299,22 @@ public final class TestSheet { PageSettingsBlock sheet = worksheet.getPageSettings(); sheet.setColumnBreak((short)0, rowFrom, rowTo); - assertTrue("no col break at 0", sheet.isColumnBroken(0)); - assertEquals("1 col break available", 1, sheet.getNumColumnBreaks()); + assertTrue(sheet.isColumnBroken(0), "no col break at 0"); + assertEquals(1, sheet.getNumColumnBreaks(), "1 col break available"); sheet.setColumnBreak((short)0, rowFrom, rowTo); - assertTrue("no col break at 0", sheet.isColumnBroken(0)); - assertEquals("1 col break available", 1, sheet.getNumColumnBreaks()); + 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("no col break at 1", sheet.isColumnBroken(1)); - assertTrue("no col break at 10", sheet.isColumnBroken(10)); - assertTrue("no col break at 15", sheet.isColumnBroken(15)); - assertEquals("4 col break available", 4, sheet.getNumColumnBreaks()); + 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; @@ -329,28 +323,28 @@ public final class TestSheet { int[] colBreaks = sheet.getColumnBreaks(); for (int main : colBreaks) { - if (main != 0 && main != 1 && main != 10 && main != 15) fail("Invalid page break"); + 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("one of the breaks didnt make it", is0 && is1 && is10 && is15); + assertTrue(is0 && is1 && is10 && is15, "one of the breaks didnt make it"); sheet.removeColumnBreak(15); - assertFalse("column break should not be there", sheet.isColumnBroken(15)); + assertFalse(sheet.isColumnBroken(15), "column break should not be there"); sheet.removeColumnBreak(0); - assertFalse("column break should not be there", sheet.isColumnBroken(0)); + assertFalse(sheet.isColumnBroken(0), "column break should not be there"); sheet.removeColumnBreak(1); - assertFalse("column break should not be there", sheet.isColumnBroken(1)); + assertFalse(sheet.isColumnBroken(1), "column break should not be there"); sheet.removeColumnBreak(10); - assertFalse("column break should not be there", sheet.isColumnBroken(10)); + assertFalse(sheet.isColumnBroken(10), "column break should not be there"); - assertEquals("no more breaks", 0, sheet.getNumColumnBreaks()); + assertEquals(0, sheet.getNumColumnBreaks(), "no more breaks"); } /** @@ -447,7 +441,7 @@ public final class TestSheet { sheet.visitContainedRecords(r -> { int estimatedSize = r.getRecordSize(); int serializedSize = r.serialize(0, buf); - assertEquals("serialized size mismatch for record (" + r.getClass().getName() + ")", estimatedSize, serializedSize); + assertEquals(estimatedSize, serializedSize, "serialized size mismatch for record (" + r.getClass().getName() + ")"); totalSize[0] += estimatedSize; }, 0); assertEquals(90, totalSize[0]); @@ -540,17 +534,13 @@ public final class TestSheet { @Test public void testMisplacedMergedCellsRecords_bug45699() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(3); - HSSFCell cell = row.getCell(4); - if (cell == null) { - fail("Identified bug 45699"); + 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()); } - assertEquals("Informations", cell.getRichStringCellValue().getString()); - - wb.close(); } /** * In 3.1, setting margins between creating first row and first cell caused an exception. diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java index c0ef0fd7dc..974a336553 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java +++ b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +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.Test; +import org.junit.jupiter.api.Test; public final class TestSheetAdditional { @Test diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java index bc8db67c85..ee9b06d0fd 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.model; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -36,7 +36,7 @@ import org.apache.poi.ss.formula.functions.FreeRefFunction; import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; import org.apache.poi.ss.formula.udf.DefaultUDFFinder; import org.apache.poi.ss.formula.udf.UDFFinder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit test for the Workbook class. @@ -161,15 +161,13 @@ public final class TestWorkbook { InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb); int oldRecordsCount = iwb.getNumRecords(); - //System.out.println("records count = " + oldRecordsCount); - assertEquals("records count", 68, oldRecordsCount); + assertEquals(68, oldRecordsCount, "records count"); WriteAccessRecord writeAccess = iwb.getWriteAccess(); assertNotNull(writeAccess); assertEquals(WriteAccessRecord.sid, writeAccess.getSid()); int newRecordsCount = iwb.getNumRecords(); - //System.out.println("records count after 'getWriteAccess' = " + newRecordsCount); - assertEquals("records count after getWriteAccess", oldRecordsCount, newRecordsCount); + assertEquals(oldRecordsCount, newRecordsCount, "records count after getWriteAccess"); } } diff --git a/src/testcases/org/apache/poi/hssf/record/AllRecordTests.java b/src/testcases/org/apache/poi/hssf/record/AllRecordTests.java deleted file mode 100644 index e32816756c..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/AllRecordTests.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 org.apache.poi.hssf.record.aggregates.AllRecordAggregateTests; -import org.apache.poi.hssf.record.cf.TestCellRange; -import org.apache.poi.hssf.record.chart.AllChartRecordTests; -import org.apache.poi.hssf.record.common.TestUnicodeString; -import org.apache.poi.hssf.record.pivot.AllPivotRecordTests; -import org.apache.poi.poifs.crypt.AllEncryptionTests; -import org.apache.poi.ss.formula.constant.TestConstantValueParser; -import org.apache.poi.ss.formula.ptg.AllFormulaTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllChartRecordTests.class, - AllEncryptionTests.class, - AllFormulaTests.class, - AllPivotRecordTests.class, - AllRecordAggregateTests.class, - TestArrayRecord.class, - TestBOFRecord.class, - TestBoolErrRecord.class, - TestBoundSheetRecord.class, - TestCellRange.class, - TestCFHeaderRecord.class, - TestCFRuleRecord.class, - TestColumnInfoRecord.class, - TestCommonObjectDataSubRecord.class, - TestConstantValueParser.class, - TestDVALRecord.class, - TestDrawingGroupRecord.class, - TestDrawingRecord.class, - TestEmbeddedObjectRefSubRecord.class, - TestEndSubRecord.class, - TestEscherAggregate.class, - TestExtendedFormatRecord.class, - TestExternalNameRecord.class, - TestFeatRecord.class, - TestFontRecord.class, - TestFormulaRecord.class, - TestHyperlinkRecord.class, - TestInterfaceEndRecord.class, - TestLabelRecord.class, - TestLbsDataSubRecord.class, - TestMergeCellsRecord.class, - TestNameRecord.class, - TestNoteRecord.class, - TestNoteStructureSubRecord.class, - TestObjRecord.class, - //TestPaletteRecord.class, //converted to junit4 - TestPaneRecord.class, - TestPLVRecord.class, - TestRecalcIdRecord.class, - TestRecordFactory.class, - TestRecordFactoryInputStream.class, - TestRecordInputStream.class, - TestSCLRecord.class, - TestSSTDeserializer.class, - TestSSTRecord.class, - TestSSTRecordSizeCalculator.class, - TestSharedFormulaRecord.class, - TestStringRecord.class, - TestStyleRecord.class, - TestSubRecord.class, - TestSupBookRecord.class, - TestTableRecord.class, - TestTextObjectBaseRecord.class, - TestTextObjectRecord.class, - TestUnicodeNameRecord.class, - TestUnicodeString.class, - TestWriteAccessRecord.class, - TestDConRefRecord.class -}) -public final class AllRecordTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java b/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java index d84b514b08..a7da3501f7 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -31,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestArrayRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java index 2baf72b8a4..daa41fc8d2 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the AutoFilterInfoRecord class. diff --git a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java index f63993e424..a73e0aacf6 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java @@ -17,14 +17,14 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestBOFRecord { @Test diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java index ee5d8af5c3..a281b5f009 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link BoolErrRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java index 4f2f32904f..48b2796d2c 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java @@ -17,16 +17,17 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests BoundSheetRecord. @@ -45,10 +46,10 @@ public final class TestBoundSheetRecord { assertEquals(24, record.getRecordSize()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testName() { BoundSheetRecord record = new BoundSheetRecord("1234567890223456789032345678904"); - record.setSheetname("s//*s"); + assertThrows(IllegalArgumentException.class, () -> record.setSheetname("s//*s")); } @Test diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java index 484cfc0b7d..68b5bad564 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java @@ -18,12 +18,12 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the {@link CFHeaderRecord} @@ -133,7 +133,7 @@ public final class TestCFHeaderRecord { CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - assertEquals("#CFRULES", 3, record.getNumberOfConditionalFormats()); + assertEquals(3, record.getNumberOfConditionalFormats(), "#CFRULES"); assertTrue(record.getNeedRecalculation()); confirm(record.getEnclosingCellRange(), 0, 3, 0, 3); CellRangeAddress[] ranges = record.getCellRanges(); @@ -180,7 +180,7 @@ public final class TestCFHeaderRecord { // bug 44739b - invalid cell range (-25536, 2, -15536, 2) CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - assertEquals("#CFRULES", 19, record.getNumberOfConditionalFormats()); + assertEquals(19, record.getNumberOfConditionalFormats(), "#CFRULES"); assertFalse(record.getNeedRecalculation()); confirm(record.getEnclosingCellRange(), 0, 65535, 0, 255); CellRangeAddress[] ranges = record.getCellRanges(); @@ -194,9 +194,9 @@ public final class TestCFHeaderRecord { } private static void confirm(CellRangeAddress cr, int expFirstRow, int expLastRow, int expFirstCol, int expLastColumn) { - assertEquals("first row", expFirstRow, cr.getFirstRow()); - assertEquals("last row", expLastRow, cr.getLastRow()); - assertEquals("first column", expFirstCol, cr.getFirstColumn()); - assertEquals("last column", expLastColumn, cr.getLastColumn()); + 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 index c0aa3629ea..ea5462dd33 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java @@ -18,12 +18,12 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -42,7 +42,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TestCFRuleRecord @@ -387,8 +387,9 @@ public final class TestCFRuleRecord { assertEquals(3, LittleEndian.getShort(data, 8)); int flags = LittleEndian.getInt(data, 10); - assertEquals("unused flags should be 111", 0x00380000, flags & 0x00380000); - assertEquals("undocumented flags should be 0000", 0, flags & 0x03C00000); // Otherwise Excel gets unhappy + 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); } @@ -415,7 +416,7 @@ public final class TestCFRuleRecord { CFRuleRecord rr = new CFRuleRecord(is); Ptg[] ptgs = rr.getParsedExpression1(); assertEquals(3, ptgs.length); - assertFalse("Identified bug 45234", ptgs[0] instanceof RefPtg); + assertFalse(ptgs[0] instanceof RefPtg, "Identified bug 45234"); assertEquals(RefNPtg.class, ptgs[0].getClass()); RefNPtg refNPtg = (RefNPtg) ptgs[0]; assertTrue(refNPtg.isColRelative()); diff --git a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java index 0d57714618..1910a96f7b 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ColumnInfoRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java index d46cda971c..c79165fec2 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java @@ -19,11 +19,11 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the {@link CommonObjectDataSubRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java index 259cd9b2a3..c9797cc6f0 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java @@ -19,17 +19,17 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Unit tests for DConRefRecord class. @@ -214,7 +214,7 @@ public class TestDConRefRecord { d.serialize(o); o.flush(); - assertArrayEquals(message, data, bos.toByteArray()); + assertArrayEquals(data, bos.toByteArray(), message); } /** @@ -241,14 +241,14 @@ public class TestDConRefRecord { DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); int expResult = data1.length; int result = instance.getDataSize(); - assertEquals("single byte external reference, volume type path data size", expResult, result); + assertEquals(expResult, result, "single byte external reference, volume type path data size"); instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertEquals("double byte self reference data size", data2.length, instance.getDataSize()); + assertEquals(data2.length, instance.getDataSize(), "double byte self reference data size"); instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data3)); - assertEquals("single byte self reference data size", data3.length, instance.getDataSize()); + assertEquals(data3.length, instance.getDataSize(), "single byte self reference data size"); instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data4)); - assertEquals("double byte external reference, UNC volume type path data size", data4.length, - instance.getDataSize()); + assertEquals(data4.length, instance.getDataSize(), + "double byte external reference, UNC volume type path data size"); } /** @@ -259,7 +259,7 @@ public class TestDConRefRecord { DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); short expResult = 81; short result = instance.getSid(); - assertEquals("SID", expResult, result); + assertEquals(expResult, result, "SID"); } /** @@ -271,7 +271,7 @@ public class TestDConRefRecord { DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); byte[] expResult = Arrays.copyOfRange(data1, 9, data1.length); byte[] result = instance.getPath(); - assertArrayEquals("get path", expResult, result); + assertArrayEquals(expResult, result, "get path"); } /** @@ -280,8 +280,8 @@ public class TestDConRefRecord { @Test public void testIsExternalRef() { DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - assertTrue("external reference", instance.isExternalRef()); + assertTrue(instance.isExternalRef(), "external reference"); instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertFalse("internal reference", instance.isExternalRef()); + 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 index 3e8ab9811e..83fff74ae8 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestDVALRecord { @Test @@ -45,7 +45,7 @@ public final class TestDVALRecord { assertEquals(56, dv.getHorizontalPos()); assertEquals(57, dv.getVerticalPos()); assertEquals(58, dv.getObjectID()); - assertNotEquals("Identified bug 44510",0, dv.getDVRecNo()); + 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 index acee4f2727..042c3ec348 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java @@ -18,12 +18,12 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.cut; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestDrawingGroupRecord { private static final int MAX_RECORD_SIZE = 8228; diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java index 9b2c650c42..1aa1cefa88 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -27,7 +27,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestDrawingRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java index b8b1e20bd8..ac3f6b56e7 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java @@ -18,11 +18,11 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java index fa5d9c7233..306c60d451 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java @@ -18,9 +18,9 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the EndSubRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java b/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java index 32c0750336..761256479b 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests the EscherAggregate class. diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java index 0d6bf167af..5ad4a65830 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestExtSSTRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java index 71de921dcc..632a6f1cf2 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java @@ -18,9 +18,9 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestExtendedFormatRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java index 3bb3c8394a..bca4bbe6fe 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java @@ -18,15 +18,15 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public final class TestExternalNameRecord { @@ -64,7 +64,7 @@ public final class TestExternalNameRecord { @Test public void testBasicSize() { ExternalNameRecord enr = createSimpleENR(dataFDS); - assertNotEquals("Identified bug 44695",13, enr.getRecordSize()); + assertNotEquals(13, enr.getRecordSize(), "Identified bug 44695"); assertEquals(17, enr.getRecordSize()); assertNotNull(enr.serialize()); diff --git a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java index fe56976545..74b06b172e 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -32,7 +32,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for FeatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java index 69f6254f96..2a24c80143 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java @@ -19,13 +19,13 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the {@link FontRecord} @@ -111,7 +111,7 @@ public final class TestFontRecord { byte [] recordBytes = other.serialize(); assertEquals(recordBytes.length - 4, data.length); for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); + assertEquals(data[i], recordBytes[i+4], "At offset " + i); } @Test diff --git a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java index bd454365e1..180a8d0521 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link FormulaRecord} @@ -83,17 +83,18 @@ public final class TestFormulaRecord { }; FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals("Row", 0, record.getRow()); - assertEquals("Column", 0, record.getColumn()); + 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(); - assertEquals("Output size", 33, output.length); //includes sid+recordlength + // includes sid+recordlength + assertEquals(33, output.length, "Output size"); for (int i = 5; i < 13;i++) { - assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]); + assertEquals(formulaByte[i], output[i+4], "FormulaByte NaN doesn't match"); } } @@ -111,11 +112,12 @@ public final class TestFormulaRecord { formulaByte[20]=(byte)0x05; formulaByte[22]=(byte)0x01; FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals("Row", 0, record.getRow()); - assertEquals("Column", 0, record.getColumn()); + assertEquals(0, record.getRow(), "Row"); + assertEquals(0, record.getColumn(), "Column"); byte[] output = record.serialize(); - assertEquals("Output size", 31, output.length); //includes sid+recordlength - assertEquals("Offset 22", 1, output[26]); + // includes sid+recordlength + assertEquals(31, output.length, "Output size"); + assertEquals(1, output[26], "Offset 22"); } @Test @@ -191,7 +193,7 @@ public final class TestFormulaRecord { fr0.setCachedResultBoolean(false); fr1.setCachedResultBoolean(true); - assertFalse("Identified bug 46479c", fr0.getCachedBooleanValue() && !fr1.getCachedBooleanValue()); + 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 index 1a1204c2f5..985fe64eaa 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the FtCblsSubRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java b/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java index 269bbd1adb..cbcb0a493f 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -33,7 +33,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test HyperlinkRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java b/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java index f085cf15c8..96e844486c 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the EndSubRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java index ec5ed36689..f1f93ffe95 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java @@ -17,14 +17,14 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for LabelRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java index ab54970fb1..71e2504761 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -33,7 +33,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the LbsDataSubRecord class works correctly. diff --git a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java b/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java index fa4dc0b1e5..f19e428355 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; import java.util.ArrayList; import java.util.List; @@ -26,7 +26,7 @@ import java.util.List; 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.Test; +import org.junit.jupiter.api.Test; /** @@ -43,15 +43,15 @@ public final class TestMergeCellsRecord { MergeCellsRecord merge = new MergeCellsRecord(cras, 0, cras.length); MergeCellsRecord clone = merge.copy(); - assertNotSame("Merged and cloned objects are the same", merge, clone); + assertNotSame(merge, clone, "Merged and cloned objects are the same"); CellRangeAddress mergeRegion = merge.getAreaAt(0); CellRangeAddress cloneRegion = clone.getAreaAt(0); - assertNotSame("Should not point to same objects when cloning", mergeRegion, cloneRegion); - assertEquals("New Clone Row From doesnt match", mergeRegion.getFirstRow(), cloneRegion.getFirstRow()); - assertEquals("New Clone Row To doesnt match", mergeRegion.getLastRow(), cloneRegion.getLastRow()); - assertEquals("New Clone Col From doesnt match", mergeRegion.getFirstColumn(), cloneRegion.getFirstColumn()); - assertEquals("New Clone Col To doesnt match", mergeRegion.getLastColumn(), cloneRegion.getLastColumn()); + 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)); } diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java index 062784675f..20fa58db33 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the NameCommentRecord serializes/deserializes correctly diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java index 7dfdf4f8ee..3c0f267bd7 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -34,7 +34,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests the NameRecord serializes/deserializes correctly diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java index c2ccad9a4a..cbec6a7573 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the NoteRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java index 358a1431c6..b1692389d7 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the NoteRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java b/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java index c6cb9ac26f..54b9cd3cac 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java @@ -18,16 +18,16 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the ObjRecord class works correctly. @@ -111,11 +111,7 @@ public final class TestObjRecord { @Test public void testReadWriteWithPadding_bug45133() { ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(recdataNeedingPadding)); - - if (record.getRecordSize() == 34) { - fail("Identified bug 45133"); - } - + assertNotEquals(34, record.getRecordSize(), "Identified bug 45133"); assertEquals(36, record.getRecordSize()); List subrecords = record.getSubRecords(); diff --git a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java index 94c8bca18d..653335cf69 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java @@ -25,7 +25,7 @@ import org.apache.poi.hssf.usermodel.HSSFDataValidation; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.DataValidationConstraint; import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Verify that presence of PLV record doesn't break data diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java index 321b6e3129..d1805300b1 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java @@ -17,13 +17,14 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Verifies that custom palette editing works correctly @@ -46,9 +47,10 @@ public final class TestPaletteRecord { byte[] paletteTriplet = palette.getColor((short) index); String msg = "Expected HSSFColor constant to match PaletteRecord at index" + (index == c.getIndex2() ? "2" : "") + " 0x" + Integer.toHexString(index); - assertEquals(msg, rgbTriplet[0], paletteTriplet[0] & 0xff); - assertEquals(msg, rgbTriplet[1], paletteTriplet[1] & 0xff); - assertEquals(msg, rgbTriplet[2], paletteTriplet[2] & 0xff); + 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 index f787ef25e5..906a73f6fd 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java @@ -19,9 +19,9 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the PaneRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java b/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java index bbaeae4a23..7662a95d5b 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java @@ -18,11 +18,11 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestRecalcIdRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java index 2e67f25b7d..103eeace7d 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -27,7 +27,7 @@ import java.util.List; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the record factory @@ -123,25 +123,19 @@ public final class TestRecordFactory { ByteArrayInputStream bois = new ByteArrayInputStream(data); Record[] records = RecordFactory.createRecords(bois).toArray(new Record[0]); - assertEquals("Created record count", 3, records.length); - assertEquals("1st record's type", - UnknownRecord.class.getName(), - records[ 0 ].getClass().getName()); - assertEquals("1st record's sid", (short)-256, records[0].getSid()); - assertEquals("2nd record's type", - ContinueRecord.class.getName(), - records[ 1 ].getClass().getName()); + 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("2nd record's sid", 0x3C, record.getSid()); - assertEquals("1st data byte", 1, record.getData()[ 0 ]); - assertEquals("2nd data byte", 2, record.getData()[ 1 ]); - assertEquals("3rd data byte", 3, record.getData()[ 2 ]); - assertEquals("3rd record's type", - ContinueRecord.class.getName(), - records[ 2 ].getClass().getName()); + 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("3nd record's sid", 0x3C, record.getSid()); - assertEquals("4th data byte", 4, record.getData()[ 0 ]); + assertEquals(0x3C, record.getSid(), "3nd record's sid"); + assertEquals(4, record.getData()[ 0 ], "4th data byte"); } /** @@ -151,10 +145,8 @@ public final class TestRecordFactory { */ @Test public void testMixedContinue() throws IOException { - /** - * Adapted from a real test sample file 39512.xls (Offset 0x4854). - * See Bug 39512 for details. - */ + // 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 " + diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java index 757da3c9ca..89604135b5 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java @@ -17,17 +17,17 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RecordFactoryInputStream} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java index ebd0db6cf2..e01048fe24 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RecordInputStream} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java index 561a966861..cfe9f1ebea 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java @@ -19,9 +19,9 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SCLRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java index 17a5a8852f..5c0c88c3b8 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; @@ -26,7 +26,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Exercise the SSTDeserializer class. @@ -42,7 +42,7 @@ public final class TestSSTDeserializer { 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); @@ -57,7 +57,7 @@ public final class TestSSTDeserializer { 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 ); @@ -88,7 +88,7 @@ public final class TestSSTDeserializer { 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<>(); @@ -104,7 +104,7 @@ public final class TestSSTDeserializer { 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); @@ -115,7 +115,7 @@ public final class TestSSTDeserializer { 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); diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java index 96ff3ad6ac..9b030894a8 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +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; @@ -39,7 +39,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestSSTRecord { @@ -339,9 +339,9 @@ public final class TestSSTRecord { * deep comparison of two SST records */ private static void assertRecordEquals(SSTRecord expected, SSTRecord actual){ - assertEquals("number of strings", expected.getNumStrings(), actual.getNumStrings()); - assertEquals("number of unique strings", expected.getNumUniqueStrings(), actual.getNumUniqueStrings()); - assertEquals("count of strings", expected.countStrings(), actual.countStrings()); + 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(); diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java index e9dd0798fa..2c26a91f54 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests that records size calculates correctly. diff --git a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java index a5cc315975..b24f02af78 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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; @@ -39,7 +39,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestSharedFormulaRecord { @@ -87,14 +87,14 @@ public final class TestSharedFormulaRecord { RefPtg refPtg = (RefPtg) convertedFormula[1]; assertEquals("$C101", refPtg.toFormulaString()); - assertNotEquals("Identified bug 45123", Ptg.CLASS_REF, refPtg.getPtgClass()); + 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("Different operand class", exp, act); + assertArrayEquals(exp, act, "Different operand class"); } @Test diff --git a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java index e113837a2a..ed1282152d 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java @@ -18,15 +18,16 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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 org.apache.poi.util.HexRead; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the StringRecord @@ -58,10 +59,10 @@ public final class TestStringRecord { byte [] recordBytes = record.serialize(); assertEquals(recordBytes.length - 4, data.length); for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, data[i], recordBytes[i+4]); + assertEquals(data[i], recordBytes[i+4], "At offset " + i); } } - + @Test public void testContinue() throws IOException { int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE; @@ -77,9 +78,8 @@ public final class TestStringRecord { sr.setString(sb.toString()); byte[] ser = sr.serialize(); assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0)); - if (LittleEndian.getUShort(ser, 2) > MAX_BIFF_DATA) { - fail("StringRecord should have been split with a continue record"); - } + 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)); diff --git a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java index a2236addc9..068ea327b2 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link StyleRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java index 10377c23f3..608e5a9050 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java @@ -20,15 +20,15 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests Subrecord components of an OBJ record. Test data taken directly @@ -79,7 +79,7 @@ public final class TestSubRecord { RecordInputStream in = TestcaseRecordInputStream.create(dataAutoFilter); ObjRecord or = new ObjRecord(in); byte[] data2 = or.serialize(); - assertNotEquals("Identified bug 45778", 8228, data2.length); + assertNotEquals(8228, data2.length, "Identified bug 45778"); assertEquals(74, data2.length); assertArrayEquals(dataAutoFilter, data2); } @@ -100,9 +100,9 @@ public final class TestSubRecord { RecordInputStream in = TestcaseRecordInputStream.create(data); ObjRecord or = new ObjRecord(in); byte[] data2 = or.serialize(); - assertNotEquals("Identified bug 45778", 8228, data2.length); - assertEquals("Encoded length", data.length, data2.length); - assertArrayEquals("Encoded data differs", data, data2); + assertNotEquals(8228, data2.length, "Identified bug 45778"); + assertEquals(data.length, data2.length, "Encoded length"); + assertArrayEquals(data, data2, "Encoded data differs"); } /** diff --git a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java index da8f6a1576..4ad7a39d35 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java @@ -27,10 +27,10 @@ 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.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SupBook record diff --git a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java index 7f052df943..0ce1f53b92 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TableRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java index dd327048b7..7823705ea9 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java @@ -18,13 +18,13 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TextObjectBaseRecord diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java index 2b57c2fc03..9456aa985a 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests that serialization and deserialization of the TextObjectRecord . @@ -97,7 +97,7 @@ public final class TestTextObjectRecord { byte [] ser = record.serialize(); int formatDataLen = LittleEndian.getUShort(ser, 16); - assertEquals("formatDataLength", 0, formatDataLen); + assertEquals(0, formatDataLen, "formatDataLength"); assertEquals(22, ser.length); // just the TXO record diff --git a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java index 03e3a17919..55f80ed678 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertNotNull; +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.Test; +import org.junit.jupiter.api.Test; public final class TestUnicodeNameRecord { diff --git a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java b/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java index 38806d9020..2187479fc9 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link WriteAccessRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java index 4acc5f71e3..93c62912a9 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java +++ b/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.record; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -85,7 +85,7 @@ public final class TestcaseRecordInputStream { */ public static void confirmRecordEncoding(String msgPrefix, int expectedSid, byte[] expectedData, byte[] actualRecordBytes) { int expectedDataSize = expectedData.length; - assertEquals("Size of encode data mismatch", actualRecordBytes.length - 4, expectedDataSize); + 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)); diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java b/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java deleted file mode 100644 index 4edf3eb9c0..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.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.hssf.record.aggregates; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record.aggregates. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCFRecordsAggregate.class, - TestColumnInfoRecordsAggregate.class, - TestFormulaRecordAggregate.class, - TestRowRecordsAggregate.class, - TestSharedValueManager.class, - TestValueRecordsAggregate.class, - TestPageSettingsBlock.class -}) -public final class AllRecordAggregateTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java index e5fb8e769d..f930fadf1d 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -36,13 +36,12 @@ 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.Record; 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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the CFRecordsAggregate @@ -138,7 +137,7 @@ public final class TestCFRecordsAggregate { agg.serialize(0, serializedRecord); int nRules = LittleEndian.getUShort(serializedRecord, 4); - assertNotEquals("Identified bug 45682 b", 0, nRules); + assertNotEquals(0, nRules, "Identified bug 45682 b"); assertEquals(rules.length, nRules); } @@ -150,27 +149,20 @@ public final class TestCFRecordsAggregate { new CellRangeAddress(0,1,0,0), new CellRangeAddress(0,1,2,2), }; - CFRuleBase[] rules = { + CFRuleBase[] rules1 = { CFRuleRecord.create(sheet, "7"), CFRule12Record.create(sheet, ComparisonOperator.BETWEEN, "2", "5"), }; - try { - new CFRecordsAggregate(cellRanges, rules); - fail("Shouldn't be able to mix between types"); - } catch (IllegalArgumentException e) { - // expected here - } + + assertThrows(IllegalArgumentException.class, () -> new CFRecordsAggregate(cellRanges, rules1), + "Shouldn't be able to mix between types"); - rules = new CFRuleBase[] { CFRuleRecord.create(sheet, "7") }; - CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules); + CFRuleBase[] rules2 = { CFRuleRecord.create(sheet, "7") }; + CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules2); assertTrue(agg.getHeader().getNeedRecalculation()); - try { - agg.addRule(CFRule12Record.create(sheet, "7")); - fail("Shouldn't be able to mix between types"); - } catch (IllegalArgumentException e) { - // expected here - } + 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 index 569ffbc8fc..238f74e3b4 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java @@ -17,16 +17,15 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Record; import org.apache.poi.hssf.record.RecordBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestColumnInfoRecordsAggregate { @@ -109,7 +108,7 @@ public final class TestColumnInfoRecordsAggregate { cirs.clear(); agg.visitContainedRecords(cirs::add); assertEquals(4, cirs.size()); - assertTrue("Inner group should still be hidden", ((ColumnInfoRecord)cirs.get(1)).getHidden()); + 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); @@ -119,10 +118,10 @@ public final class TestColumnInfoRecordsAggregate { 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", startColIx, cir.getFirstColumn()); - assertEquals("endColIx", endColIx, cir.getLastColumn()); - assertEquals("level", level, cir.getOutlineLevel()); - assertEquals("hidden", isHidden, cir.getHidden()); - assertEquals("collapsed", isCollapsed, cir.getCollapsed()); + 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 index 798fa54b5a..d31f3d837f 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java @@ -17,23 +17,22 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Record; 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.Test; +import org.junit.jupiter.api.Test; public final class TestFormulaRecordAggregate { diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java index 2f4217400b..c7822c28f0 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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; @@ -55,7 +55,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tess for {@link PageSettingsBlock} @@ -228,7 +228,7 @@ public final class TestPageSettingsBlock { List outRecs = new ArrayList<>(); psb.visitContainedRecords(outRecs::add); - assertNotEquals("PageSettingsBlock didn't add missing header/footer records", 2, outRecs.size()); + 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}; diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java index c6b44be8f4..f0b2b671f6 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java @@ -17,10 +17,11 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +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; @@ -41,7 +42,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RowRecordsAggregate} @@ -58,8 +59,8 @@ public final class TestRowRecordsAggregate { RowRecord rr1 = rra.getRow(4); assertNotNull(rr1); - assertEquals("Row number is 1", 4, rr1.getRowNumber()); - assertSame("Row record retrieved is identical ", rr1, rr); + assertEquals(4, rr1.getRowNumber(), "Row number is 1"); + assertSame(rr1, rr, "Row record retrieved is identical "); } /** @@ -108,11 +109,8 @@ public final class TestRowRecordsAggregate { if (rec.getClass() == shfClass) { result++; Record prevRec = recs.get(i-1); - if (!(prevRec instanceof FormulaRecord)) { - fail("Bad record order at index " - + i + ": Formula record expected but got (" - + prevRec.getClass().getName() + ")"); - } + assertTrue(prevRec instanceof FormulaRecord, + "Bad record order at index " + i + ": Formula record expected but got (" + prevRec.getClass().getName() + ")"); verifySharedFormula((FormulaRecord) prevRec, rec); } } diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java index 8c2a47e14c..2790da2cc9 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.Collection; import java.util.HashMap; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link SharedValueManager} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java index 477affdbf0..44f9656e19 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.record.aggregates; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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 static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -44,7 +44,7 @@ import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ValueRecordsAggregate} @@ -78,8 +78,8 @@ public final class TestValueRecordsAggregate { assertEquals(1, cvrs.size()); CellValueRecordInterface record = cvrs.get(0); - assertNotNull( "Row contains a value", record ); - assertTrue( "First record is a FormulaRecordsAggregate", ( record instanceof FormulaRecordAggregate ) ); + assertNotNull( record, "Row contains a value" ); + assertTrue( ( record instanceof FormulaRecordAggregate ), "First record is a FormulaRecordsAggregate"); } private void constructValueRecord(List records) { @@ -258,13 +258,13 @@ public final class TestValueRecordsAggregate { String cellFormula; cellFormula = getFormulaFromFirstCell(s, 0); // row "1" // the problem is not observable in the first row of the shared formula - assertEquals("Something else wrong with this test case", "\"first formula\"", cellFormula); + 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("found bug 44449 (Wrong SharedFormulaRecord was used).", "\"second formula\"", cellFormula); + assertNotEquals("\"second formula\"", cellFormula, "found bug 44449 (Wrong SharedFormulaRecord was used)."); - assertEquals("Something else wrong with this test case", "\"first formula\"", cellFormula); + assertEquals("\"first formula\"", cellFormula, "Something else wrong with this test case"); wb.close(); } diff --git a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java b/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java index 639edca2b3..aa59f19b88 100644 --- a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java +++ b/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java @@ -17,15 +17,15 @@ limitations under the License. package org.apache.poi.hssf.record.cf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests CellRange operations. @@ -78,7 +78,7 @@ public final class TestCellRange { for(int j=0; j!=ranges.length;j++) { boolean expectedResult = containsExpectedResults[i][j]; - assertEquals("("+i+","+j+"): ", expectedResult, CellRangeUtil.contains(ranges[i], ranges[j])); + assertEquals(expectedResult, CellRangeUtil.contains(ranges[i], ranges[j]), "("+i+","+j+"): "); } } } @@ -169,8 +169,8 @@ public final class TestCellRange { public void testCreate() { CellRangeAddress cr = createCR(0, -1, 2, 255); // $C:$IV - assertFalse("isFullRowRange", cr.isFullRowRange()); - assertTrue("isFullColumnRange", cr.isFullColumnRange()); + assertFalse(cr.isFullRowRange(), "isFullRowRange"); + assertTrue(cr.isFullColumnRange(), "isFullColumnRange"); createCR(0, 7, 1, 1); // $B$1:$B$8 @@ -249,11 +249,11 @@ public final class TestCellRange { // } private void verifyExpectedResult(CellRangeAddress[] result, String... expectedOutput) { - assertEquals("\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result), - expectedOutput.length, result.length); + assertEquals(expectedOutput.length, result.length, + "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result)); for(int i = 0;i < expectedOutput.length;i++) { - assertEquals("\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result), - expectedOutput[i], result[i].formatAsString()); + assertEquals(expectedOutput[i], result[i].formatAsString(), + "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result)); } } diff --git a/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java b/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java deleted file mode 100644 index 0f0c698681..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.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 org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record.class. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaFormatRecord.class, - TestAreaRecord.class, - TestAxisLineFormatRecord.class, - TestAxisOptionsRecord.class, - TestAxisParentRecord.class, - TestAxisRecord.class, - TestAxisUsedRecord.class, - TestBarRecord.class, - TestCategorySeriesAxisRecord.class, - TestChartFormatRecord.class, - TestChartRecord.class, - TestChartTitleFormatRecord.class, - TestDatRecord.class, - TestDataFormatRecord.class, - TestDefaultDataLabelTextPropertiesRecord.class, - TestFontBasisRecord.class, - TestFontIndexRecord.class, - TestFrameRecord.class, - TestLegendRecord.class, - TestLineFormatRecord.class, - TestLinkedDataRecord.class, - TestNumberFormatIndexRecord.class, - TestObjectLinkRecord.class, - TestPlotAreaRecord.class, - TestPlotGrowthRecord.class, - TestSeriesChartGroupIndexRecord.class, - TestSeriesIndexRecord.class, - TestSeriesLabelsRecord.class, - TestSeriesListRecord.class, - TestSeriesRecord.class, - TestSeriesTextRecord.class, - TestSheetPropertiesRecord.class, - TestTextRecord.class, - TestTickRecord.class, - TestUnitsRecord.class, - TestValueRangeRecord.class -}) -public class AllChartRecordTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java index 9df58a8427..c8684fd20d 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AreaFormatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java index 1bf68f0558..0143a3fe0b 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AreaRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java index ac12f27119..d7cd652e46 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AxisLineFormatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java index d17dcfa765..906544cf0a 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AxisOptionsRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java index 7f12260a89..581611161f 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AxisParentRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java index 56ba5d58a3..7065c50f89 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AxisRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java index b2907aa5ea..13bc7826e7 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the AxisUsedRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java index ca4f581612..911e72828b 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java @@ -19,11 +19,11 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the BarRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java index d23783b755..52ea943d21 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the CategorySeriesAxisRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java index 8d497e8699..ce6ede8437 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java @@ -17,14 +17,14 @@ package org.apache.poi.hssf.record.chart; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ChartFormatRecord} Test data taken directly from a real @@ -48,7 +48,7 @@ public final class TestChartFormatRecord { public void testLoad() { RecordInputStream in = TestcaseRecordInputStream.create(data); ChartFormatRecord record = new ChartFormatRecord(in); - assertNotEquals("Identified bug 44693d", 2, in.remaining()); + assertNotEquals(2, in.remaining(), "Identified bug 44693d"); assertEquals(0, in.remaining()); assertEquals(24, record.getRecordSize()); diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java index 545e236623..621fa7676d 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the ChartRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java index 53774be9ac..eb3894ba4a 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.record.chart; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.InputStream; import java.util.ArrayList; @@ -27,10 +27,9 @@ 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.record.Record; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestChartTitleFormatRecord { @@ -38,10 +37,10 @@ public final class TestChartTitleFormatRecord { public 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(); @@ -51,21 +50,21 @@ public final class TestChartTitleFormatRecord { 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<>(); } @@ -76,6 +75,6 @@ public final class TestChartTitleFormatRecord { 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 index adce7880dc..71b0c6901c 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the DatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java index 47b22d6a5d..b304166a5d 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java @@ -19,11 +19,11 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the DataFormatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java index 1dd31d92d6..fe54c3d6c2 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the DefaultDataLabelTextPropertiesRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java index d478945fbd..ce95d58328 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the FontBasisRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java index 1f055491af..0bb9d954e7 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the FontIndexRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java index 86e2729d4c..86ab6691fc 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the FrameRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java index 16eaf33b72..1965bcf776 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java @@ -18,12 +18,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the LegendRecord class works diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java index 7305134f35..dd2e5a60c5 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the LineFormatRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java index ae5b652b9a..91bb43f998 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java @@ -19,13 +19,13 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the LinkedDataRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java index c5efa00df4..b2fe6db59c 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the NumberFormatIndexRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java index 8913ca60d6..1641270e37 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the ObjectLinkRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java index ece7eefd91..119cf47117 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.record.chart; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the PlotAreaRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java index f12474fa54..235d144bbc 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the PlotGrowthRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java index ea674198c9..27aec2c93b 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesChartGroupIndexRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java index 1607f88cbd..92c54e4a47 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesIndexRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java index 232a1f7b70..1454da7474 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesLabelsRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java index fe310f233b..49cf366d84 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesListRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java index dd6c944881..2fd3d4384c 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java index 138415f49f..59dcb4b2ac 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java @@ -18,13 +18,13 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the SeriesTextRecord class @@ -88,7 +88,7 @@ public final class TestSeriesTextRecord { // "Bad requested string length (-126)" SeriesTextRecord str = new SeriesTextRecord(in); - assertTrue("Identified bug 45784b", str.getRecordSize() >= 0); + 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 index fb9273fb30..2fc545854e 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java @@ -19,14 +19,14 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link SheetPropertiesRecord} @@ -43,7 +43,7 @@ public final class TestSheetPropertiesRecord { public void testLoad() { RecordInputStream in = TestcaseRecordInputStream.create(0x1044, data); SheetPropertiesRecord record = new SheetPropertiesRecord(in); - assertNotEquals("Identified bug 44693c", 1, in.remaining()); + assertNotEquals(1, in.remaining(), "Identified bug 44693c"); assertEquals(0, in.remaining()); assertEquals( 10, record.getFlags()); assertFalse(record.isChartTypeManuallyFormatted()); diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java index 5e0b854743..99de874822 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TextRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java index 7b64608cda..7e5395f583 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java @@ -19,11 +19,11 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the TickRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java index f99c6a4e87..5996f909c5 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java @@ -19,10 +19,10 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the UnitsRecord diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java index 5c5fe7bf69..d0314e1ae5 100644 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java @@ -19,12 +19,12 @@ package org.apache.poi.hssf.record.chart; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests the serialization and deserialization of the ValueRangeRecord diff --git a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java b/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java index f1016745bb..ab43d21e3d 100644 --- a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java +++ b/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.record.common; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -41,7 +41,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests that {@link UnicodeString} record size calculates correctly. The record size diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/AllPivotRecordTests.java b/src/testcases/org/apache/poi/hssf/record/pivot/AllPivotRecordTests.java deleted file mode 100644 index 3f25e99398..0000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/AllPivotRecordTests.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.record.pivot; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.record.pivot. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestExtendedPivotTableViewFieldsRecord.class, - TestPageItemRecord.class, - TestViewFieldsRecord.class -}) -public final class AllPivotRecordTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java index 113951d32c..314fbdd686 100644 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java @@ -18,13 +18,13 @@ package org.apache.poi.hssf.record.pivot; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ExtendedPivotTableViewFieldsRecord} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java index 1468fc1401..e9f7ff1f36 100644 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.record.pivot; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link PageItemRecord} @@ -36,7 +36,7 @@ public final class TestPageItemRecord { 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("Identified bug 46917", 6, in.remaining()); + assertNotEquals(6, in.remaining(), "Identified bug 46917"); assertEquals(0, in.remaining()); assertEquals(4+data.length, rec.getRecordSize()); diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java index 3ab92651b3..c51da99e2e 100644 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java +++ b/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.record.pivot; import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ViewFieldsRecord} @@ -37,7 +37,7 @@ public final class TestViewFieldsRecord { 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("Identified bug 46693b", 1, in.remaining()); + assertNotEquals(1, in.remaining(), "Identified bug 46693b"); assertEquals(0, in.remaining()); assertEquals(4+data.length, rec.getRecordSize()); } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java b/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java deleted file mode 100644 index bcbddf0551..0000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.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.usermodel; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for the org.apache.poi.hssf.usermodel package. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBug42464.class, - TestBugs.class, - TestCellStyle.class, - TestCloneSheet.class, - TestDataValidation.class, - TestEscherGraphics.class, - TestEscherGraphics2d.class, - TestFontDetails.class, - TestFormulaEvaluatorBugs.class, - TestFormulaEvaluatorDocs.class, - TestFormulas.class, - TestHSSFCell.class, - TestHSSFClientAnchor.class, - //TestHSSFComment.class, //converted to junit4 - TestHSSFConditionalFormatting.class, - TestHSSFDataFormat.class, - TestHSSFDataFormatter.class, - TestHSSFDateUtil.class, - TestHSSFFont.class, - TestHSSFFormulaEvaluator.class, - TestHSSFHeaderFooter.class, - TestHSSFHyperlink.class, - TestHSSFName.class, - TestHSSFOptimiser.class, - TestHSSFPalette.class, - TestHSSFPatriarch.class, - TestHSSFPicture.class, - TestHSSFPictureData.class, - TestHSSFRichTextString.class, - TestHSSFRow.class, - TestHSSFSheet.class, - TestHSSFSheetShiftRows.class, - TestHSSFSheetUpdateArrayFormulas.class, - TestHSSFTextbox.class, - TestHSSFWorkbook.class, - TestOLE2Embeding.class, - TestPOIFSProperties.class, - TestReadWriteChart.class, - TestRowStyle.class, - TestSanityChecker.class, - TestSheetHiding.class, - /* deliberately avoiding this one - TestUnfixedBugs.class,*/ - TestUnicodeWorkbook.class, - TestNonStandardWorkbookStreamNames.class, - TestWorkbook.class -}) -public class AllUserModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java index 04ac448d25..0f67a86c10 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java @@ -19,188 +19,107 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.BOFRecord; -import org.apache.poi.hssf.record.BackupRecord; -import org.apache.poi.hssf.record.BookBoolRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.CalcModeRecord; -import org.apache.poi.hssf.record.CodepageRecord; -import org.apache.poi.hssf.record.CountryRecord; -import org.apache.poi.hssf.record.DSFRecord; -import org.apache.poi.hssf.record.DateWindow1904Record; -import org.apache.poi.hssf.record.DefaultColWidthRecord; -import org.apache.poi.hssf.record.DefaultRowHeightRecord; -import org.apache.poi.hssf.record.DeltaRecord; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.ExtSSTRecord; -import org.apache.poi.hssf.record.ExtendedFormatRecord; -import org.apache.poi.hssf.record.ExternSheetRecord; -import org.apache.poi.hssf.record.FnGroupCountRecord; -import org.apache.poi.hssf.record.FontRecord; -import org.apache.poi.hssf.record.FormatRecord; -import org.apache.poi.hssf.record.GridsetRecord; -import org.apache.poi.hssf.record.GutsRecord; -import org.apache.poi.hssf.record.HideObjRecord; -import org.apache.poi.hssf.record.InterfaceEndRecord; -import org.apache.poi.hssf.record.InterfaceHdrRecord; -import org.apache.poi.hssf.record.IterationRecord; -import org.apache.poi.hssf.record.MMSRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.PasswordRev4Record; -import org.apache.poi.hssf.record.PrecisionRecord; -import org.apache.poi.hssf.record.PrintGridlinesRecord; -import org.apache.poi.hssf.record.PrintHeadersRecord; -import org.apache.poi.hssf.record.ProtectRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.RefModeRecord; -import org.apache.poi.hssf.record.RefreshAllRecord; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.SaveRecalcRecord; -import org.apache.poi.hssf.record.SelectionRecord; -import org.apache.poi.hssf.record.StyleRecord; -import org.apache.poi.hssf.record.SupBookRecord; -import org.apache.poi.hssf.record.TabIdRecord; -import org.apache.poi.hssf.record.UseSelFSRecord; -import org.apache.poi.hssf.record.WSBoolRecord; -import org.apache.poi.hssf.record.WindowOneRecord; -import org.apache.poi.hssf.record.WindowProtectRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.WriteAccessRecord; +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 - { + 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 ) - { + 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 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) - { + public CheckRecord(Class record, char occurance, boolean together) { this.record = record; this.occurance = occurance; this.together = together; } - public Class getRecord() - { + public Class getRecord() { return record; } - public char getOccurance() - { - return occurance; - } - - public boolean isRequired() - { + public boolean isRequired() { return occurance == '1' || occurance == 'M'; } - public boolean isOptional() - { + public boolean isOptional() { return occurance == '0' || occurance == '*'; } - public boolean isTogether() - { - return together; - } - - public boolean isMany() - { + public boolean isMany() { return occurance == '*' || occurance == 'M'; } - public int match( List records, int recordIdx ) - { + public int match(List records, int recordIdx) { int firstRecord = findFirstRecord(records, getRecord(), recordIdx); - if (isRequired()) - { - return matchRequired( firstRecord, records, recordIdx ); + if (isRequired()) { + return matchRequired(firstRecord, records, recordIdx); } - return matchOptional( firstRecord, records, recordIdx ); + return matchOptional(firstRecord, records, recordIdx); } - private int matchOptional( int firstRecord, List records, int recordIdx ) - { - if (firstRecord == -1) - { + private int matchOptional(int firstRecord, List records, int recordIdx) { + if (firstRecord == -1) { return recordIdx; } - return matchOneOrMany( records, firstRecord ); + return matchOneOrMany(records, firstRecord); } - private int matchRequired( int firstRecord, List records, int recordIdx ) - { - if (firstRecord == -1) - { - fail("Manditory record missing or out of order: " + record); - } + private int matchRequired(int firstRecord, List records, int recordIdx) { + assertNotEquals(-1, firstRecord, "Manditory record missing or out of order: " + record); - return matchOneOrMany( records, firstRecord ); + return matchOneOrMany(records, firstRecord); } - private int matchOneOrMany( List records, int recordIdx ) - { - if (isZeroOrOne()) - { + private int matchOneOrMany(List records, int recordIdx) { + if (isZeroOrOne()) { // check no other records - if (findFirstRecord(records, getRecord(), recordIdx+1) != -1) - fail("More than one record matched for " + getRecord().getName()); - } - else if (isZeroToMany()) - { - if (together) - { - int nextIdx = findFirstRecord(records, record, recordIdx+1); - while (nextIdx != -1) - { - if (nextIdx - 1 != recordIdx) - fail("Records are not together " + record.getName()); + 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); + nextIdx = findFirstRecord(records, record, recordIdx + 1); } } } - return recordIdx+1; + return recordIdx + 1; } - private boolean isZeroToMany() - { + private boolean isZeroToMany() { return occurance == '*' || occurance == 'M'; } - private boolean isZeroOrOne() - { + private boolean isZeroOrOne() { return occurance == '0' || occurance == '1'; } } - CheckRecord[] workbookRecords = new CheckRecord[] { + CheckRecord[] workbookRecords = { new CheckRecord(BOFRecord.class, '1'), new CheckRecord(InterfaceHdrRecord.class, '1'), new CheckRecord(MMSRecord.class, '1'), @@ -235,7 +154,7 @@ public class SanityChecker { new CheckRecord(EOFRecord.class, '1'), }; - CheckRecord[] sheetRecords = new CheckRecord[] { + CheckRecord[] sheetRecords = { new CheckRecord(BOFRecord.class, '1'), new CheckRecord(CalcModeRecord.class, '1'), new CheckRecord(RefModeRecord.class, '1'), @@ -256,14 +175,12 @@ public class SanityChecker { new CheckRecord(EOFRecord.class, '1') }; - private void checkWorkbookRecords(InternalWorkbook workbook) - { + 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); -// checkRecordsTogether(records, workbookRecords); } private void checkSheetRecords(InternalSheet sheet) { @@ -272,104 +189,27 @@ public class SanityChecker { assertTrue(records.get(records.size() - 1) instanceof EOFRecord); checkRecordOrder(records, sheetRecords); -// checkRecordsTogether(records, sheetRecords); } - public void checkHSSFWorkbook(HSSFWorkbook wb) - { + public void checkHSSFWorkbook(HSSFWorkbook wb) { checkWorkbookRecords(wb.getWorkbook()); for (int i = 0; i < wb.getNumberOfSheets(); i++) checkSheetRecords(wb.getSheetAt(i).getSheet()); } - /* - private void checkRecordsTogether(List records, CheckRecord[] check) - { - for ( int checkIdx = 0; checkIdx < check.length; checkIdx++ ) - { - int recordIdx = findFirstRecord(records, check[checkIdx].getRecord()); - boolean notFoundAndRecordRequired = (recordIdx == -1 && check[checkIdx].isRequired()); - if (notFoundAndRecordRequired) - { - fail("Expected to find record of class " + check.getClass() + " but did not"); - } - else if (recordIdx >= 0) - { - if (check[checkIdx].isMany()) - { - // Skip records that are together - while (recordIdx < records.size() && check[checkIdx].getRecord().isInstance(records.get(recordIdx))) - recordIdx++; - } - - // Make sure record does not occur in remaining records (after the next) - recordIdx++; - for (int recordIdx2 = recordIdx; recordIdx2 < records.size(); recordIdx2++) - { - if (check[checkIdx].getRecord().isInstance(records.get(recordIdx2))) - fail("Record occurs scattered throughout record chain:\n" + records.get(recordIdx2)); - } - } - } - } */ - - /* package */ static int findFirstRecord( List records, Class record, int startIndex ) - { - for (int i = startIndex; i < records.size(); i++) - { + 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) - { + void checkRecordOrder(List records, CheckRecord[] check) { int recordIdx = 0; for (CheckRecord element : check) { recordIdx = element.match(records, recordIdx); } } - - /* - void checkRecordOrder(List records, CheckRecord[] check) - { - int checkIndex = 0; - for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) - { - Record record = (org.apache.poi.hssf.record.Record) records.get(recordIndex); - if (check[checkIndex].getRecord().isInstance(record)) - { - if (check[checkIndex].getOccurance() == 'M') - { - // skip over duplicate records if multiples are allowed - while (recordIndex+1 < records.size() && check[checkIndex].getRecord().isInstance(records.get(recordIndex+1))) - recordIndex++; -// lastGoodMatch = recordIndex; - } - else if (check[checkIndex].getOccurance() == '1') - { - // Check next record to make sure there's not more than one - if (recordIndex != records.size() - 1) - { - if (check[checkIndex].getRecord().isInstance(records.get(recordIndex+1))) - { - fail("More than one occurance of record found:\n" + records.get(recordIndex).toString()); - } - } -// lastGoodMatch = recordIndex; - } -// else if (check[checkIndex].getOccurance() == '0') -// { -// -// } - checkIndex++; - } - if (checkIndex >= check.length) - return; - } - fail("Could not find required record: " + check[checkIndex]); - } */ - } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java index 5e414f08a7..6f51abef42 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java @@ -17,19 +17,19 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertNotNull; +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.util.CellReference; 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.junit.Test; +import org.apache.poi.ss.util.CellReference; +import org.junit.jupiter.api.Test; /** * @@ -42,7 +42,7 @@ public final class TestBug42464 { process(wb); wb.close(); } - + @Test public void testExpSharedBadFile() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls"); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java index 24c5bf4c92..342335e267 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java @@ -20,7 +20,7 @@ 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.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; @@ -88,11 +88,11 @@ 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.AfterClass; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +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; /** * Testcases for bugs entered in bugzilla @@ -110,7 +110,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { private static final Map SIMPLE_REFS = new LinkedHashMap<>(); // References used for the simpleTest convenience method - @BeforeClass + @BeforeAll public static void initSimpleRefs() { String[] refs = { "Calculations", @@ -138,7 +138,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { LocaleUtil.setUserLocale(Locale.US); } - @AfterClass + @AfterAll public static void cleanUpRefs() { SIMPLE_REFS.clear(); } @@ -837,7 +837,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { * Problems with extracting check boxes from * HSSFObjectData */ - @Test(expected = IllegalArgumentException.class) + @Test public void bug44840() throws Exception { try (HSSFWorkbook wb = openSampleWorkbook("WithCheckBoxes.xls")) { @@ -863,7 +863,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { assertEquals(12, obj.getObjectData().length); assertEquals("Forms.CheckBox.1", obj.getOLE2ClassName()); - obj.getDirectory(); + assertThrows(IllegalArgumentException.class, obj::getDirectory); } } @@ -1001,13 +1001,8 @@ public final class TestBugs extends BaseTestBugzillaIssues { // formula cells, so we can see it updates properly c3.setCellValue(new HSSFRichTextString("test")); confirmCachedValue("test", c3); - try { - c3.getNumericCellValue(); - fail("exception should have been thrown"); - } catch (IllegalStateException e) { - assertEquals("Cannot get a NUMERIC value from a STRING formula cell", e.getMessage()); - } - + 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); @@ -1082,7 +1077,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { *

* Expected ExpPtg to be converted from Shared to Non-Shared... */ - @Ignore("For now, blows up with an exception from ExtPtg") + @Disabled("For now, blows up with an exception from ExtPtg") @Test public void test43623() throws Exception { try (HSSFWorkbook wb1 = openSampleWorkbook("43623.xls")) { @@ -1913,12 +1908,10 @@ public final class TestBugs extends BaseTestBugzillaIssues { // Will show as the center, as that is what excel does // with an invalid footer lacking left/right/center details - assertEquals("Left text should be empty", "", f.getLeft()); - assertEquals("Right text should be empty", "", f.getRight()); - assertEquals( - "Center text should contain the illegal value", - "BlahBlah blah blah ", f.getCenter() - ); + 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"); } } @@ -2226,9 +2219,9 @@ public final class TestBugs extends BaseTestBugzillaIssues { * Normally encrypted files have BOF then FILEPASS, but * some may squeeze a WRITEPROTECT in the middle */ - @Test(expected = EncryptedDocumentException.class) - public void bug51832() throws IOException { - simpleTest("51832.xls"); + @Test + public void bug51832() { + assertThrows(EncryptedDocumentException.class, () -> simpleTest("51832.xls")); } @Test @@ -2265,9 +2258,9 @@ public final class TestBugs extends BaseTestBugzillaIssues { // Problem 3: These used to fail, now pass HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - assertEquals("evaluating c1", 30.0, eval.evaluate(c1).getNumberValue(), 0.001); - assertEquals("evaluating d1", 30.0, eval.evaluate(d1).getNumberValue(), 0.001); - assertEquals("evaluating e1", 30.0, eval.evaluate(e1).getNumberValue(), 0.001); + 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"); } } @@ -2697,7 +2690,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { try { bimage = ImageIO.read(structURL); } catch (IOException e) { - Assume.assumeNoException("Downloading a jpg from poi.apache.org should work", e); + Assumptions.assumeFalse(true, "Downloading a jpg from poi.apache.org should work"); return; } @@ -2711,7 +2704,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { // Pop structure into Structure HSSFSheet int pict = wb.addPicture(imageBytes, HSSFWorkbook.PICTURE_TYPE_JPEG); Sheet sheet = wb.getSheet("Structure"); - assertNotNull("Did not find sheet", sheet); + 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); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java index 1bac320643..4f856657fb 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -45,7 +45,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class to test cell styling functionality @@ -97,8 +97,8 @@ public final class TestCellStyle { SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); + assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); } // assert((s.getLastRowNum() == 99)); @@ -134,8 +134,8 @@ public final class TestCellStyle { SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW ", 0, s.getLastRowNum()); - assertEquals("FIRST ROW ", 0, s.getFirstRowNum()); + assertEquals(0, s.getLastRowNum(), "LAST ROW"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW"); } } @@ -185,8 +185,6 @@ public final class TestCellStyle { File file = TempFile.createTempFile("testWriteSheetStyle", ".xls"); try (HSSFWorkbook wb = new HSSFWorkbook()) { HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; HSSFFont fnt = wb.createFont(); HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs2 = wb.createCellStyle(); @@ -203,10 +201,10 @@ public final class TestCellStyle { cs2.setFillPattern(FillPatternType.DIAMONDS); cs2.setFont(fnt); for (int rownum = 0; rownum < 100; rownum++) { - r = s.createRow(rownum); + HSSFRow r = s.createRow(rownum); for (int cellnum = 0; cellnum < 50; cellnum += 2) { - c = r.createCell(cellnum); + HSSFCell c = r.createCell(cellnum); c.setCellValue(rownum * 10000 + cellnum + (((double) rownum / 1000) + ((double) cellnum / 10000))); @@ -221,8 +219,8 @@ public final class TestCellStyle { } SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); + assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); } } @@ -455,13 +453,13 @@ public final class TestCellStyle { Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { - for (Integer idxCell = 0; idxCell < row.getLastCellNum(); idxCell++) { + for (int idxCell = 0; idxCell < row.getLastCellNum(); idxCell++) { Cell cell = row.getCell(idxCell); cell.getCellStyle().getDataFormatString(); if (cell.getCellType() == CellType.NUMERIC) { boolean isDate = DateUtil.isCellDateFormatted(cell); - assertFalse("cell " + idxCell + " is not a date.", idxCell > 0 && isDate); + assertFalse(idxCell > 0 && isDate, "cell " + idxCell + " is not a date."); } } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java index 5bdfe6227b..d8e6ea92e8 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java @@ -17,18 +17,21 @@ 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.Test; - -import java.io.IOException; -import java.util.Arrays; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; /** * Test the ability to clone a sheet. @@ -46,7 +49,7 @@ public final class TestCloneSheet extends BaseTestCloneSheet { 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()); @@ -97,7 +100,7 @@ public final class TestCloneSheet extends BaseTestCloneSheet { 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); @@ -106,11 +109,11 @@ public final class TestCloneSheet extends BaseTestCloneSheet { assertEquals(c.getRow(), c2.getRow()); assertEquals(c.getColumn(), c2.getColumn()); - // The ShapeId is not equal? + // 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); @@ -126,7 +129,7 @@ public final class TestCloneSheet extends BaseTestCloneSheet { 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 index 92e5f64472..b03292cd71 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java @@ -24,8 +24,7 @@ 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.AfterClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCryptoAPI { final HSSFITestDataProvider ssTests = HSSFITestDataProvider.instance; @@ -44,7 +43,7 @@ public class TestCryptoAPI { // 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); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java index 1e3fc381cc..51bca0f4af 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java @@ -17,11 +17,12 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -45,7 +46,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class for testing Excel's data validation mechanism @@ -164,9 +165,7 @@ public final class TestDataValidation extends BaseTestDataValidation { // 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. - if (nextSid == 0x0867) { - fail("Identified bug 45519"); - } + assertNotEquals(0x0867, nextSid, "Identified bug 45519"); assertEquals(DVRecord.sid, nextSid); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java index 51a5c64847..af2c703582 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java @@ -17,14 +17,14 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for the embedded object fetching support in HSSF diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java index f8c4c65c7e..4f4cce473e 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -28,9 +28,9 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +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. @@ -45,7 +45,7 @@ public final class TestEscherGraphics { private HSSFShapeGroup escherGroupA; private EscherGraphics graphics; - @Before + @BeforeEach public void setUp() throws IOException { workbook = new HSSFWorkbook(); @@ -55,8 +55,8 @@ public final class TestEscherGraphics { patriarch.createGroup(new HSSFClientAnchor(20,30,500,200,(short)0,0,(short) 0,0)); graphics = new EscherGraphics(escherGroupA, workbook, Color.black, 1.0f); } - - @After + + @AfterEach public void closeResources() throws IOException { workbook.close(); } @@ -268,9 +268,9 @@ public final class TestEscherGraphics { assertEquals(40, patriarch.getY2()); // Check the two groups and the text - // Result of patriarch.countOfAllChildren() makes no sense: + // Result of patriarch.countOfAllChildren() makes no sense: // Returns 4 for 2 empty groups + 1 TextBox. - //assertEquals(3, patriarch.countOfAllChildren()); + //assertEquals(3, patriarch.countOfAllChildren()); assertEquals(3, patriarch.getChildren().size()); // Should be two groups and a text diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java index e765936b01..f207b9a117 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java @@ -17,9 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.awt.Color; import java.awt.Font; @@ -27,9 +26,9 @@ import java.awt.FontMetrics; import java.awt.geom.Line2D; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the Graphics2d drawing capability. @@ -39,7 +38,7 @@ public final class TestEscherGraphics2d { private HSSFShapeGroup escherGroup; private EscherGraphics2d graphics; - @Before + @BeforeEach public void setUp() { workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("test"); @@ -48,8 +47,8 @@ public final class TestEscherGraphics2d { EscherGraphics g = new EscherGraphics(escherGroup, workbook, Color.black, 1.0f); graphics = new EscherGraphics2d(g); } - - @After + + @AfterEach public void closeResources() throws IOException { workbook.close(); } @@ -77,12 +76,7 @@ public final class TestEscherGraphics2d { // But with an invalid font, we get an exception font = new Font("IamAmadeUPfont", Font.PLAIN, 22); graphics.setFont(font); - try { - graphics.drawString("This is another test", 10, 10); - fail(); - } catch(IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> graphics.drawString("This is another test", 10, 10)); } @Test diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java b/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java index 39d7e13d90..b60b5c10c1 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java @@ -16,16 +16,16 @@ ==================================================================== */ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public class TestExternalReferenceChange { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java index 724ffb29d0..0b469d64a8 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the implementation of the FontDetails class. @@ -30,7 +30,7 @@ import org.junit.Test; public final class TestFontDetails { private FontDetails fontDetails; - @Before + @BeforeEach public void setUp() { Properties properties = new Properties(); properties.setProperty("font.Arial.height", "13"); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java index 61103829af..dc03e67cfd 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.File; import java.io.FileOutputStream; @@ -45,8 +45,8 @@ import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellReference; import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @@ -55,7 +55,7 @@ public final class TestFormulaEvaluatorBugs { private static boolean OUTPUT_TEST_FILES; private static String tmpDirName; - @BeforeClass + @BeforeAll public static void setUp() { tmpDirName = System.getProperty("java.io.tmpdir"); OUTPUT_TEST_FILES = Boolean.parseBoolean( @@ -95,7 +95,7 @@ public final class TestFormulaEvaluatorBugs { 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(); @@ -182,7 +182,7 @@ public final class TestFormulaEvaluatorBugs { cell = row.getCell(0); assertEquals("-1000000-3000000", cell.getCellFormula()); assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); - + wb.close(); } @@ -243,7 +243,7 @@ public final class TestFormulaEvaluatorBugs { HSSFCell cellSUM2D = rowSUM2D.getCell(0); assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); - + wb.close(); } @@ -267,7 +267,7 @@ public final class TestFormulaEvaluatorBugs { fail("Identified bug 44508"); } assertTrue(cell.getBooleanCellValue()); - + wb.close(); } @@ -292,27 +292,24 @@ public final class TestFormulaEvaluatorBugs { } } } - + wb.close(); } @Test public void testEvaluateInCellWithErrorCode_bug44950() throws Exception { - 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); - try { + 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; - } finally { - wb.close(); } } @@ -357,7 +354,7 @@ public final class TestFormulaEvaluatorBugs { cell.setCellFormula("DATE(2012,2-12,1+4)"); fe.notifyUpdateCell(cell); assertEquals(40579.0, fe.evaluate(cell).getNumberValue(), 0); - + wb.close(); } @@ -420,13 +417,11 @@ public final class TestFormulaEvaluatorBugs { WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener); ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cell)); int evalCount = evalListener.getCountCacheMisses(); - if (evalCount > 10) { - // 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"); - fail("Identifed bug 45376 - Formula evaluator should cache values"); - } + // 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); @@ -440,7 +435,7 @@ public final class TestFormulaEvaluatorBugs { // confirm the evaluation result too assertEquals(ErrorEval.NA, ve); - + wb.close(); } @@ -527,22 +522,22 @@ public final class TestFormulaEvaluatorBugs { 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()); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java index 30c85cbe3d..c718fece8d 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java @@ -17,7 +17,7 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -25,7 +25,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests to show that our documentation at diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java index d2aeaf3803..8ef9614e57 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java @@ -18,10 +18,10 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -40,7 +40,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestFormulas { @@ -66,7 +66,7 @@ public final class TestFormulas { r = s.getRow(1); c = r.getCell(1); - assertEquals("Formula is as expected", "1+1", c.getCellFormula()); + assertEquals("1+1", c.getCellFormula(), "Formula is as expected"); } } } @@ -201,9 +201,10 @@ public final class TestFormulas { for (int y = 1; y < 256 && y > 0; y=(short)(y+2)) { HSSFCell c = r.getCell(y); - assertNotNull("got a formula", c.getCellFormula()); + assertNotNull(c.getCellFormula(), "got a formula"); - assertEquals("loop Formula is as expected " + x + "." + y + operator + y + "." + x + "!=" + c.getCellFormula(), ("" + x + "." + y + operator + y + "." + x), c.getCellFormula()); + assertEquals(("" + x + "." + y + operator + y + "." + x), c.getCellFormula(), + "loop Formula is as expected " + x + "." + y + operator + y + "." + x + "!=" + c.getCellFormula()); } } } @@ -281,7 +282,8 @@ public final class TestFormulas { HSSFRow r = s.getRow(0); HSSFCell c = r.getCell(1); //get our minimum values - assertEquals("minval Formula is as expected A2" + operator + "A3 != " + c.getCellFormula(), ("A2" + operator + "A3"), c.getCellFormula()); + 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)) { @@ -301,7 +303,8 @@ public final class TestFormulas { String ref2=cr.formatAsString(); - assertEquals("loop Formula is as expected " + ref + operator + ref2 + "!=" + c.getCellFormula(), ("" + ref + operator + ref2), c.getCellFormula()); + assertEquals(("" + ref + operator + ref2), c.getCellFormula(), + "loop Formula is as expected " + ref + operator + ref2 + "!=" + c.getCellFormula()); } } @@ -332,7 +335,7 @@ public final class TestFormulas { //get our minimum values r = s.getRow(0); c = r.getCell(1); - assertEquals("minval Formula is as expected", formula, c.getCellFormula()); + assertEquals(formula, c.getCellFormula(), "minval Formula is as expected"); } } } @@ -382,14 +385,16 @@ public final class TestFormulas { //get our minimum values HSSFRow r = s.getRow(0); HSSFCell c = r.getCell(1); - assertEquals("minval Formula is as expected 1" + operator + "1 != " + c.getCellFormula(), ("1" + operator + "1"), c.getCellFormula()); + 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("loop Formula is as expected " + x + operator + y + "!=" + c.getCellFormula(), ("" + x + operator + y), c.getCellFormula()); + assertEquals(("" + x + operator + y), c.getCellFormula(), + "loop Formula is as expected " + x + operator + y + "!=" + c.getCellFormula()); } } @@ -397,7 +402,8 @@ public final class TestFormulas { r = s.getRow(0); c = r.getCell(0); - assertEquals("maxval Formula is as expected", ("" + Short.MAX_VALUE + operator + Short.MAX_VALUE), c.getCellFormula()); + assertEquals(("" + Short.MAX_VALUE + operator + Short.MAX_VALUE), c.getCellFormula(), + "maxval Formula is as expected"); } /** @@ -415,7 +421,8 @@ public final class TestFormulas { r = s.getRow(0); c = r.getCell(0); - assertEquals("function =" + function + "(A2:A3)", function + "(A2:A3)", c.getCellFormula()); + assertEquals(function + "(A2:A3)", c.getCellFormula(), + "function =" + function + "(A2:A3)"); } } } @@ -436,7 +443,7 @@ public final class TestFormulas { r = s.getRow(0); c = r.getCell(0); - assertEquals("function =" + function + "(A2,A3)", (function + "(A2,A3)"), c.getCellFormula()); + assertEquals((function + "(A2,A3)"), c.getCellFormula(), "function =" + function + "(A2,A3)"); } } } @@ -461,10 +468,10 @@ public final class TestFormulas { r = s.getRow(0); c = r.getCell(0); - assertEquals("function =" + function + "(A2:A4,B2:B4)", (function + "(A2:A4,B2:B4)"), c.getCellFormula()); + assertEquals((function + "(A2:A4,B2:B4)"), c.getCellFormula(), "function =" + function + "(A2:A4,B2:B4)"); c = r.getCell(1); - assertEquals("function =" + function + "($A$2:$A4,B$2:B4)", (function + "($A$2:$A4,B$2:B4)"), c.getCellFormula()); + assertEquals((function + "($A$2:$A4,B$2:B4)"), c.getCellFormula(), "function =" + function + "($A$2:$A4,B$2:B4)"); } } } @@ -490,15 +497,15 @@ public final class TestFormulas { s = wb2.getSheetAt(0); r = s.getRow(0); c = r.getCell(0); - assertEquals("A3+A2", ("A3+A2"), c.getCellFormula()); + assertEquals("A3+A2", c.getCellFormula()); c = r.getCell(1); - assertEquals("$A3+$A2", ("$A3+$A2"), c.getCellFormula()); + assertEquals("$A3+$A2", c.getCellFormula()); c = r.getCell(2); - assertEquals("A$3+A$2", ("A$3+A$2"), c.getCellFormula()); + assertEquals("A$3+A$2", c.getCellFormula()); c = r.getCell(3); - assertEquals("$A$3+$A$2", ("$A$3+$A$2"), c.getCellFormula()); + assertEquals("$A$3+$A$2", c.getCellFormula()); c = r.getCell(4); - assertEquals("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)"), c.getCellFormula()); + assertEquals("SUM($A$3,$A$2)", c.getCellFormula()); } } } @@ -526,9 +533,11 @@ public final class TestFormulas { s = wb2.getSheet("B"); r = s.getRow(0); c = r.getCell(0); - assertEquals("expected: AVERAGE(A!A1:B1) got: " + c.getCellFormula(), ("AVERAGE(A!A1:B1)"), c.getCellFormula()); + assertEquals("AVERAGE(A!A1:B1)", c.getCellFormula(), + "expected: AVERAGE(A!A1:B1) got: " + c.getCellFormula()); c = r.getCell(1); - assertEquals("expected: A!A1+A!B1 got: " + c.getCellFormula(), ("A!A1+A!B1"), c.getCellFormula()); + assertEquals("A!A1+A!B1", c.getCellFormula(), + "expected: A!A1+A!B1 got: " + c.getCellFormula()); } } } @@ -568,7 +577,7 @@ public final class TestFormulas { try (FileOutputStream out = new FileOutputStream(file)) { wb.write(out); } - assertTrue("file exists", file.exists()); + assertTrue(file.exists()); } } @@ -607,7 +616,7 @@ public final class TestFormulas { s = wb2.getSheetAt(0); r = s.getRow(0); c = r.getCell(1); - assertEquals("Formula in cell 1 ", "IF(A1 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); - try { - cellA.setCellStyle(styB); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - try { - cellB.setCellStyle(styA); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> cellA.setCellStyle(styB)); + assertThrows(IllegalArgumentException.class, () -> cellB.setCellStyle(styA)); } } @@ -329,7 +302,7 @@ public final class TestHSSFCell extends BaseTestCell { final List recs = new ArrayList<>(); sheet.getSheet().visitContainedRecords(recs::add, 0); - assertFalse("Identified bug - leftover StringRecord", recs.size() == 28 && recs.get(23) instanceof StringRecord); + assertFalse(recs.size() == 28 && recs.get(23) instanceof StringRecord, "Identified bug - leftover StringRecord"); confirmStringRecord(sheet, false); // string to error code @@ -390,12 +363,7 @@ public final class TestHSSFCell extends BaseTestCell { // cover some deprecated methods and other smaller stuff... assertEquals(wb.getWorkbook(), cell.getBoundWorkbook()); - try { - cell.getCachedFormulaResultType(); - fail("Should catch exception"); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, cell::getCachedFormulaResultType); cell.removeCellComment(); cell.removeCellComment(); @@ -410,7 +378,7 @@ public final class TestHSSFCell extends BaseTestCell { Cell cell = row.createCell(0); cell.setBlank(); - assertNull(null, cell.getDateCellValue()); + assertNull(cell.getDateCellValue()); assertFalse(cell.getBooleanCellValue()); assertEquals("", cell.toString()); @@ -440,11 +408,11 @@ public final class TestHSSFCell extends BaseTestCell { } } - @Test(expected = IllegalStateException.class) + @Test public void getErrorCellValue_throwsISE_onABlankCell() throws IOException { try (HSSFWorkbook wb = new HSSFWorkbook()) { Cell cell = wb.createSheet().createRow(0).createCell(0); - cell.getErrorCellValue(); + 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 index 987741f4ca..494072402c 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link HSSFChart} @@ -139,26 +139,26 @@ public final class TestHSSFChart { assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle()); assertEquals("Sheet 3 Chart with Title", charts[0].getChartTitle()); } - + @Test public void testExistingSheet3() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.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); } @@ -168,11 +168,11 @@ public final class TestHSSFChart { HSSFWorkbook wb = HSSFTestDataSamples.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); @@ -185,12 +185,12 @@ public final class TestHSSFChart { 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); } @@ -200,7 +200,7 @@ public final class TestHSSFChart { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls"); HSSFSheet sheet = wb.getSheetAt( 0 ) ; HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - + for ( HSSFChart chart : charts ) { //System.out.println( chart.getType() ) ; HSSFSeries[] seriesArray = chart.getSeries() ; @@ -237,7 +237,7 @@ public final class TestHSSFChart { HSSFChart chart = charts[ 2 ] ; chart.removeSeries( chart.getSeries()[ 0 ] ) ; } - + /** * Bug 26862: HSSFWorkbook.cloneSheet copies charts */ @@ -248,10 +248,10 @@ public final class TestHSSFChart { 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); @@ -263,11 +263,11 @@ public final class TestHSSFChart { 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 index 30c6fce97a..2d19ce1aaf 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java @@ -17,13 +17,14 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Various tests for HSSFClientAnchor. @@ -128,9 +129,10 @@ public final class TestHSSFClientAnchor { assertEquals(65535, anchor.getRow2()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCannotHaveRowGreaterThan65535() { - new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65536, (short) 0, 65536); + assertThrows(IllegalArgumentException.class, () -> + new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65536, (short) 0, 65536)); } /** @@ -146,13 +148,15 @@ public final class TestHSSFClientAnchor { assertEquals(65535, anchor.getRow2()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCannotSetRow1GreaterThan65535() { - new HSSFClientAnchor().setRow1(65536); + assertThrows(IllegalArgumentException.class, () -> + new HSSFClientAnchor().setRow1(65536)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCannotSetRow2GreaterThan65535() { - new HSSFClientAnchor().setRow2(65536); + assertThrows(IllegalArgumentException.class, () -> + new HSSFClientAnchor().setRow2(65536)); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java index 62ecf00a4f..ef4a2bc538 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -44,7 +44,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests TestHSSFCellComment. @@ -97,10 +97,10 @@ public final class TestHSSFComment extends BaseTestCellComment { cell = sheet.getRow(5).getCell(2); comment = cell.getCellComment(); assertEquals("c6", comment.getString().getString()); - + wb.close(); } - + @Test public void testBug56380InsertComments() throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(); @@ -108,7 +108,7 @@ public final class TestHSSFComment extends BaseTestCellComment { 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); @@ -125,14 +125,14 @@ public final class TestHSSFComment extends BaseTestCellComment { } 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(); } @@ -173,7 +173,7 @@ public final class TestHSSFComment extends BaseTestCellComment { for(int i = 0; i < noOfRows; i++) { assertNotNull(sheet.getRow(i)); assertNotNull(sheet.getRow(i).getCell(0)); - assertNotNull("Did not get a Cell Comment for row " + i, sheet.getRow(i).getCell(0).getCellComment()); + 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()); } @@ -181,27 +181,27 @@ public final class TestHSSFComment extends BaseTestCellComment { 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.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 public void resultEqualsToNonExistingAbstractShape() throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); @@ -308,7 +308,7 @@ public final class TestHSSFComment extends BaseTestCellComment { 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(); @@ -364,7 +364,7 @@ public final class TestHSSFComment extends BaseTestCellComment { assertEquals(comment.getColumn(), 32); assertEquals(comment.getRow(), 42); assertTrue(comment.isVisible()); - + wb.close(); wbBack.close(); wbBack2.close(); @@ -403,7 +403,7 @@ public final class TestHSSFComment extends BaseTestCellComment { assertNotNull(sh.findCellComment(5, 4)); assertNull(sh.findCellComment(5, 5)); - + wb.close(); wbBack.close(); } @@ -424,7 +424,7 @@ public final class TestHSSFComment extends BaseTestCellComment { assertNotNull(shape); assertEquals(comment.getOptRecord().getEscherProperties().size(), 10); - + wb.close(); } @@ -446,7 +446,7 @@ public final class TestHSSFComment extends BaseTestCellComment { 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 index 63ba22c935..0512d5a080 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java @@ -18,14 +18,19 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.*; +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.*; -import org.junit.Test; +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 @@ -35,8 +40,8 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm super(HSSFITestDataProvider.instance); } @Override - protected void assertColour(String hexExpected, Color actual) { - assertNotNull("Colour must be given", actual); + 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()); @@ -54,7 +59,7 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm public void testRead() throws IOException { testRead("WithConditionalFormatting.xls"); } - + @Test public void testReadOffice2007() throws IOException { testReadOffice2007("NewStyleConditionalFormattings.xls"); @@ -73,10 +78,10 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm } wb.removeSheetAt(1);*/ - + // initially it is good writeTemp53691(wb, "agood"); - + // clone sheet corrupts it Sheet sheet = wb.cloneSheet(0); writeTemp53691(wb, "bbad"); @@ -84,28 +89,28 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm // 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); + 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)); + 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++) { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java index dd334b0183..2747b19d52 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -32,7 +32,7 @@ import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link HSSFDataFormat} @@ -62,12 +62,12 @@ public final class TestHSSFDataFormat extends BaseTestDataFormat { short customFmtIdx = dataFormat.getFormat("\u00a3##.00[Yellow]"); assertTrue(customFmtIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX ); assertEquals("\u00a3##.00[Yellow]", dataFormat.getFormat(customFmtIdx)); - + wb.close(); } /** - * [Bug 58532] Handle formats that go numnum, numK, numM etc + * [Bug 58532] Handle formats that go numnum, numK, numM etc */ @Override @Test diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java index 7ee4525989..035eeaa78a 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -35,9 +35,9 @@ 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.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Unit tests for HSSFDataFormatter.java @@ -45,14 +45,14 @@ import org.junit.Test; public final class TestHSSFDataFormatter { private static TimeZone userTimeZone; - @BeforeClass + @BeforeAll public static void setTimeZone() { userTimeZone = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); LocaleUtil.setUserLocale(Locale.US); } - @AfterClass + @AfterAll public static void resetTimeZone() { LocaleUtil.setUserTimeZone(userTimeZone); LocaleUtil.setUserLocale(Locale.ROOT); @@ -109,10 +109,10 @@ public final class TestHSSFDataFormatter { String[] goodTimePatterns = { "HH:MM", "HH:MM:SS", - "HH:MM;HH:MM;HH:MM", + "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", + "[BLUE]HH:MM;[RED]HH:MM;[GREEN]HH:MM", "yyyy-mm-dd hh:mm", "yyyy-mm-dd hh:mm:ss", }; @@ -241,7 +241,7 @@ public final class TestHSSFDataFormatter { // should not be equal to "555.555" assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertFalse("555.555".equals(fmtval)); + assertNotEquals(fmtval, "555.555"); String fmt = cell.getCellStyle().getDataFormatString(); @@ -257,7 +257,7 @@ public final class TestHSSFDataFormatter { jul = jul.substring(0,1); } // check we found july properly - assertTrue("Format came out incorrect - " + fmt, fmtval.contains(jul)); + assertTrue(fmtval.contains(jul), "Format came out incorrect - " + fmt); } row = wb.getSheetAt(0).getRow(1); @@ -271,11 +271,11 @@ public final class TestHSSFDataFormatter { // should not be equal to "555.47431" assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertFalse("555.47431".equals(fmtval)); + assertNotEquals(fmtval, "555.47431"); // check we found the time properly - assertTrue("Format came out incorrect - " + fmt + " - found " + fmtval + - ", but expected to find '11:23'", fmtval.contains("11:23")); + assertTrue(fmtval.contains("11:23"), + "Format came out incorrect - " + fmt + " - found " + fmtval + ", but expected to find '11:23'"); } // test number formats @@ -367,10 +367,10 @@ public final class TestHSSFDataFormatter { Cell cell = it.next(); cell.setCellValue(cell.getNumericCellValue() * Math.random() / 1000000 - 1000); log(formatter.formatCellValue(cell)); - - String formatted = formatter.formatCellValue(cell); - assertTrue("Doesn't start with Balance: " + formatted, formatted.startsWith("Balance ")); - assertTrue("Doesn't end with USD: " + formatted, formatted.endsWith(" USD")); + + 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); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java index 066f4bdf66..cbb6bfcdd8 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java @@ -17,10 +17,10 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -29,9 +29,9 @@ 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.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Class TestHSSFDateUtil @@ -39,14 +39,14 @@ import org.junit.Test; public class TestHSSFDateUtil { static TimeZone userTimeZone; - - @BeforeClass + + @BeforeAll public static void setCEST() { userTimeZone = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST")); } - - @AfterClass + + @AfterAll public static void resetTimeZone() { LocaleUtil.setUserTimeZone(userTimeZone); } @@ -54,7 +54,7 @@ public class TestHSSFDateUtil { /** * Test that against a real, test file, we still do everything * correctly - * @throws IOException + * @throws IOException */ @Test public void onARealFile() throws IOException { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java index c53e01b4aa..538d266cf4 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java @@ -17,15 +17,15 @@ package org.apache.poi.hssf.usermodel; +import java.util.AbstractMap; +import java.util.Map; + import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.formula.EvaluationSheet; import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.Sheet; -import org.junit.Test; - -import java.util.AbstractMap; -import java.util.Map; +import org.junit.jupiter.api.Test; public class TestHSSFEvaluationSheet extends BaseTestXEvaluationSheet { @Override @@ -33,7 +33,7 @@ public class TestHSSFEvaluationSheet extends BaseTestXEvaluationSheet { HSSFSheet sheet = new HSSFWorkbook().createSheet(); return new AbstractMap.SimpleEntry<>(sheet, new HSSFEvaluationSheet(sheet)); } - + @Test public void testMissingExternalName() { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("external_name.xls"); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java index 81f28d81fe..f05ebb5203 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java @@ -22,7 +22,7 @@ import java.io.IOException; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.ss.usermodel.BaseTestFont; import org.apache.poi.ss.usermodel.Font; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java index daae2cc6e4..c421e2cee5 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java @@ -17,8 +17,10 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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; @@ -35,7 +37,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator { @@ -43,258 +45,249 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator { super(HSSFITestDataProvider.instance); } - /** - * Test that the HSSFFormulaEvaluator can evaluate simple named ranges - * (single cells and rectangular areas) - */ + /** + * Test that the HSSFFormulaEvaluator can evaluate simple named ranges + * (single cells and rectangular areas) + */ @Test - public 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(); - } + public 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. - */ + /** + * 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 - public 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"); + public 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); + // 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)"); + 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 + // 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); + 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; - } - } + assertEquals(CellType.NUMERIC, value.getCellType()); + assertEquals(5.33, value.getNumberValue(), 0.0); - /** - * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values - */ - @Test - public void testShortCircuitIfEvaluation() throws IOException { - // Set up a simple IF() formula that has measurable evaluation cost for its operands. - 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(); - if (evalCount == 6) { - // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1) - fail("Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations."); - } - assertEquals(3, evalCount); - assertEquals(2.0, ((NumberEval)ve).getNumberValue(), 0D); - - wb.close(); - } - - /** - * Ensures that we can handle NameXPtgs in the formulas - * we parse. - */ - @Test - public void testXRefs() throws IOException { - 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) + } catch (RuntimeException e) { + if (e.getMessage().equals("Don't know how to evaluate name 'Is_Multicar_Vehicle'")) { + fail("Identified bug 47048a"); } - ); - eval.evaluateFormulaCell( - wb1.getSheetAt(0).getRow(1).getCell(2) - ); - eval.evaluateFormulaCell( - wb1.getSheetAt(0).getRow(1).getCell(4) - ); - + throw e; + } finally { + wb.close(); + } + } - // 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); + private static final class EvalCountListener extends EvaluationListener { + private int _evalCount; - // Try to add a formula for a new external workbook, won't be allowed to start - try { - cell = wb1.getSheetAt(0).getRow(1).createCell(42); - cell.setCellFormula("[alt.xls]Sheet0!$A$1"); - fail("New workbook not linked, shouldn't be able to add"); - } catch(Exception e) { - // expected here - } - - // Link our new workbook - 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()); + public EvalCountListener() { + _evalCount = 0; + } - // Evaluate it, without a link to that workbook - try { - eval.evaluate(cell); - fail("No cached value and no link to workbook, shouldn't evaluate"); - } catch(Exception e) { - // expected here - } - - // 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 - 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()); - - wb4.close(); - wb3.close(); - wb2.close(); - wb1.close(); - } + @Override + public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { + _evalCount++; + } - @Test + public int getEvalCount() { + return _evalCount; + } + } + + /** + * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values + */ + @Test + public 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 + public 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()); + } + } + } + } + + @Test public void testSharedFormulas() throws IOException { baseTestSharedFormulas("shared_formulas.xls"); } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java index a8e8b33ae9..6d2263dd9b 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java @@ -18,12 +18,12 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link HSSFHeader} / {@link HSSFFooter} @@ -156,14 +156,14 @@ public final class TestHSSFHeaderFooter { try (HSSFWorkbook wb = openSampleWorkbook("DBCSHeader.xls")) { HSSFSheet s = wb.getSheetAt(0); HSSFHeader h = s.getHeader(); - assertEquals("Header Left ", h.getLeft(), "\u090f\u0915"); - assertEquals("Header Center ", h.getCenter(), "\u0939\u094b\u0917\u093e"); - assertEquals("Header Right ", h.getRight(), "\u091c\u093e"); + 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("Footer Left ", f.getLeft(), "\u091c\u093e"); - assertEquals("Footer Center ", f.getCenter(), "\u091c\u093e"); - assertEquals("Footer Right ", f.getRight(), "\u091c\u093e"); + assertEquals(f.getLeft(), "\u091c\u093e", "Footer Left"); + assertEquals(f.getCenter(), "\u091c\u093e", "Footer Center"); + assertEquals(f.getRight(), "\u091c\u093e", "Footer Right"); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java index 39d20c1ebd..180624a495 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -28,13 +28,7 @@ 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.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCreationHelper; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -*/ -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests HSSFHyperlink. diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java index 566e2f57c5..cc4d519c65 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java @@ -17,6 +17,12 @@ 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; @@ -26,11 +32,8 @@ 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.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; /** * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. @@ -126,7 +129,7 @@ public final class TestHSSFName extends BaseTestNamedRange { HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); HSSFName nm = wb2.getNameAt(wb2.getNameIndex("RangeTest")); - assertEquals("Name is " + nm.getNameName(), "RangeTest", nm.getNameName()); + assertEquals("RangeTest", nm.getNameName(), "Name is " + nm.getNameName()); assertEquals(wb2.getSheetName(0)+"!$D$4:$E$8", nm.getRefersToFormula()); wb2.close(); wb1.close(); @@ -152,16 +155,16 @@ public final class TestHSSFName extends BaseTestNamedRange { String reference = namedRange1.getRefersToFormula(); assertEquals(sheetName+"!$A$1:$D$10", reference); - assertEquals(false, namedRange1.isDeleted()); - assertEquals(false, namedRange1.isHidden()); + assertFalse(namedRange1.isDeleted()); + assertFalse(namedRange1.isHidden()); HSSFName namedRange2 = wb.getNameAt(1); assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getRefersToFormula()); assertEquals("SecondNamedRange", namedRange2.getNameName()); - assertEquals(false, namedRange2.isDeleted()); - assertEquals(false, namedRange2.isHidden()); - + assertFalse(namedRange2.isDeleted()); + assertFalse(namedRange2.isHidden()); + wb.close(); } @@ -184,7 +187,7 @@ public final class TestHSSFName extends BaseTestNamedRange { name.setRefersToFormula(newReference); assertEquals(newReference, name.getRefersToFormula()); - + wb.close(); } @@ -204,26 +207,23 @@ public final class TestHSSFName extends BaseTestNamedRange { @Test public void testDeletedReference() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("24207.xls"); - assertEquals(2, wb.getNumberOfNames()); + 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()); - assertTrue("Successfully constructed first reference", true); + 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()); - try { - wb.getCreationHelper().createAreaReference(name2.getRefersToFormula()); - fail("attempt to supply an invalid reference to AreaReference constructor results in exception"); - } catch (IllegalArgumentException e) { // TODO - use a stronger typed exception for this condition - // expected during successful test + 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"); } - wb.close(); } /** diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java index 3a351afa06..c7c3ddbffb 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java @@ -16,13 +16,17 @@ ==================================================================== */ package org.apache.poi.hssf.usermodel; -import java.io.IOException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.apache.poi.ss.usermodel.*; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.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; public final class TestHSSFOptimiser { @Test @@ -324,8 +328,8 @@ public final class TestHSSFOptimiser { @Test public void testColumnAndRowStyles() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -357,8 +361,8 @@ public final class TestHSSFOptimiser { @Test public void testUnusedStyle() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -395,8 +399,8 @@ public final class TestHSSFOptimiser { @Test public void testUnusedStyleOneUsed() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -431,10 +435,10 @@ public final class TestHSSFOptimiser { } @Test - public void testDefaultColumnStyleWitoutCell() throws IOException { + public void testDefaultColumnStyleWitoutCell() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -473,10 +477,10 @@ public final class TestHSSFOptimiser { } @Test - public void testUserDefinedStylesAreNeverOptimizedAway() throws IOException { + public void testUserDefinedStylesAreNeverOptimizedAway() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -532,10 +536,10 @@ public final class TestHSSFOptimiser { } @Test - public void testBug57517() throws IOException { + public void testBug57517() { HSSFWorkbook wb = new HSSFWorkbook(); - assertEquals("Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()", - 21, wb.getNumCellStyles()); + assertEquals(21, wb.getNumCellStyles(), + "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()"); HSSFSheet sheet = wb.createSheet(); @@ -599,7 +603,7 @@ public final class TestHSSFOptimiser { // Create a test font and style, and use them for (int i = 3; i < 6; i++) { // Set Cell Color : GREEN - HSSFRow row = sheet.getRow(0 + 9); + HSSFRow row = sheet.getRow(9); row.createCell(i - 3).setCellStyle( createColorStyle(wb, IndexedColors.GREEN)); obj_cnt++; diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java index e26146a1eb..d009a6f58a 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java @@ -17,15 +17,14 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +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.Iterator; import java.util.Map; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -34,17 +33,16 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestHSSFPalette { - private PaletteRecord _palette; private HSSFPalette _hssfPalette; - @Before + @BeforeEach public void setUp() { - _palette = new PaletteRecord(); + PaletteRecord _palette = new PaletteRecord(); _hssfPalette = new HSSFPalette(_palette); } @@ -66,27 +64,27 @@ public final class TestHSSFPalette { palette = book.getCustomPalette(); HSSFColor color = palette.getColor(HSSFColorPredefined.CORAL.getIndex()); //unmodified - assertNotNull("Unexpected null in custom palette (unmodified index)", color); + 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(msg, expectedRGB[0], actualRGB[0]); - assertEquals(msg, expectedRGB[1], actualRGB[1]); - assertEquals(msg, expectedRGB[2], actualRGB[2]); + assertEquals(expectedRGB[0], actualRGB[0], msg); + assertEquals(expectedRGB[1], actualRGB[1], msg); + assertEquals(expectedRGB[2], actualRGB[2], msg); color = palette.getColor((short) 0x12); - assertNotNull("Unexpected null in custom palette (modified)", color); + assertNotNull(color, "Unexpected null in custom palette (modified)"); actualRGB = color.getTriplet(); msg = "Expected palette modification to be preserved across save"; - assertEquals(msg, (short) 101, actualRGB[0]); - assertEquals(msg, (short) 230, actualRGB[1]); - assertEquals(msg, (short) 100, actualRGB[2]); + 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("deprecation") + @SuppressWarnings("ConstantConditions") @Test public void testPaletteFromCellColours() { HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls"); @@ -105,6 +103,7 @@ public final class TestHSSFPalette { 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)); @@ -145,11 +144,12 @@ public final class TestHSSFPalette { assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString()); } + @SuppressWarnings("ConstantConditions") @Test public 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] @@ -218,7 +218,7 @@ public final class TestHSSFPalette { 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(), @@ -228,23 +228,17 @@ public final class TestHSSFPalette { 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 public void testGnumericStrings() { - compareToDefaults(new ColorComparator() { - @Override - public void compare(HSSFColor expected, HSSFColor palette) - { - assertEquals(expected.getHexString(), palette.getHexString()); - } - }); + compareToDefaults((expected, palette) -> assertEquals(expected.getHexString(), palette.getHexString())); } /** @@ -258,25 +252,18 @@ public final class TestHSSFPalette { _hssfPalette.setColorAtIndex((short) 0x45, (byte) 255, (byte) 255, (byte) 255); //should still match defaults; - compareToDefaults(new ColorComparator() { - @Override - public void compare(HSSFColor expected, HSSFColor palette) - { - short[] s1 = expected.getTriplet(); - short[] s2 = palette.getTriplet(); - assertEquals(s1[0], s2[0]); - assertEquals(s1[1], s2[1]); - assertEquals(s1[2], s2[2]); - } + 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(); - Iterator it = colors.keySet().iterator(); - while (it.hasNext()) - { - Number index = it.next(); + for (Integer index : colors.keySet()) { HSSFColor expectedColor = colors.get(index); HSSFColor paletteColor = _hssfPalette.getColor(index.shortValue()); c.compare(expectedColor, paletteColor); @@ -285,16 +272,11 @@ public final class TestHSSFPalette { @Test public void testAddColor() { - try - { - _hssfPalette.addColor((byte)10,(byte)10,(byte)10); - fail(); - } catch (RuntimeException e) { - // Failing because by default there are no colours left in the palette. - } + assertThrows(RuntimeException.class, () -> _hssfPalette.addColor((byte)10,(byte)10,(byte)10), + "Failing because by default there are no colours left in the palette."); } - private static interface ColorComparator { + private interface ColorComparator { void compare(HSSFColor expected, HSSFColor palette); } @@ -304,7 +286,7 @@ public final class TestHSSFPalette { Color color = Color.decode("#006B6B"); HSSFPalette palette = wb.getCustomPalette(); - + HSSFColor hssfColor = palette.findColor((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); assertNull(hssfColor); @@ -317,7 +299,7 @@ public final class TestHSSFPalette { 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 index ff65cbe113..4e81dbc402 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertNotNull; +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.Test; +import org.junit.jupiter.api.Test; public final class TestHSSFPatriarch { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java index 95bd508770..5de42c63ef 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.Arrays; @@ -34,7 +34,7 @@ import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHSSFPicture extends BaseTestPicture { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java index 986bad978d..0a9a0b8894 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +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; @@ -31,15 +31,15 @@ import javax.imageio.IIOException; import javax.imageio.ImageIO; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.BeforeClass; -import org.junit.Test; +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. */ public final class TestHSSFPictureData { - @BeforeClass + @BeforeAll public static void setUpClass() { final String tmpDirProperty = System.getProperty("java.io.tmpdir"); if(tmpDirProperty == null || "".equals(tmpDirProperty)) { @@ -86,7 +86,7 @@ public final class TestHSSFPictureData { } } } catch (IIOException e) { - assertFalse(e.getMessage(), e.getMessage().contains("Can't create cache file")); + assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage()); } } @@ -100,7 +100,7 @@ public final class TestHSSFPictureData { HSSFPictureData pict = lst.get(0); String ext = pict.suggestFileExtension(); - assertEquals("Expected a PNG.", "png", ext); + assertEquals("png", ext, "Expected a PNG."); //try to read image data using javax.imageio.* (JDK 1.4+) byte[] data = pict.getData(); @@ -111,7 +111,7 @@ public final class TestHSSFPictureData { assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); assertEquals("image/png", pict.getMimeType()); } catch (IIOException e) { - assertFalse(e.getMessage(), e.getMessage().contains("Can't create cache file")); + assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage()); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java index 07f37d8e4a..9ba33f7d8c 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java @@ -22,7 +22,7 @@ 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.Before; +import org.junit.jupiter.api.BeforeEach; public class TestHSSFRangeCopier extends BaseTestRangeCopier { @@ -32,7 +32,7 @@ public class TestHSSFRangeCopier extends BaseTestRangeCopier { testDataProvider = HSSFITestDataProvider.instance; } - @Before + @BeforeEach public void init() { workbook = HSSFTestDataSamples.openSampleWorkbook("tile-range-test.xls"); initSheets(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java index 442bf7e8c5..36d8f13c78 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestHSSFRichTextString { @Test diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java index 53d799e953..0bfef5735b 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java @@ -17,6 +17,13 @@ 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; @@ -24,9 +31,7 @@ import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.RowRecord; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.BaseTestRow; -import org.junit.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; /** * Test HSSFRow is okay. @@ -67,9 +72,8 @@ public final class TestHSSFRow extends BaseTestRow { HSSFRow row = new HSSFRow(workbook, sheet, rowRec); HSSFCell cell = row.createCellFromRecord(br); - if (row.getFirstCellNum() == 2 && row.getLastCellNum() == 5) { - fail("Identified bug 46654a"); - } + assertFalse(row.getFirstCellNum() == 2 && row.getLastCellNum() == 5, "Identified bug 46654a"); + assertEquals(COL_IX, row.getFirstCellNum()); assertEquals(COL_IX + 1, row.getLastCellNum()); row.removeCell(cell); @@ -100,20 +104,10 @@ public final class TestHSSFRow extends BaseTestRow { assertEquals(4, row.getLastCellNum()); // Try to move to somewhere else that's used - try { - row.moveCell(cellB2, (short)3); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellB2, (short)3)); // Try to move one off a different row - try { - row.moveCell(cellA2, (short)3); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellA2, (short)3)); // Move somewhere spare assertNotNull(row.getCell(1)); @@ -124,7 +118,7 @@ public final class TestHSSFRow extends BaseTestRow { assertEquals(5, cellB2.getColumnIndex()); assertEquals(2, row.getFirstCellNum()); assertEquals(6, row.getLastCellNum()); - + workbook.close(); } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java index 09906b8e27..38f5b28422 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java @@ -18,7 +18,15 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.*; +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; @@ -43,7 +51,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests HSSFSheet. This test case is very incomplete at the moment. @@ -390,10 +398,10 @@ public final class TestHSSFSheet extends BaseTestSheet { HSSFSheet s = wb.createSheet(); s.protectSheet("abcdefghij"); WorksheetProtectionBlock pb = s.getSheet().getProtectionBlock(); - assertTrue("protection should be on", pb.isSheetProtected()); - assertTrue("object protection should be on", pb.isObjectProtected()); - assertTrue("scenario protection should be on", pb.isScenarioProtected()); - assertEquals("well known value for top secret hash should be " + Integer.toHexString(expectedHash).substring(4), expectedHash, pb.getPasswordHash()); + 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)); } } @@ -465,30 +473,18 @@ public final class TestHSSFSheet extends BaseTestSheet { assertEquals(sclLoc, window2Loc + 1); // verify limits - try { - sheet.setZoom(0); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(65536); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(2, 0); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(2, 65536); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - } + 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()); } } @@ -504,26 +500,26 @@ public final class TestHSSFSheet extends BaseTestSheet { HSSFSheet sheet = wb1.getSheetAt(0); assertNotNull(sheet); - assertEquals("1 row page break", 1, sheet.getRowBreaks().length); - assertEquals("1 column page break", 1, sheet.getColumnBreaks().length); + assertEquals(1, sheet.getRowBreaks().length, "1 row page break"); + assertEquals(1, sheet.getColumnBreaks().length, "1 column page break"); - assertTrue("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short) 4)); + 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("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); + 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("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short) 4)); + assertTrue(sheet.isRowBroken(22), "No row page break"); + assertTrue(sheet.isColumnBroken((short) 4), "No column page break"); - assertEquals("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); + assertEquals(2, sheet.getRowBreaks().length, "row breaks number"); + assertEquals(2, sheet.getColumnBreaks().length, "column breaks number"); } } } @@ -532,8 +528,8 @@ public final class TestHSSFSheet extends BaseTestSheet { public void dbcsName () throws IOException { try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls")) { wb.getSheetAt(1); - assertEquals("DBCS Sheet Name 2", wb.getSheetName(1), "\u090f\u0915"); - assertEquals("DBCS Sheet Name 1", wb.getSheetName(0), "\u091c\u093e"); + assertEquals(wb.getSheetName(1), "\u090f\u0915", "DBCS Sheet Name 2"); + assertEquals(wb.getSheetName(0), "\u091c\u093e", "DBCS Sheet Name 1"); } } @@ -551,8 +547,8 @@ public final class TestHSSFSheet extends BaseTestSheet { short toprow = (short) 100; short leftcol = (short) 50; sheet.showInPane(toprow, leftcol); - assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow()); - assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol()); + assertEquals(toprow, sheet.getTopRow(), "HSSFSheet.getTopRow()"); + assertEquals(leftcol, sheet.getLeftCol(), "HSSFSheet.getLeftCol()"); } } @@ -597,8 +593,8 @@ public final class TestHSSFSheet extends BaseTestSheet { // autoSize the first column and check its size before the merged region (1,0,1,1) is set: // it has to be based on the 2nd row width sheet.autoSizeColumn((short) 0); - assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth(0) >= minWithRow1And2); - assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth(0) <= maxWithRow1And2); + 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))); @@ -779,11 +775,11 @@ public final class TestHSSFSheet extends BaseTestSheet { try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls")) { HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(0); - assertNotNull("Identified bug 41187 a", row); + assertNotNull(row, "Identified bug 41187 a"); - assertNotEquals("Identified bug 41187 b", (short) 0, row.getHeight()); + assertNotEquals((short) 0, row.getHeight(), "Identified bug 41187 b"); - assertEquals("Hi Excel!", row.getCell(0).getRichStringCellValue().getString()); + assertEquals(row.getCell(0).getRichStringCellValue().getString(), "Hi Excel!"); // check row height for 'default' flag assertEquals((short) 0xFF, row.getHeight()); @@ -838,12 +834,10 @@ public final class TestHSSFSheet extends BaseTestSheet { final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars wb.createSheet(SAME_PREFIX + "Dxxxx"); - try { - wb.createSheet(SAME_PREFIX + "Dyyyy"); // identical up to the 32nd char - fail("Expected exception not thrown"); - } catch (IllegalArgumentException e) { - assertEquals("The workbook already contains a sheet named 'A123456789B123456789C123456789Dyyyy'", e.getMessage()); - } + // 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 } } @@ -923,8 +917,8 @@ public final class TestHSSFSheet extends BaseTestSheet { // The built-in name for auto-filter must consist of a single Area3d Ptg. Ptg[] ptg = name.getNameDefinition(); - assertEquals("The built-in name for auto-filter must consist of a single Area3d Ptg", 1, ptg.length); - assertTrue("The built-in name for auto-filter must consist of a single Area3d Ptg", ptg[0] instanceof Area3DPtg); + 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()); @@ -1003,12 +997,10 @@ public final class TestHSSFSheet extends BaseTestSheet { assertEquals(40000, sheet.getColumnWidth((short) 10)); //The maximum column width for an individual cell is 255 characters - try { - sheet.setColumnWidth((short) 9, 256 * 256); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage()); - } + 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)) { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java index f5be8470d2..5da9a1c606 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java @@ -24,14 +24,14 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestHSSFSheetShiftColumns extends BaseTestSheetShiftColumns { public TestHSSFSheetShiftColumns() { - super(); + super(); workbook = new HSSFWorkbook(); - _testDataProvider = HSSFITestDataProvider.instance; + _testDataProvider = HSSFITestDataProvider.instance; } protected Workbook openWorkbook(String spreadsheetFileName) @@ -42,45 +42,45 @@ public class TestHSSFSheetShiftColumns extends BaseTestSheetShiftColumns { protected Workbook getReadBackWorkbook(Workbook wb) throws IOException { return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)wb); } - - @Override - @Ignore("see ") + + @Override + @Disabled("see ") @Test public void shiftMergedColumnsToMergedColumnsLeft() throws IOException { - // 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 - @Ignore("see ") - @Test - public void shiftMergedColumnsToMergedColumnsRight() throws IOException { - // 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 - @Ignore("see ") - @Test - public void testBug54524() throws IOException { - // 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 - @Ignore("see ") - @Test - public void testCommentsShifting() throws IOException { - // 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 - @Ignore("see ") - @Test - public void testShiftWithMergedRegions() throws IOException { - // 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. + // 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 - @Ignore("see ") + @Disabled("see ") + @Test + public void shiftMergedColumnsToMergedColumnsRight() throws IOException { + // 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 ") + @Test + public void testBug54524() throws IOException { + // 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 ") + @Test + public void testCommentsShifting() throws IOException { + // 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 ") + @Test + public void testShiftWithMergedRegions() throws IOException { + // 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 ") @Test public void testShiftHyperlinks() throws IOException {} } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java index cc06e8fca6..7007c1edbc 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -33,14 +33,13 @@ 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.Record; 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.Test; +import org.junit.jupiter.api.Test; /** * Test array formulas in HSSF @@ -113,7 +112,7 @@ public final class TestHSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateA RowRecordsAggregate rra = s.getSheet().getRowsAggregate(); SharedValueManager svm = POITestCase.getFieldValue(RowRecordsAggregate.class, rra, SharedValueManager.class, "_sharedValueManager"); - assertNull("Array record was not cleaned up properly.", svm.getArrayRecord(4, 1)); + 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 index e727e321bd..8d01fb2bc1 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test HSSFTextbox. diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java index fde0d769d2..4a7c855958 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java @@ -19,12 +19,13 @@ 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.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -70,14 +71,17 @@ 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.Ignore; -import org.junit.Test; +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; /** * 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); @@ -208,9 +212,9 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { // Demonstrate bug 44525: // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse("Identified bug 44523 a", sheet1.isSelected()); + assertFalse(sheet1.isSelected(), "Identified bug 44523 a"); wb.setActiveSheet(1); - assertFalse("Identified bug 44523 b", sheet1.isActive()); + assertFalse(sheet1.isActive(), "Identified bug 44523 b"); confirmActiveSelected(sheet1, false); confirmActiveSelected(sheet2, true); @@ -229,7 +233,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } private static void assertCollectionsEquals(Collection expected, Collection actual) { - assertEquals("size", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size()); for (int e : expected) { assertTrue(actual.contains(e)); } @@ -278,22 +282,6 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertFalse(sheet0.isActive()); assertTrue(sheet2.isActive()); - /*{ // helpful if viewing this workbook in excel: - sheet0.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet0")); - sheet1.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet1")); - sheet2.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet2")); - sheet3.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet3")); - - try { - File fOut = TempFile.createTempFile("sheetMultiSelect", ".xls"); - FileOutputStream os = new FileOutputStream(fOut); - wb.write(os); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }*/ - wb.close(); } @@ -325,8 +313,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { wb.removeSheetAt(3); // after removing the only active/selected sheet, another should be active/selected in its place - assertTrue("identified bug 40414 a", sheet4.isSelected()); - assertTrue("identified bug 40414 b", sheet4.isActive()); + assertTrue(sheet4.isSelected(), "identified bug 40414 a"); + assertTrue(sheet4.isActive(), "identified bug 40414 b"); confirmActiveSelected(sheet0, false); confirmActiveSelected(sheet1, false); @@ -370,8 +358,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { private static void confirmActiveSelected(HSSFSheet sheet, boolean expectedActive, boolean expectedSelected) { - assertEquals("active", expectedActive, sheet.isActive()); - assertEquals("selected", expectedSelected, sheet.isSelected()); + assertEquals(expectedActive, sheet.isActive(), "active"); + assertEquals(expectedSelected, sheet.isSelected(), "selected"); } /** @@ -382,21 +370,15 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { */ @Test public void sheetSerializeSizeMismatch_bug45066() throws IOException { - 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 - try { - wb.getBytes(); - fail("Identified bug 45066 a"); - } catch (IllegalStateException e) { - // Expected badly behaved sheet record to cause exception + 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")); } - - wb.close(); } /** @@ -572,7 +554,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { */ @Test public void bug47920() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(POIDataSamples.getSpreadSheetInstance().openResourceAsStream("47920.xls")); + POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs1); ClassID clsid1 = fs1.getRoot().getStorageClsid(); @@ -593,34 +575,19 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { * If we try to open an old (pre-97) workbook, we get a helpful * Exception give to explain what we've done wrong */ - @Test - public void helpfulExceptionOnOldFiles() throws Exception { - InputStream excel4 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_4.xls"); - try { - new HSSFWorkbook(excel4).close(); - fail("Shouldn't be able to load an Excel 4 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF4"); + @ParameterizedTest + @CsvSource({ + "testEXCEL_4.xls,BIFF4", + "testEXCEL_5.xls,BIFF5", + "testEXCEL_95.xls,BIFF5" + }) + public 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); } - excel4.close(); - - InputStream excel5 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_5.xls"); - try { - new HSSFWorkbook(excel5).close(); - fail("Shouldn't be able to load an Excel 5 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF5"); - } - excel5.close(); - - InputStream excel95 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_95.xls"); - try { - new HSSFWorkbook(excel95).close(); - fail("Shouldn't be able to load an Excel 95 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF5"); - } - excel95.close(); } /** @@ -717,25 +684,20 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { @Test public void cellStylesLimit() throws IOException { - Workbook wb = new HSSFWorkbook(); - int numBuiltInStyles = wb.getNumCellStyles(); - int MAX_STYLES = 4030; - int limit = MAX_STYLES - numBuiltInStyles; - for(int i=0; i < limit; i++){ - /* HSSFCellStyle style =*/ wb.createCellStyle(); - } + 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()); - try { - /*HSSFCellStyle style =*/ wb.createCellStyle(); - fail("expected exception"); - } catch (IllegalStateException e){ + 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()); + "You can define up to 4000 styles in a .xls workbook", e.getMessage()); + assertEquals(MAX_STYLES, wb.getNumCellStyles()); } - assertEquals(MAX_STYLES, wb.getNumCellStyles()); - - wb.close(); } @Test @@ -831,10 +793,10 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } // Should throw exception about invalid POIFSFileSystem - @Test(expected=IllegalArgumentException.class) + @Test public void emptyDirectoryNode() throws IOException { try (POIFSFileSystem fs = new POIFSFileSystem()) { - new HSSFWorkbook(fs).close(); + assertThrows(IllegalArgumentException.class, () -> new HSSFWorkbook(fs).close()); } } @@ -856,9 +818,9 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { // Demonstrate bug 44525: // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse("Identified bug 44523 a", sheet1.isSelected()); + assertFalse(sheet1.isSelected(), "Identified bug 44523 a"); wb.setActiveSheet(1); - assertFalse("Identified bug 44523 b", sheet1.isActive()); + assertFalse(sheet1.isActive(), "Identified bug 44523 b"); confirmActiveSelected(sheet1, false); confirmActiveSelected(sheet2, true); @@ -876,12 +838,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { public void names() throws IOException { HSSFWorkbook wb=new HSSFWorkbook(); - try { - wb.getNameAt(0); - fail("Fails without any defined names"); - } catch (IllegalStateException e) { - assertTrue(e.getMessage(), e.getMessage().contains("no defined names")); - } + IllegalStateException ex1 = assertThrows(IllegalStateException.class, () -> wb.getNameAt(0)); + assertTrue(ex1.getMessage().contains("no defined names")); HSSFName name = wb.createName(); assertNotNull(name); @@ -894,19 +852,11 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertEquals(0, wb.getNameIndex(name)); assertEquals(0, wb.getNameIndex("myname")); - try { - wb.getNameAt(5); - fail("Fails without any defined names"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("outside the allowable range")); - } + IllegalArgumentException ex2 = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(5)); + assertTrue(ex2.getMessage().contains("outside the allowable range")); - try { - wb.getNameAt(-3); - fail("Fails without any defined names"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("outside the allowable range")); - } + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(-3)); + assertTrue(ex.getMessage().contains("outside the allowable range")); wb.close(); } @@ -930,13 +880,6 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { wb.writeProtectWorkbook("mypassword", "myuser"); assertTrue(wb.isWriteProtected()); -// OutputStream os = new FileOutputStream("/tmp/protected.xls"); -// try { -// wb.write(os); -// } finally { -// os.close(); -// } - wb.unwriteProtectWorkbook(); assertFalse(wb.isWriteProtected()); @@ -969,8 +912,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { int expected = wb.getWorkbook().getSize(); int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - assertEquals("Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected, - expected, written); + 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"); @@ -1012,8 +954,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { int expected = wb.getWorkbook().getSize(); int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - assertEquals("Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected, - expected, written); + assertEquals(expected, written, "Did not have the expected size when writing the workbook"); HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest"); @@ -1105,7 +1046,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } } - assertTrue("Should find some images via Client or Child anchors, but did not find any at all", found); + assertTrue(found, "Should find some images via Client or Child anchors, but did not find any at all"); workbook.close(); } @@ -1159,7 +1100,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { @Test public void closeDoesNotModifyWorkbook() throws IOException { final String filename = "SampleSS.xls"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); + final File file = samples.getFile(filename); Workbook wb; // File via POIFileStream (java.nio) @@ -1186,47 +1127,29 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { @Test public void invalidInPlaceWrite() throws Exception { - HSSFWorkbook wb; - // Can't work for new files - wb = new HSSFWorkbook(); - try { - wb.write(); - fail("Shouldn't work for new files"); - } catch (IllegalStateException e) { - // expected here + try (HSSFWorkbook wb = new HSSFWorkbook()) { + assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for new files"); } - wb.close(); // Can't work for InputStream opened files - wb = new HSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls")); - try { - wb.write(); - fail("Shouldn't work for InputStream"); - } catch (IllegalStateException e) { - // expected here + try (InputStream is = samples.openResourceAsStream("SampleSS.xls"); + HSSFWorkbook wb = new HSSFWorkbook(is)) { + assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for InputStream"); } - wb.close(); // Can't work for Read-Only files - POIFSFileSystem fs = new POIFSFileSystem( - POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls"), true); - wb = new HSSFWorkbook(fs); - try { - wb.write(); - fail("Shouldn't work for Read Only"); - } catch (IllegalStateException e) { - // expected here + 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"); } - wb.close(); } @Test public void inPlaceWrite() throws Exception { // Setup as a copy of a known-good file final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - try (InputStream inputStream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls"); + try (InputStream inputStream = samples.openResourceAsStream("SampleSS.xls"); FileOutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } @@ -1255,7 +1178,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { public void testWriteToNewFile() throws Exception { // Open from a Stream HSSFWorkbook wb = new HSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls")); + samples.openResourceAsStream("SampleSS.xls")); // Save to a new temp file final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); @@ -1268,7 +1191,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { wb.close(); } - @Ignore + @Disabled @Test @Override public void createDrawing() throws Exception { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java index 8d337e0888..67370a33da 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java @@ -17,14 +17,15 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +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.ss.formula.eval.ErrorEval; @@ -38,14 +39,11 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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; -@RunWith(Parameterized.class) public final class TestMatrixFormulasFromBinarySpreadsheet { private static final POILogger LOG = POILogFactory.getLogger(TestMatrixFormulasFromBinarySpreadsheet.class); @@ -65,7 +63,7 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { * then adding matrix size parameter would be useful and parsing would be based off that. */ - private static interface Navigator { + private interface Navigator { /** * Name of the test spreadsheet (found in the standard test data folder) */ @@ -98,20 +96,15 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { } /* Parameters for test case */ - @Parameter(0) - public String targetFunctionName; - @Parameter(1) - public int formulasRowIdx; - @AfterClass + @AfterAll public static void closeResource() throws Exception { LocaleUtil.setUserLocale(userLocale); workbook.close(); } /* generating parameter instances */ - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 @@ -122,37 +115,32 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { sheet = workbook.getSheetAt(0); evaluator = new HSSFFormulaEvaluator(workbook); - List data = new ArrayList(); + List data = new ArrayList<>(); - processFunctionGroup(data, Navigator.START_OPERATORS_ROW_INDEX, null); + processFunctionGroup(data); - return data; + return data.stream(); } - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass null to test all functions - */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { + 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("Test spreadsheet cell empty on row (" + assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" + (rowIndex) + "). Expected function name or '" - + Navigator.END_OF_TESTS + "'", targetFunctionName); + + Navigator.END_OF_TESTS + "'"); if(targetFunctionName.equals(Navigator.END_OF_TESTS)) { // found end of functions list break; } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - data.add(new Object[]{targetFunctionName, rowIndex}); - } + data.add(Arguments.of(targetFunctionName, rowIndex)); } } - @Test - public void processFunctionRow() { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow(String targetFunctionName, int formulasRowIdx) { int endColNum = Navigator.START_RESULT_COL_INDEX + Navigator.COL_OFF_EXPECTED_RESULT; @@ -177,31 +165,32 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" , targetFunctionName, c.getCellFormula(), rowNum, colNum); - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); + 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(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(CellType.BLANK, actValue.getCellType(), msg); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); - assertEquals(msg, ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue())); + 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(msg, CellType.NUMERIC, actValue.getCellType()); - TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + TestMathX.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + cellType); @@ -215,7 +204,6 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { */ private static String getTargetFunctionName(Row r) { if(r == null) { - LOG.log(POILogger.WARN,"Warning - given null row, can't figure out function name"); return null; } @@ -226,20 +214,10 @@ public final class TestMatrixFormulasFromBinarySpreadsheet { "Warning - Row " + r.getRowNum() + " has no cell " + Navigator.START_OPERATORS_COL_INDEX + ", can't figure out function name"); return null; } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - fail("Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; + 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 index 8d54e9b021..6a4a6dc885 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -26,11 +26,11 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for how HSSFWorkbook behaves with XLS files - * with a WORKBOOK or BOOK directory entry (instead of + * with a WORKBOOK or BOOK directory entry (instead of * the more usual, Workbook) */ public final class TestNonStandardWorkbookStreamNames { @@ -54,7 +54,7 @@ public final class TestNonStandardWorkbookStreamNames { // But not a Workbook one assertFalse(root.hasEntry("Workbook")); - + wb.close(); } @@ -75,7 +75,7 @@ public final class TestNonStandardWorkbookStreamNames { // But not a Workbook one and not a Summary one assertFalse(root.hasEntry("Workbook")); assertFalse(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)); - + wb.close(); } @@ -93,9 +93,9 @@ public final class TestNonStandardWorkbookStreamNames { // 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")); @@ -115,7 +115,7 @@ public final class TestNonStandardWorkbookStreamNames { 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(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java index cf1d1ba34e..340839bdde 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -34,38 +34,32 @@ 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.Test; +import org.junit.jupiter.api.Test; /** - * + * */ public final class TestOLE2Embeding { @Test public void testEmbeding() throws Exception { // This used to break, until bug #43116 was fixed - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); - - // Check we can get at the Escher layer still - workbook.getAllPictures(); - - workbook.close(); + try (HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls")) { + // Check we can get at the Escher layer still + workbook.getAllPictures(); + } } @Test public void testEmbeddedObjects() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); - - List objects = workbook.getAllEmbeddedObjects(); - assertEquals("Wrong number of objects", 2, objects.size()); - assertEquals("Wrong name for first object", "MBD06CAB431", - objects.get(0).getDirectory().getName()); - assertEquals("Wrong name for second object", "MBD06CAC85A", - objects.get(1).getDirectory().getName()); - - workbook.close(); + 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 public void testReallyEmbedSomething() throws Exception { HSSFWorkbook wb1 = new HSSFWorkbook(); @@ -81,7 +75,7 @@ public final class TestOLE2Embeding { 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; @@ -89,21 +83,21 @@ public final class TestOLE2Embeding { 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); @@ -117,10 +111,10 @@ public final class TestOLE2Embeding { // wb.write(fos); // fos.close(); // } - + HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); wb1.close(); - + ByteArrayOutputStream bos = new ByteArrayOutputStream(); HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0); Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); @@ -137,21 +131,21 @@ public final class TestOLE2Embeding { 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(); @@ -163,8 +157,8 @@ public final class TestOLE2Embeding { 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 index 1060aaadc1..62b27c1800 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Old-style setting of POIFS properties doesn't work with POI 3.0.2 @@ -103,7 +103,7 @@ public class TestPOIFSProperties { 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("Had: " + HexDump.toHex(bytes), 5120, bytes.length); + 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)); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java index 6ca0acda0f..30dfe80b5a 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java @@ -17,15 +17,15 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +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.Test; +import org.junit.jupiter.api.Test; public class TestPatriarch { @Test diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java index b47443b1b8..f76cd0983b 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java @@ -18,9 +18,9 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestPolygon { @Test @@ -71,7 +71,7 @@ public class TestPolygon { assertEquals(expected.length, actual.length); assertArrayEquals(expected, actual); - + wb.close(); } @@ -100,10 +100,10 @@ public class TestPolygon { "" + ""; 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}); @@ -121,10 +121,10 @@ public class TestPolygon { "AQAEAA==" + ""; actual = verticesProp1.toXml("").replaceAll("[\r\n\t]",""); - + assertEquals(verticesProp1.getNumberOfElementsInArray(), 4); assertEquals(expected, actual); - + wb.close(); } @@ -173,7 +173,7 @@ public class TestPolygon { assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61}); assertEquals(polygon.getDrawAreaHeight(), 1011); assertEquals(polygon.getDrawAreaWidth(), 1021); - + wb3.close(); } @@ -227,7 +227,7 @@ public class TestPolygon { assertArrayEquals(polygon2.getYPoints(), new int[]{24,25,26}); assertEquals(polygon2.getDrawAreaHeight(), 204); assertEquals(polygon2.getDrawAreaWidth(), 203); - + wb3.close(); } @@ -243,7 +243,7 @@ public class TestPolygon { 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(); } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java index e7fe40c02f..7f0cc0c24f 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Calendar; import java.util.Date; @@ -31,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * @author Glen Stampoultzis (glens at apache.org) @@ -61,7 +61,7 @@ public final class TestReadWriteChart { 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 index 1977ef0caa..f94b63ce2e 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java @@ -18,14 +18,14 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test row styling functionality @@ -58,8 +58,8 @@ public final class TestRowStyle { try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb2); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); + assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); } } } @@ -90,8 +90,8 @@ public final class TestRowStyle { SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb2); - assertEquals("LAST ROW ", 1, s.getLastRowNum()); - assertEquals("FIRST ROW ", 0, s.getFirstRowNum()); + assertEquals(1, s.getLastRowNum(), "LAST ROW"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW"); } } } @@ -109,7 +109,6 @@ public final class TestRowStyle { public void testWriteSheetStyle() throws IOException { try (HSSFWorkbook wb = new HSSFWorkbook()) { HSSFSheet s = wb.createSheet(); - HSSFRow r = null; HSSFFont fnt = wb.createFont(); HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs2 = wb.createCellStyle(); @@ -126,7 +125,7 @@ public final class TestRowStyle { cs2.setFillPattern(FillPatternType.BRICKS); cs2.setFont(fnt); for (int rownum = 0; rownum < 100; rownum++) { - r = s.createRow(rownum); + HSSFRow r = s.createRow(rownum); r.setRowStyle(cs); r.createCell(0); @@ -140,34 +139,34 @@ public final class TestRowStyle { try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) { SanityChecker sanityChecker = new SanityChecker(); sanityChecker.checkHSSFWorkbook(wb2); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); + assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); s = wb2.getSheetAt(0); - assertNotNull("Sheet is not null", s); + assertNotNull(s, "Sheet is not null"); for (int rownum = 0; rownum < 100; rownum++) { - r = s.getRow(rownum); - assertNotNull("Row is not null", r); + HSSFRow r = s.getRow(rownum); + assertNotNull(r, "Row is not null"); cs = r.getRowStyle(); assertNotNull(cs); - assertEquals("Bottom Border Style for row:", BorderStyle.THIN, cs.getBorderBottom()); - assertEquals("Left Border Style for row:", BorderStyle.THIN, cs.getBorderLeft()); - assertEquals("Right Border Style for row:", BorderStyle.THIN, cs.getBorderRight()); - assertEquals("Top Border Style for row:", BorderStyle.THIN, cs.getBorderTop()); - assertEquals("FillForegroundColor for row:", 0xA, cs.getFillForegroundColor()); - assertEquals("FillPattern for row:", FillPatternType.BRICKS, cs.getFillPattern()); + 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("Row is not null", r); + assertNotNull(r, "Row is not null"); cs2 = r.getRowStyle(); assertNotNull(cs2); - assertEquals("FillForegroundColor for row: ", cs2.getFillForegroundColor(), (short) 0x0); - assertEquals("FillPattern for row: ", cs2.getFillPattern(), FillPatternType.BRICKS); + 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 index 0293348636..cd020fe6d1 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java @@ -17,7 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Arrays; @@ -30,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * A Test case for a test utility class.
@@ -43,7 +44,7 @@ public final class TestSanityChecker { private static BoundSheetRecord createBoundSheetRec() { return new BoundSheetRecord("Sheet1"); } - + @Test public void testCheckRecordOrder() { final SanityChecker c = new SanityChecker(); @@ -119,20 +120,10 @@ public final class TestSanityChecker { EOFRecord.instance, }); } + private static void confirmBadRecordOrder(final SanityChecker.CheckRecord[] check, Record[] recs) { final SanityChecker c = new SanityChecker(); final List records = Arrays.asList(recs); - try { - new Runnable() { - @Override - public void run() { - c.checkRecordOrder(records, check); - } - }.run(); - } catch (AssertionError pass) { - // expected during normal test - return; - } - fail("Did not get failure exception as expected"); + 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 index 46ca6b9560..c927b9273f 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestShapeGroup { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java index f9d172310b..0164a69189 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java @@ -21,12 +21,13 @@ 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.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; public final class TestSheetHiding extends BaseTestSheetHiding { public TestSheetHiding() { @@ -60,11 +61,6 @@ public final class TestSheetHiding extends BaseTestSheetHiding { assertEquals(SheetVisibility.HIDDEN, intWb.getSheetVisibility(1)); // check sheet-index with index out of bounds => throws exception - try { - wb.setSheetVisibility(10, SheetVisibility.HIDDEN); - fail("Should catch exception here"); - } catch (RuntimeException e) { - // expected here - } + 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 index bb16cf9879..751f7f5fb3 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java @@ -18,15 +18,15 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * @author Evgeniy Berlog @@ -75,7 +75,7 @@ public class TestText { assertEquals(expected.length, actual.length); assertArrayEquals(expected, actual); - + TextObjectRecord tor = textbox.getTextObjectRecord(); expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); @@ -83,7 +83,7 @@ public class TestText { assertEquals(expected.length, actual.length); assertArrayEquals(expected, actual); - + wb.close(); } @@ -118,7 +118,7 @@ public class TestText { 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(); } @@ -191,7 +191,7 @@ public class TestText { assertEquals(textbox.getMarginLeft(), 81); assertEquals(textbox.getMarginRight(), 91); assertEquals(textbox.getMarginTop(), 101); - + wb3.close(); } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java index 40afff2131..828e8b6087 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java @@ -17,8 +17,8 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * @author aviks diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java index 6535246725..d4e19943b5 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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.Test; +import org.junit.jupiter.api.Test; public final class TestUnicodeWorkbook { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java index 79d9553eca..678dd9e976 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java @@ -23,13 +23,12 @@ 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.Record; import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Class to test Workbook functionality @@ -62,23 +61,22 @@ public final class TestWorkbook { */ @Test public void testWriteSheetSimple() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); + try (HSSFWorkbook wb1 = new HSSFWorkbook()) { + HSSFSheet s = wb1.createSheet(); - populateSheet(s); + populateSheet(s); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); + 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("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - wb2.close(); - wb1.close(); + sanityChecker.checkHSSFWorkbook(wb2); + s = wb2.getSheetAt(0); + assertEquals(99, s.getLastRowNum(), "LAST ROW == 99"); + assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0"); + } + } } /** @@ -107,16 +105,16 @@ public final class TestWorkbook { } HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - + sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 74", 74, s.getLastRowNum()); - assertEquals("FIRST ROW == 25", 25, s.getFirstRowNum()); + assertEquals(74, s.getLastRowNum(), "LAST ROW == 74"); + assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25"); sanityChecker.checkHSSFWorkbook(wb2); s = wb2.getSheetAt(0); - assertEquals("LAST ROW == 74", 74, s.getLastRowNum()); - assertEquals("FIRST ROW == 25", 25, s.getFirstRowNum()); - + assertEquals(74, s.getLastRowNum(), "LAST ROW == 74"); + assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25"); + wb2.close(); wb1.close(); } @@ -155,7 +153,7 @@ public final class TestWorkbook { assertEquals(1.25,cell.getNumericCellValue(), 1e-10); assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); - + wb.close(); } @@ -214,7 +212,7 @@ public final class TestWorkbook { 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(); } @@ -241,7 +239,7 @@ public final class TestWorkbook { sheet = wb2.getSheetAt(0); cell = sheet.getRow(0).getCell(0); assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - + wb2.close(); wb1.close(); } @@ -279,7 +277,7 @@ public final class TestWorkbook { assertEquals(REPLACED, cell.getRichStringCellValue().getString()); cell = sheet.getRow(1).getCell(1); assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString()); - + wb2.close(); wb1.close(); } @@ -312,7 +310,7 @@ public final class TestWorkbook { HSSFCell cell = sheet.getRow(k).getCell(0); assertEquals(REPLACED, cell.getRichStringCellValue().getString()); } - + wb2.close(); wb1.close(); } @@ -347,7 +345,7 @@ public final class TestWorkbook { 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(); } @@ -366,7 +364,7 @@ public final class TestWorkbook { HSSFCell c = s.getRow(0).getCell(0); assertEquals(CellType.NUMERIC, c.getCellType()); - + wb.close(); } @@ -442,7 +440,7 @@ public final class TestWorkbook { wb.setBackupFlag(false); assertEquals(0, record.getBackup()); assertFalse(wb.getBackupFlag()); - + wb.close(); } @@ -482,7 +480,7 @@ public final class TestWorkbook { RecordCounter rc = new RecordCounter(); sheet.getSheet().visitContainedRecords(rc, 0); assertEquals(1, rc.getCount()); - + workbook.close(); } @@ -503,7 +501,7 @@ public final class TestWorkbook { cell.setCellValue(i); } sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 32770", 32770, sheet.getLastRowNum()); + assertEquals(32770, sheet.getLastRowNum(), "LAST ROW == 32770"); cell = sheet.getRow(32770).getCell(0); double lastVal = cell.getNumericCellValue(); @@ -511,9 +509,9 @@ public final class TestWorkbook { HSSFSheet s = wb2.getSheetAt(0); row = s.getRow(32770); cell = row.getCell(0); - assertEquals("Value from last row == 32770", lastVal, cell.getNumericCellValue(), 0); - assertEquals("LAST ROW == 32770", 32770, s.getLastRowNum()); - + assertEquals(lastVal, cell.getNumericCellValue(), 0, "Value from last row == 32770"); + assertEquals(32770, s.getLastRowNum(), "LAST ROW == 32770"); + wb2.close(); wb1.close(); } @@ -539,7 +537,7 @@ public final class TestWorkbook { sheet = wb2.getSheetAt(0); assertEquals("A:B", sheet.getRepeatingColumns().formatAsString()); assertEquals("1:1", sheet.getRepeatingRows().formatAsString()); - + wb2.close(); wb1.close(); } @@ -558,25 +556,14 @@ public final class TestWorkbook { HSSFCell cell = row.createCell(1); cell.setCellValue(new HSSFRichTextString("hi")); CellRangeAddress cra = new CellRangeAddress(-1, 1, -1, 1); - try { - sheet.setRepeatingColumns(cra); - fail("invalid start index is ignored"); - } catch (IllegalArgumentException e) { - // expected here - } - - try { - sheet.setRepeatingRows(cra); - fail("invalid start index is ignored"); - } catch (IllegalArgumentException e) { - // expected here - } + 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(); } @@ -590,12 +577,12 @@ public final class TestWorkbook { 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"; @@ -608,23 +595,29 @@ public final class TestWorkbook { 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/AllHSSFUtilTests.java b/src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.java deleted file mode 100644 index 7e71fb2de1..0000000000 --- a/src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.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.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.util. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaReference.class, - TestCellReference.class, - TestHSSFColor.class, - TestRKUtil.class -}) -public class AllHSSFUtilTests { -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java index fddd1e7603..c3c68a3dca 100644 --- a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java +++ b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java @@ -17,12 +17,12 @@ package org.apache.poi.hssf.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -44,27 +44,27 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestAreaReference { @Test public void testAreaRef1() { AreaReference ar = new AreaReference("$A$1:$B$2", SpreadsheetVersion.EXCEL97); - assertFalse("Two cells expected", ar.isSingleCell()); + assertFalse(ar.isSingleCell(), "Two cells expected"); CellReference cf = ar.getFirstCell(); - assertEquals("row is 4", 0, cf.getRow()); - assertEquals("col is 1", 0, cf.getCol()); - assertTrue("row is abs", cf.isRowAbsolute()); - assertTrue("col is abs", cf.isColAbsolute()); - assertEquals("string is $A$1", "$A$1", cf.formatAsString()); + 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("row is 4", 1, cf.getRow()); - assertEquals("col is 1", 1, cf.getCol()); - assertTrue("row is abs", cf.isRowAbsolute()); - assertTrue("col is abs", cf.isColAbsolute()); - assertEquals("string is $B$2", "$B$2", cf.formatAsString()); + 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); @@ -136,24 +136,9 @@ public final class TestAreaReference { // Check we can only create contiguous entries new AreaReference(refSimple, SpreadsheetVersion.EXCEL97); new AreaReference(ref2D, SpreadsheetVersion.EXCEL97); - try { - new AreaReference(refDCSimple, SpreadsheetVersion.EXCEL97); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - try { - new AreaReference(refDC2D, SpreadsheetVersion.EXCEL97); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - try { - new AreaReference(refDC3D, SpreadsheetVersion.EXCEL97); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected during successful test - } + 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; @@ -251,6 +236,7 @@ public final class TestAreaReference { HSSFName aNamedCell = wb.getName("test"); // Should have 2 references + assertNotNull(aNamedCell); String formulaRefs = aNamedCell.getRefersToFormula(); assertNotNull(formulaRefs); assertEquals(ref, formulaRefs); diff --git a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java b/src/testcases/org/apache/poi/hssf/util/TestCellReference.java index c7a7e10aa5..ab23476c1d 100644 --- a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java +++ b/src/testcases/org/apache/poi/hssf/util/TestCellReference.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.util; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.apache.poi.ss.SpreadsheetVersion; +import org.junit.jupiter.api.Test; /** * Tests for the HSSF and SS versions of CellReference. @@ -41,7 +41,7 @@ public final class TestCellReference { 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)); @@ -49,19 +49,15 @@ public final class TestCellReference { 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 - try { - CellReference.convertColStringToIndex("A$B$"); - fail("Column reference is invalid and shouldn't be accepted"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> CellReference.convertColStringToIndex("A$B$"), + "Column reference is invalid and shouldn't be accepted"); } @Test @@ -129,11 +125,11 @@ public final class TestCellReference { int expCol, boolean expIsRowAbs, boolean expIsColAbs, String expText) { assertEquals(expSheetName, cf.getSheetName()); - assertEquals("row index is wrong", expRow, cf.getRow()); - assertEquals("col index is wrong", expCol, cf.getCol()); - assertEquals("isRowAbsolute is wrong", expIsRowAbs, cf.isRowAbsolute()); - assertEquals("isColAbsolute is wrong", expIsColAbs, cf.isColAbsolute()); - assertEquals("text is wrong", expText, cf.formatAsString()); + 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 diff --git a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java b/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java index eb484a775e..ac636c8f5c 100644 --- a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java +++ b/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public final class TestHSSFColor { @Test @@ -31,7 +31,7 @@ public final class TestHSSFColor { assertTrue(HSSFColorPredefined.YELLOW.getIndex() > 0); assertTrue(HSSFColorPredefined.YELLOW.getIndex2() > 0); } - + @Test public void testContents() { short[] triplet = HSSFColorPredefined.YELLOW.getTriplet(); @@ -39,14 +39,14 @@ public final class TestHSSFColor { assertEquals(255, triplet[0]); assertEquals(255, triplet[1]); assertEquals(0, triplet[2]); - + assertEquals("FFFF:FFFF:0", HSSFColorPredefined.YELLOW.getHexString()); } - + @Test public void testTripletHash() { Map triplets = HSSFColor.getTripletHash(); - + assertEquals( HSSFColorPredefined.MAROON.getColor(), triplets.get(HSSFColorPredefined.MAROON.getHexString()) diff --git a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java b/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java index 09fcaa40cf..28e1964ff7 100644 --- a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java +++ b/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the {@link RKUtil} class. diff --git a/src/testcases/org/apache/poi/poifs/AllPOIFSTests.java b/src/testcases/org/apache/poi/poifs/AllPOIFSTests.java deleted file mode 100644 index a50bfe6f43..0000000000 --- a/src/testcases/org/apache/poi/poifs/AllPOIFSTests.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.poifs; - -import org.apache.poi.poifs.eventfilesystem.TestPOIFSReaderRegistry; -import org.apache.poi.poifs.filesystem.AllPOIFSFileSystemTests; -import org.apache.poi.poifs.macros.TestVBAMacroReader; -import org.apache.poi.poifs.nio.TestDataSource; -import org.apache.poi.poifs.property.AllPOIFSPropertyTests; -import org.apache.poi.poifs.storage.AllPOIFSStorageTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for all sub-packages of org.apache.poi.poifs - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestPOIFSReaderRegistry.class - , TestDataSource.class - , TestVBAMacroReader.class - , AllPOIFSFileSystemTests.class - , AllPOIFSPropertyTests.class - , AllPOIFSStorageTests.class -}) -public final class AllPOIFSTests { -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java b/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java deleted file mode 100644 index 8bd67db91b..0000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.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.poifs.crypt; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.poifs.crypt. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBiff8DecryptingStream.class, - TestCipherAlgorithm.class, - TestXorEncryption.class -}) -public final class AllEncryptionTests { -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java b/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java index d57cbdda41..1ccdb3083a 100644 --- a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java +++ b/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java @@ -17,9 +17,9 @@ package org.apache.poi.poifs.crypt; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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; @@ -27,7 +27,7 @@ import javax.crypto.spec.SecretKeySpec; import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream; import org.apache.poi.util.HexRead; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Biff8DecryptingStream} @@ -118,7 +118,7 @@ public final class TestBiff8DecryptingStream { byte[] expData = HexRead.readFromString(expHexData); byte[] actData = new byte[expData.length]; _bds.readFully(actData); - assertArrayEquals("Data mismatch", expData, actData); + assertArrayEquals(expData, actData, "Data mismatch"); } } @@ -180,9 +180,9 @@ public final class TestBiff8DecryptingStream { Biff8DecryptingStream bds = st.getBDS(); int hval = bds.readDataSize(); // unencrypted int nextInt = bds.readInt(); - assertNotEquals("Indentified bug in key alignment after call to readHeaderUShort()",0x8F534029, nextInt); + assertNotEquals(0x8F534029, nextInt, "Indentified bug in key alignment after call to readHeaderUShort()"); assertEquals(0x16885243, nextInt); - assertNotEquals("readHeaderUShort() incorrectly decrypted result", 0x283E, hval); + assertNotEquals(0x283E, hval, "readHeaderUShort() incorrectly decrypted result"); assertEquals(0x504F, hval); // confirm next key change diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java b/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java index 68d6ab2901..998eacbd0f 100644 --- a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java +++ b/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java @@ -17,16 +17,17 @@ package org.apache.poi.poifs.crypt; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.poi.EncryptedDocumentException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCipherAlgorithm { @Test public void validInputs() { assertEquals(128, CipherAlgorithm.aes128.defaultKeySize); - + for(CipherAlgorithm alg : CipherAlgorithm.values()) { assertEquals(alg, CipherAlgorithm.valueOf(alg.toString())); } @@ -34,19 +35,11 @@ public class TestCipherAlgorithm { assertEquals(CipherAlgorithm.aes128, CipherAlgorithm.fromEcmaId(0x660E)); assertEquals(CipherAlgorithm.aes192, CipherAlgorithm.fromXmlId("AES", 192)); } - - @Test(expected=EncryptedDocumentException.class) - public void invalidEcmaId() { - CipherAlgorithm.fromEcmaId(0); - } - - @Test(expected=EncryptedDocumentException.class) - public void invalidXmlId1() { - CipherAlgorithm.fromXmlId("AES", 1); - } - - @Test(expected=EncryptedDocumentException.class) - public void invalidXmlId2() { - CipherAlgorithm.fromXmlId("RC1", 0x40); + + @Test + public 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 index 91894113bd..6a2d8d8709 100644 --- a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java +++ b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java @@ -19,7 +19,7 @@ package org.apache.poi.poifs.crypt; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -33,8 +33,8 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestXorEncryption { @@ -73,7 +73,7 @@ public class TestXorEncryption { } @Test - @Ignore("currently not supported") + @Disabled("currently not supported") public void encrypt() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { diff --git a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java b/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java index b1155c3f57..373b9af4fc 100644 --- a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java +++ b/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java @@ -18,9 +18,8 @@ package org.apache.poi.poifs.crypt.binaryrc4; import static org.apache.poi.util.HexRead.readFromString; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.security.GeneralSecurityException; @@ -29,20 +28,20 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestBinaryRC4 { @Test - public void createKeyDigest() throws GeneralSecurityException { + public 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("keyDigest mismatch", expResult, sk.getEncoded()); + + assertArrayEquals(expResult, sk.getEncoded(), "keyDigest mismatch"); } @Test @@ -81,7 +80,7 @@ public class TestBinaryRC4 { 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); @@ -96,11 +95,6 @@ public class TestBinaryRC4 { String pass = password == null ? Decryptor.DEFAULT_PASSWORD : password; boolean actResult = ei.getDecryptor().verifyPassword(pass); - if (expectedResult) { - assertTrue("validate failed", actResult); - } else { - assertFalse("validate succeeded unexpectedly", actResult); - } + 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 index f03bbf9127..ef4eec6417 100644 --- a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java +++ b/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java @@ -16,26 +16,35 @@ ==================================================================== */ package org.apache.poi.poifs.dev; +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.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; + import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; 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.TempFile; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.*; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestPOIFSDump { private static PrintStream SYSTEM; - @BeforeClass + @BeforeAll public static void setUp() throws UnsupportedEncodingException { SYSTEM = System.out; System.setOut(new PrintStream(new OutputStream() { @@ -46,7 +55,7 @@ public class TestPOIFSDump { }, false, "UTF-8")); } - @AfterClass + @AfterAll public static void resetSystemOut() { System.setOut(SYSTEM); } @@ -65,7 +74,7 @@ public class TestPOIFSDump { "-dump-mini-stream", }; - @After + @AfterEach public void tearDown() throws IOException { // clean up the directory that POIFSDump writes to deleteDirectory(new File(new File(TEST_FILE+"_dump").getName())); @@ -140,60 +149,28 @@ public class TestPOIFSDump { } } @Test - public void testInvalidFile() throws Exception { - try { - POIFSDump.main(new String[]{ - INVALID_FILE - }); - fail("Should fail with an exception"); - } catch (NotOLE2FileException e) { - // expected here - } - - try { - POIFSDump.main(new String[]{ - INVALID_XLSX_FILE - }); - fail("Should fail with an exception"); - } catch (OfficeXmlFileException e) { - // expected here - } + public 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) { - try { - POIFSDump.main(new String[]{ - option, - INVALID_FILE - }); - fail("Should fail with an exception"); - } catch (NotOLE2FileException e) { - // expected here - } - - try { - POIFSDump.main(new String[]{ - option, - INVALID_XLSX_FILE - }); - fail("Should fail with an exception"); - } catch (OfficeXmlFileException e) { - // expected here - } + assertThrows(NotOLE2FileException.class, () -> POIFSDump.main(new String[]{option, INVALID_FILE})); + assertThrows(OfficeXmlFileException.class, () -> POIFSDump.main(new String[]{option, INVALID_XLSX_FILE})); } } - @Ignore("Calls System.exit()") + @Disabled("Calls System.exit()") @Test public void testMainNoArgs() throws Exception { POIFSDump.main(new String[] {}); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testFailToWrite() throws IOException { File dir = TempFile.createTempFile("TestPOIFSDump", ".tst"); - assertTrue("Had: " + dir, dir.exists()); - assertTrue("Had: " + dir, dir.delete()); - assertTrue("Had: " + dir, dir.mkdirs()); + 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); @@ -204,6 +181,6 @@ public class TestPOIFSDump { // try with an invalid startBlock to trigger an exception // to validate that file-handles are closed properly - POIFSDump.dump(fs, 999999999, "mini-stream", dir); + 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/TestPOIFSReaderRegistry.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java index 9a87b3fe7f..89457e22b1 100644 --- a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java +++ b/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java @@ -17,16 +17,16 @@ package org.apache.poi.poifs.eventfilesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test POIFSReaderRegistry functionality diff --git a/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java b/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java deleted file mode 100644 index fff4a4fcda..0000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.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.poifs.filesystem; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Tests for org.apache.poi.poifs.filesystem - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDirectoryNode.class - , TestDocument.class - , TestDocumentDescriptor.class - , TestDocumentInputStream.class - , TestDocumentOutputStream.class - , TestEmptyDocument.class - , TestNotOLE2Exception.class - , TestOfficeXMLException.class - , TestPOIFSDocumentPath.class - , TestPOIFSFileSystem.class - , TestPropertySorter.class - , TestOle10Native.class -}) -public final class AllPOIFSFileSystemTests { -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java index b3363b9cae..92536e96f4 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java @@ -18,11 +18,11 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -31,7 +31,7 @@ import java.util.Iterator; import org.apache.poi.poifs.property.DirectoryProperty; import org.apache.poi.poifs.property.DocumentProperty; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test DirectoryNode functionality @@ -70,13 +70,7 @@ public final class TestDirectoryNode { assertEquals(0, node.getEntryCount()); // verify behavior of getEntry - try { - node.getEntry("foo"); - fail("should have caught FileNotFoundException"); - } catch (FileNotFoundException ignored) { - - // as expected - } + assertThrows(FileNotFoundException.class, () -> node.getEntry("foo")); // verify behavior of isDirectoryEntry assertTrue(node.isDirectoryEntry()); @@ -128,13 +122,7 @@ public final class TestDirectoryNode { child1.getEntry("child3"); node.getEntry("child2"); - try { - node.getEntry("child3"); - fail("should have caught FileNotFoundException"); - } catch (FileNotFoundException ignored) { - - // as expected - } + assertThrows(FileNotFoundException.class, () -> node.getEntry("child3")); // verify behavior of isDirectoryEntry assertTrue(node.isDirectoryEntry()); diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java index 59839672e3..91b58df0d9 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java @@ -18,10 +18,10 @@ package org.apache.poi.poifs.filesystem; import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -32,7 +32,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class to test POIFSDocument functionality diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java index 0081a43181..c548042a2e 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java @@ -17,10 +17,10 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test DocumentDescriptor functionality @@ -50,7 +50,7 @@ public final class TestDocumentDescriptor { DocumentDescriptor d2 = new DocumentDescriptor(paths[ k ], names[ n ]); if (m == n) { - assertEquals("" + j + "," + k + "," + m + "," + n, d1, d2); + assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n); } else { assertNotEquals(d1, d2); } @@ -80,7 +80,7 @@ public final class TestDocumentDescriptor { DocumentDescriptor d2 = new DocumentDescriptor(builtUpPaths[ k ], names[ n ]); if ((k == j) && (m == n)) { - assertEquals("" + j + "," + k + "," + m + "," + n, d1, d2); + assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n); } else { 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 index b6261817a9..af5466b052 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java @@ -17,10 +17,10 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -30,8 +30,8 @@ import java.util.Arrays; import org.apache.poi.POIDataSamples; import org.apache.poi.util.SuppressForbidden; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Class to test DocumentInputStream functionality @@ -45,7 +45,7 @@ public final class TestDocumentInputStream { // any block size private static final int _buffer_size = 6; - @Before + @BeforeEach public void setUp() throws Exception { int blocks = (_workbook_size + 511) / 512; @@ -87,13 +87,13 @@ public final class TestDocumentInputStream { /** * test available() behavior */ - @Test(expected = IllegalStateException.class) + @Test public void testAvailable() throws IOException { DocumentInputStream nstream = new DocumentInputStream(_workbook_n); assertEquals(_workbook_size, available(nstream)); nstream.close(); - available(nstream); + assertThrows(IllegalStateException.class, () -> available(nstream)); } /** @@ -109,10 +109,7 @@ public final class TestDocumentInputStream { // Read a fifth of it, and check all's correct stream.read(buffer); for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j], buffer[j] - ); + assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); } assertEquals(_workbook_size - buffer.length, available(stream)); @@ -125,10 +122,7 @@ public final class TestDocumentInputStream { // Read part of a block stream.read(small_buffer); for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j], small_buffer[j] - ); + assertEquals(_workbook_data[j], small_buffer[j], "checking byte " + j); } assertEquals(_workbook_size - small_buffer.length, available(stream)); stream.mark(0); @@ -136,10 +130,7 @@ public final class TestDocumentInputStream { // Read the next part stream.read(small_buffer); for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j + small_buffer.length], small_buffer[j] - ); + assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j); } assertEquals(_workbook_size - 2 * small_buffer.length, available(stream)); @@ -150,10 +141,7 @@ public final class TestDocumentInputStream { // Read stream.read(small_buffer); for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j + small_buffer.length], small_buffer[j] - ); + assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j); } assertEquals(_workbook_size - 2 * small_buffer.length, available(stream)); @@ -179,7 +167,7 @@ public final class TestDocumentInputStream { pos++; } - assertEquals("checking byte " + j, exp, small_buffer[j]); + assertEquals(exp, small_buffer[j], "checking byte " + j); } // Now repeat it with spanning multiple blocks @@ -188,10 +176,7 @@ public final class TestDocumentInputStream { buffer = new byte[_workbook_size / 5]; stream.read(buffer); for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j], buffer[j] - ); + assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); } assertEquals(_workbook_size - buffer.length, available(stream)); @@ -201,20 +186,15 @@ public final class TestDocumentInputStream { stream.read(buffer); for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[j], buffer[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)); + assertEquals(_workbook_size - (2 * buffer.length), available(stream)); for (int j = buffer.length; j < (2 * buffer.length); j++) { - assertEquals("checking byte " + j, _workbook_data[j], - buffer[j - buffer.length]); + assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j); } // Reset, should go back to only one buffer full read @@ -223,11 +203,9 @@ public final class TestDocumentInputStream { // Read the buffer again stream.read(buffer); - assertEquals(_workbook_size - (2 * buffer.length), - available(stream)); + assertEquals(_workbook_size - (2 * buffer.length), available(stream)); for (int j = buffer.length; j < (2 * buffer.length); j++) { - assertEquals("checking byte " + j, _workbook_data[j], - buffer[j - buffer.length]); + assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j); } assertTrue(stream.markSupported()); } @@ -236,7 +214,7 @@ public final class TestDocumentInputStream { * test simple read method */ @SuppressWarnings("ResultOfMethodCallIgnored") - @Test(expected = IOException.class) + @Test public void testReadSingleByte() throws IOException { DocumentInputStream stream = new DocumentInputStream(_workbook_n); int remaining = _workbook_size; @@ -244,12 +222,10 @@ public final class TestDocumentInputStream { // Try and read each byte in turn for (int j = 0; j < _workbook_size; j++) { int b = stream.read(); - assertTrue("checking sign of " + j, b >= 0); - assertEquals("validating byte " + j, _workbook_data[j], - (byte) b); + assertTrue(b >= 0, "checking sign of " + j); + assertEquals(_workbook_data[j], (byte) b, "validating byte " + j); remaining--; - assertEquals("checking remaining after reading byte " + j, - remaining, available(stream)); + assertEquals(remaining, available(stream), "checking remaining after reading byte " + j); } // Ensure we fell off the end @@ -257,7 +233,7 @@ public final class TestDocumentInputStream { // Check that after close we can no longer read stream.close(); - stream.read(); + assertThrows(IOException.class, stream::read); } /** @@ -268,12 +244,7 @@ public final class TestDocumentInputStream { public void testBufferRead() throws IOException { DocumentInputStream stream = new DocumentInputStream(_workbook_n); // Need to give a byte array to read - try { - stream.read(null); - fail("Should have caught NullPointerException"); - } catch (NullPointerException ignored) { - // as expected - } + assertThrows(NullPointerException.class, () -> stream.read(null)); // test reading zero length buffer assertEquals(0, stream.read(new byte[0])); @@ -284,12 +255,10 @@ public final class TestDocumentInputStream { while (available(stream) >= buffer.length) { assertEquals(_buffer_size, stream.read(buffer)); for (byte element : buffer) { - assertEquals("in main loop, byte " + offset, - _workbook_data[offset], element); + assertEquals(_workbook_data[offset], element, "in main loop, byte " + offset); offset++; } - assertEquals("offset " + offset, _workbook_size - offset, - available(stream)); + assertEquals(_workbook_size - offset, available(stream), "offset " + offset); } assertEquals(_workbook_size % _buffer_size, available(stream)); Arrays.fill(buffer, (byte) 0); @@ -297,22 +266,17 @@ public final class TestDocumentInputStream { assertEquals(_workbook_size % _buffer_size, count); for (int j = 0; j < count; j++) { - assertEquals("past main loop, byte " + offset, - _workbook_data[offset], buffer[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("checking remainder, byte " + j, 0, buffer[j]); + assertEquals(0, buffer[j], "checking remainder, byte " + j); } assertEquals(-1, stream.read(buffer)); stream.close(); - try { - stream.read(buffer); - fail("Should have caught IOException"); - } catch (IOException ignored) { - // as expected - } + + assertThrows(IOException.class, () -> stream.read(buffer)); } /** @@ -322,32 +286,12 @@ public final class TestDocumentInputStream { @Test public void testComplexBufferRead() throws IOException { DocumentInputStream stream = new DocumentInputStream(_workbook_n); - try { - stream.read(null, 0, 1); - fail("Should have caught NullPointerException"); - } catch (IllegalArgumentException ignored) { - // as expected - } + assertThrows(IllegalArgumentException.class, () -> stream.read(null, 0, 1)); // test illegal offsets and lengths - try { - stream.read(new byte[5], -4, 0); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } - try { - stream.read(new byte[5], 0, -4); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } - try { - stream.read(new byte[5], 0, 6); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } + 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)); @@ -357,48 +301,39 @@ public final class TestDocumentInputStream { while (available(stream) >= _buffer_size) { Arrays.fill(buffer, (byte) 0); - assertEquals(_buffer_size, - stream.read(buffer, offset, _buffer_size)); + assertEquals(_buffer_size, stream.read(buffer, offset, _buffer_size)); for (int j = 0; j < offset; j++) { - assertEquals("checking byte " + j, 0, buffer[j]); + assertEquals(0, buffer[j], "checking byte " + j); } for (int j = offset; j < (offset + _buffer_size); j++) { - assertEquals("checking byte " + j, _workbook_data[j], - buffer[j]); + assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); } for (int j = offset + _buffer_size; j < buffer.length; j++) { - assertEquals("checking byte " + j, 0, buffer[j]); + assertEquals(0, buffer[j], "checking byte " + j); } offset += _buffer_size; - assertEquals("offset " + offset, _workbook_size - offset, - available(stream)); + 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); + int count = stream.read(buffer, offset, _workbook_size % _buffer_size); assertEquals(_workbook_size % _buffer_size, count); for (int j = 0; j < offset; j++) { - assertEquals("checking byte " + j, 0, buffer[j]); + assertEquals(0, buffer[j], "checking byte " + j); } for (int j = offset; j < buffer.length; j++) { - assertEquals("checking byte " + j, _workbook_data[j], - buffer[j]); + assertEquals(_workbook_data[j], buffer[j], "checking byte " + j); } assertEquals(_workbook_size, offset + count); for (int j = count; j < offset; j++) { - assertEquals("byte " + j, 0, buffer[j]); + assertEquals(0, buffer[j], "byte " + j); } assertEquals(-1, stream.read(buffer, 0, 1)); stream.close(); - try { - stream.read(buffer, 0, 1); - fail("Should have caught IOException"); - } catch (IOException ignored) { - // as expected - } + + assertThrows(IOException.class, () -> stream.read(buffer, 0, 1)); } /** diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java index a31a78feab..36d31da9f7 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java @@ -18,15 +18,16 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test DocumentOutputStream functionality @@ -51,12 +52,7 @@ public final class TestDocumentOutputStream { fail("stream exhausted too early"); } - try { - dstream.write(0); - fail("Should have caught IOException"); - } - catch (IOException ignored) { - } + assertThrows(IOException.class, () -> dstream.write(0)); }; compare(l, expected); @@ -78,11 +74,7 @@ public final class TestDocumentOutputStream { fail("stream exhausted too early"); } - try { - dstream.write(new byte[]{'7','7','7','7'}); - fail("Should have caught IOException"); - } catch (IOException ignored) { - } + assertThrows(IOException.class, () -> dstream.write(new byte[]{'7','7','7','7'})); }; compare(l, expected); @@ -103,11 +95,7 @@ public final class TestDocumentOutputStream { } catch (IOException ignored) { fail("stream exhausted too early"); } - try { - dstream.write(input, 0, 1); - fail("Should have caught IOException"); - } - catch (IOException ignored) {} + assertThrows(IOException.class, () -> dstream.write(input, 0, 1)); }; compare(l, expected); diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java index 9c7b688b58..bfd5a9c004 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java @@ -17,8 +17,8 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -27,7 +27,7 @@ import java.io.IOException; import org.apache.poi.util.IOUtils; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestEmptyDocument { private static final POILogger LOG = POILogFactory.getLogger(TestEmptyDocument.class); @@ -48,12 +48,7 @@ public final class TestEmptyDocument { public void testSingleEmptyDocumentEvent() throws IOException { POIFSFileSystem fs = new POIFSFileSystem(); DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Foo", 0, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { - LOG.log(POILogger.WARN, "written"); - } - }); + dir.createDocument("Foo", 0, event -> LOG.log(POILogger.WARN, "written")); ByteArrayOutputStream out = new ByteArrayOutputStream(); fs.writeFilesystem(out); @@ -78,21 +73,14 @@ public final class TestEmptyDocument { public void testEmptyDocumentEventWithFriend() throws IOException { POIFSFileSystem fs = new POIFSFileSystem(); DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Bar", 1, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { - try { - event.getStream().write(0); - } catch (IOException exception) { - throw new RuntimeException("exception on write: " + exception); - } - } - }); - dir.createDocument("Foo", 0, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { + 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 -> {}); ByteArrayOutputStream out = new ByteArrayOutputStream(); fs.writeFilesystem(out); @@ -116,15 +104,15 @@ public final class TestEmptyDocument { fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty"); - assertEquals("Expected zero size", 0, entry.getSize()); + assertEquals(0, entry.getSize(), "Expected zero size"); byte[] actualReadbackData; actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals("Expected zero read from stream", 0, actualReadbackData.length); + assertEquals(0, actualReadbackData.length, "Expected zero read from stream"); entry = (DocumentEntry) fs.getRoot().getEntry("NotEmpty"); actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals("Expected size was wrong", testData.length, entry.getSize()); - assertArrayEquals("Expected same data read from stream", testData, actualReadbackData); + assertEquals(testData.length, entry.getSize(), "Expected size was wrong"); + assertArrayEquals(testData, actualReadbackData, "Expected same data read from stream"); fs.close(); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java index 7dca078a3e..984844a4d2 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java @@ -17,11 +17,11 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -30,7 +30,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestEntryUtils { private static final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 }; @@ -42,23 +42,23 @@ public class TestEntryUtils { 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")); @@ -66,16 +66,16 @@ public class TestEntryUtils { 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")); @@ -83,11 +83,11 @@ public class TestEntryUtils { 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())); @@ -104,32 +104,32 @@ public class TestEntryUtils { 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()); @@ -153,59 +153,59 @@ public class TestEntryUtils { 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 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 index 0b1261a7fc..1cd92b952f 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java @@ -17,13 +17,13 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -37,7 +37,7 @@ import java.util.Random; import org.apache.poi.POIDataSamples; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestFileMagic { @Test @@ -62,12 +62,7 @@ public class TestFileMagic { assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf("something".getBytes(StandardCharsets.UTF_8))); assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(new byte[0])); - try { - FileMagic.valueOf("some string"); - fail("Should catch exception here"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> FileMagic.valueOf("some string")); } @Test @@ -134,7 +129,7 @@ public class TestFileMagic { } } - @Test(expected = IOException.class) + @Test public void testMarkRequired() throws IOException { byte[] data = new byte[] { -1, -40, -1, -32, 0 }; @@ -148,7 +143,7 @@ public class TestFileMagic { try (FileInputStream str = new FileInputStream(file)) { assertFalse(str.markSupported()); - FileMagic.valueOf(str); + assertThrows(IOException.class, () -> FileMagic.valueOf(str)); } } finally { assertTrue(file.delete()); diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java index 140794bca8..dee7a17c4b 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java @@ -17,8 +17,8 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -30,8 +30,8 @@ import java.util.List; import java.util.Map; import org.apache.poi.POIDataSamples; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * Tests bugs for POIFSFileSystem @@ -42,7 +42,7 @@ public final class TestFileSystemBugs { private List openedFSs; - @After + @AfterEach public void tearDown() { if (openedFSs != null && !openedFSs.isEmpty()) { for (POIFSFileSystem fs : openedFSs) { diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java index 65d9265ab0..e511bc2609 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java @@ -18,11 +18,10 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -32,177 +31,134 @@ import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Class to test FilteringDirectoryNode functionality */ public final class TestFilteringDirectoryNode { - private POIFSFileSystem fs; - private DirectoryEntry dirA; - private DirectoryEntry dirAA; - private DirectoryEntry dirB; - private DocumentEntry eRoot; - private DocumentEntry eA; - private DocumentEntry eAA; + private POIFSFileSystem fs; + private DirectoryEntry dirA; + private DirectoryEntry dirAA; + private DirectoryEntry dirB; + private DocumentEntry eRoot; + private DocumentEntry eA; + private DocumentEntry eAA; - @Before - public 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[]{})); - } + @BeforeEach + public 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 - public void testNoFiltering() throws Exception { - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), new HashSet<>()); - assertEquals(3, d.getEntryCount()); - assertEquals(dirA.getName(), d.getEntry(dirA.getName()).getName()); + @Test + public 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(dirA.getName()).isDirectoryEntry()); + assertFalse(d.getEntry(dirA.getName()).isDocumentEntry()); - assertTrue(d.getEntry(dirB.getName()).isDirectoryEntry()); - assertFalse(d.getEntry(dirB.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()); + 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()); - try { - assertNull(i.next()); - fail("Should throw NoSuchElementException when depleted"); - } catch (NoSuchElementException ignored) { - } - } + 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 - public void testChildFiltering() throws Exception { - List excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName()); - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), excl); + @Test + public void testChildFiltering() throws Exception { + List excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName()); + FilteringDirectoryNode d1 = new FilteringDirectoryNode(fs.getRoot(), excl); - assertEquals(2, d.getEntryCount()); - assertTrue(d.hasEntry(dirA.getName())); - assertTrue(d.hasEntry(dirB.getName())); - assertFalse(d.hasEntry(eRoot.getName())); + assertEquals(2, d1.getEntryCount()); + assertTrue(d1.hasEntry(dirA.getName())); + assertTrue(d1.hasEntry(dirB.getName())); + assertFalse(d1.hasEntry(eRoot.getName())); - assertEquals(dirA, d.getEntry(dirA.getName())); - assertEquals(dirB, d.getEntry(dirB.getName())); - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } + assertEquals(dirA, d1.getEntry(dirA.getName())); + assertEquals(dirB, d1.getEntry(dirB.getName())); + assertThrows(FileNotFoundException.class, () -> d1.getEntry(eRoot.getName())); - Iterator i = d.getEntries(); - assertEquals(dirA, i.next()); - assertEquals(dirB, i.next()); - try { - assertNull(i.next()); - fail("Should throw NoSuchElementException when depleted"); - } catch (NoSuchElementException ignored) { - } + 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()); - d = new FilteringDirectoryNode(fs.getRoot(), excl); + // Filter more + excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName(), dirA.getName()); + FilteringDirectoryNode d2 = new FilteringDirectoryNode(fs.getRoot(), excl); - assertEquals(1, d.getEntryCount()); - assertFalse(d.hasEntry(dirA.getName())); - assertTrue(d.hasEntry(dirB.getName())); - assertFalse(d.hasEntry(eRoot.getName())); + 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"); - try { - d.getEntry(dirA.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } - assertEquals(dirB, d.getEntry(dirB.getName())); - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } + i = d2.getEntries(); + assertEquals(dirB, i.next()); + assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); - i = d.getEntries(); - assertEquals(dirB, i.next()); - try { - assertNull(i.next()); - fail("Should throw NoSuchElementException when depleted"); - } catch (NoSuchElementException ignored) { - } + // 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"); - // Filter everything - excl = Arrays.asList("NotThere", eRoot.getName(), dirA.getName(), dirB.getName()); - d = new FilteringDirectoryNode(fs.getRoot(), excl); + i = d3.getEntries(); + assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted"); + } - assertEquals(0, d.getEntryCount()); - assertFalse(d.hasEntry(dirA.getName())); - assertFalse(d.hasEntry(dirB.getName())); - assertFalse(d.hasEntry(eRoot.getName())); + @Test + public 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); - try { - d.getEntry(dirA.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } - try { - d.getEntry(dirB.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch (FileNotFoundException e) { - } + // Check main + assertEquals(2, d.getEntryCount()); + assertTrue(d.hasEntry(dirA.getName())); + assertTrue(d.hasEntry(dirB.getName())); + assertFalse(d.hasEntry(eRoot.getName())); - i = d.getEntries(); - try { - assertNull(i.next()); - fail("Should throw NoSuchElementException when depleted"); - } catch (NoSuchElementException ignored) { - } - } + // Check filtering down + assertTrue(d.getEntry(dirA.getName()) instanceof FilteringDirectoryNode); + assertFalse(d.getEntry(dirB.getName()) instanceof FilteringDirectoryNode); - @Test - public 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); + DirectoryEntry fdA = (DirectoryEntry) d.getEntry(dirA.getName()); + assertFalse(fdA.hasEntry(eA.getName())); + assertTrue(fdA.hasEntry(dirAA.getName())); - // Check main - assertEquals(2, d.getEntryCount()); - assertTrue(d.hasEntry(dirA.getName())); - assertTrue(d.hasEntry(dirB.getName())); - assertFalse(d.hasEntry(eRoot.getName())); + DirectoryEntry fdAA = (DirectoryEntry) fdA.getEntry(dirAA.getName()); + assertTrue(fdAA.hasEntry(eAA.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(expected = IllegalArgumentException.class) - public void testNullDirectory() { - new FilteringDirectoryNode(null, null); - } + @Test + public 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 index ef0798a4c7..d43833bb1f 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java @@ -18,7 +18,7 @@ package org.apache.poi.poifs.filesystem; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.InputStream; @@ -26,7 +26,7 @@ import java.io.InputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.OldExcelFormatException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test that POIFS complains when given older non-OLE2 @@ -44,10 +44,7 @@ public class TestNotOLE2Exception { @Test public void testRawXMLException() throws IOException { try (InputStream in = openXLSSampleStream("SampleSS.xml")) { - new POIFSFileSystem(in).close(); - fail("expected exception was not thrown"); - } catch(NotOLE2FileException e) { - // expected during successful test + 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"); } @@ -56,10 +53,7 @@ public class TestNotOLE2Exception { @Test public void testMSWriteException() throws IOException { try (InputStream in = openDOCSampleStream("MSWriteOld.wri")) { - new POIFSFileSystem(in).close(); - fail("expected exception was not thrown"); - } catch(NotOLE2FileException e) { - // expected during successful test + 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"); } @@ -68,10 +62,7 @@ public class TestNotOLE2Exception { @Test public void testBiff3Exception() throws IOException { try (InputStream in = openXLSSampleStream("testEXCEL_3.xls")) { - new POIFSFileSystem(in).close(); - fail("expected exception was not thrown"); - } catch(OldExcelFormatException e) { - // expected during successful test + 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"); } @@ -80,10 +71,7 @@ public class TestNotOLE2Exception { @Test public void testBiff4Exception() throws IOException { try (InputStream in = openXLSSampleStream("testEXCEL_4.xls")) { - new POIFSFileSystem(in).close(); - fail("expected exception was not thrown"); - } catch(OldExcelFormatException e) { - // expected during successful test + 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 index 1b154bd89d..bd727fafcb 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java @@ -17,11 +17,11 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test that POIFS complains when given an Office 2003 XML diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java index 2a235d3940..7aa4efaf7a 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java @@ -19,9 +19,9 @@ package org.apache.poi.poifs.filesystem; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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; @@ -34,7 +34,7 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestOle10Native { private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance(); diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java index 9c01ca0a52..58119d8a13 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java @@ -17,15 +17,16 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test POIFSDocumentPath functionality @@ -73,14 +74,8 @@ public final class TestPOIFSDocumentPath { // test weird variants assertEquals(0, new POIFSDocumentPath(null).length()); - try { - new POIFSDocumentPath(new String[]{"fu", ""}); - fail("should have caught IllegalArgumentException"); - } catch (IllegalArgumentException ignored) { } - try { - new POIFSDocumentPath(new String[]{"fu", null}); - fail("should have caught IllegalArgumentException"); - } catch (IllegalArgumentException ignored) { } + assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", ""})); + assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", null})); } /** @@ -129,16 +124,10 @@ public final class TestPOIFSDocumentPath { new POIFSDocumentPath(base, new String[]{"", "fu"}); // This one shouldn't be allowed - try { - new POIFSDocumentPath(base, new String[]{"fu", null}); - fail("should have caught IllegalArgumentException"); - } catch (IllegalArgumentException ignored) { } + assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{"fu", null})); // Ditto - try { - new POIFSDocumentPath(base, new String[]{null, "fu"}); - fail("should have caught IllegalArgumentException"); - } catch (IllegalArgumentException ignored) { } + assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{null, "fu"})); } } @@ -157,7 +146,7 @@ public final class TestPOIFSDocumentPath { for (int j = 0; j < paths.length; j++) { for (int k = 0; k < paths.length; k++) { - assertEquals(j + "<>" + k, paths[ j ], paths[ k ]); + assertEquals(paths[ j ], paths[ k ], j + "<>" + k); } } a2 = new POIFSDocumentPath(a1, new String[]{"foo"}); @@ -178,7 +167,7 @@ public final class TestPOIFSDocumentPath { for (int k = 0; k < builtUpPaths.length; k++) { for (int j = 0; j < fullPaths.length; j++) { if (k == j) { - assertEquals(j + "<>" + k, fullPaths[ j ], builtUpPaths[ k ]); + assertEquals(fullPaths[ j ], builtUpPaths[ k ], j + "<>" + k); } else { assertNotEquals(fullPaths[j], builtUpPaths[k]); } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java index 9860935c12..cff04d3e78 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java @@ -18,10 +18,9 @@ package org.apache.poi.poifs.filesystem; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -42,7 +41,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for the older OPOIFS-based POIFSFileSystem @@ -113,23 +112,17 @@ public final class TestPOIFSFileSystem { */ @Test public void testAlwaysClose() throws IOException { - TestIS testIS; - // Normal case - read until EOF and close - testIS = new TestIS(openSampleStream("13224.xls"), -1); - try (POIFSFileSystem ignored = new POIFSFileSystem(testIS)){ - assertTrue("input stream was not closed", testIS.isClosed()); + 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 - testIS = new TestIS(openSampleStream("13224.xls"), 10000); - try (POIFSFileSystem ignored = new POIFSFileSystem(testIS)){ - fail("ex should have been thrown"); - } catch (MyEx e) { - // expected - assertTrue("input stream was not closed", testIS.isClosed()); // but still should close - } catch (Exception e) { - fail("MyEx is expected to be thrown"); + 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"); } } @@ -173,9 +166,9 @@ public final class TestPOIFSFileSystem { public void testFATandDIFATsectors() throws Exception { try (InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")) { IndexOutOfBoundsException ex = assertThrows( - "File is corrupt and shouldn't have been opened", IndexOutOfBoundsException.class, - () -> new POIFSFileSystem(stream) + () -> new POIFSFileSystem(stream), + "File is corrupt and shouldn't have been opened" ); assertTrue(ex.getMessage().contains("Block 1148 not found")); } @@ -302,8 +295,7 @@ public final class TestPOIFSFileSystem { try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.getFile("64322.ole2"))) { int count = recurseDir(poiFS.getRoot()); - assertEquals("Expecting a fixed number of entries being found in the test-document", - 1285, count); + assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document"); } } @@ -312,8 +304,7 @@ public final class TestPOIFSFileSystem { try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.openResourceAsStream("64322.ole2"))) { int count = recurseDir(poiFS.getRoot()); - assertEquals("Expecting a fixed number of entries being found in the test-document", - 1285, count); + assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document"); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java index 92ea46c698..26f8d6b8fa 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java @@ -17,11 +17,12 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; @@ -31,451 +32,443 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for the Mini Store in the NIO POIFS */ @SuppressWarnings("CatchMayIgnoreException") public final class TestPOIFSMiniStore { - private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance(); + 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 - public 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(); + /** + * Check that for a given mini block, we can correctly figure + * out what the next one is + */ + @Test + public 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)); + // 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)); + // 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)); + // 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)); + // 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)); + // 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)); + // 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)); + // 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)); + // 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(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(175)); - assertEquals(177 , ministore.getNextBlock(176)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(177)); + 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)); + 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 ministore.getBATBlockAndIndex(256), "Should only be two SBATs"); - // 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()); + // Now ask for a free one, will need to extend the SBAT chain + assertEquals(256, ministore.getFreeBlock()); - // 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()); + 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 - // 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(); - } + fs.close(); + } - /** - * Ask for free blocks where there are some already - * to be had from the SFAT - */ - @Test - public void testGetFreeBlockWithSpare() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); + /** + * Test that we will extend the underlying chain of + * big blocks that make up the ministream as needed + */ + @Test + public void testCreateBlockIfNeeded() throws Exception { + POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); + POIFSMiniStore ministore = fs.getMiniStore(); - // Our 2nd SBAT block has spares - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); + // 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)); + } - // 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)); + // 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"); - // Ask, will get 181 - assertEquals(181, ministore.getFreeBlock()); + // 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 again, will still get 181 as not written to - assertEquals(181, ministore.getFreeBlock()); + // Ask it to get block 184 with creating, it will do + ministore.createBlockIfNeeded(184); - // Allocate it, then ask again - ministore.setNextBlock(181, POIFSConstants.END_OF_CHAIN); - assertEquals(182, ministore.getFreeBlock()); + // 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); - fs.close(); - } + // The mini block block counts now run to 191 + for (int i = 0; i <= 191; i++) { + ministore.getBlockAt(i); + } - /** - * Ask for free blocks where no free ones exist, and so the - * stream needs to be extended and another SBAT added - */ - @Test - public void testGetFreeBlockWithNoneSpare() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); + assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(192), "No block at 192"); - // We've spare ones from 181 to 255 - for(int i=181; i<256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } + // 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 our SBAT free stuff is correct - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); + // 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)); + } - // Allocate all the spare ones - for(int i=181; i<256; i++) { - ministore.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } + fs.close(); + } - // SBAT are now full, but there's only the two - assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertFalse(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - try { - assertFalse(ministore.getBATBlockAndIndex(256).getBlock().hasFreeSectors()); - fail("Should only be two SBATs"); - } catch(IndexOutOfBoundsException e) {} + @Test + public void testCreateMiniStoreFirst() throws Exception { + POIFSFileSystem fs = new POIFSFileSystem(); + POIFSMiniStore ministore = fs.getMiniStore(); + DocumentInputStream dis; + DocumentEntry entry; - // Now ask for a free one, will need to extend the SBAT chain - assertEquals(256, ministore.getFreeBlock()); + // 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) { + } - 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 + // 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)); - fs.close(); - } + // 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)); - /** - * Test that we will extend the underlying chain of - * big blocks that make up the ministream as needed - */ - @Test - public void testCreateBlockIfNeeded() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); + // Re-fetch the mini store, and add it a second time + ministore = fs.getMiniStore(); + fs.getRoot().createDocument("mini2", new ByteArrayInputStream(data)); - // 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)); - } + // 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)); - // However, the ministore data only covers blocks to 183 - for(int i=0; i<=183; i++) { - ministore.getBlockAt(i); - } - try { - ministore.getBlockAt(184); - fail("No block at 184"); - } catch(NoSuchElementException e) {} + // 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(); - // 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); + 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(); - // Ask it to get block 184 with creating, it will do - ministore.createBlockIfNeeded(184); + // Done + fs.close(); + } - // 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); + @Test + public 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); + } - // The mini block block counts now run to 191 - for(int i=0; i<=191; i++) { - ministore.getBlockAt(i); - } - try { - ministore.getBlockAt(192); - fail("No block at 192"); - } catch(NoSuchElementException e) {} + // 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)); - // 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); + // 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 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)); - } + // 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)); - fs.close(); - } + // First 2 Mini blocks will be used + assertEquals(2, ministore.getFreeBlock()); - @Test - public void testCreateMiniStoreFirst() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(); - POIFSMiniStore ministore = fs.getMiniStore(); - DocumentInputStream dis; - DocumentEntry entry; + // Add one more mini-stream, and check + fs.getRoot().createDocument("mini1", new ByteArrayInputStream(data1B)); - // 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) {} + 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)); - // Write a very small new document, will populate the ministore for us - byte[] data = new byte[8]; - for (int i=0; i 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 - public 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 - public 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 - public 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 - public 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 - try { - i.next(); - fail("Loop should have been detected but wasn't!"); - } catch(RuntimeException e) { - // Good, it was detected - } - assertTrue(i.hasNext()); - - fs.close(); - } - - /** - * Tests that we can load some streams that are - * stored in the mini stream. - */ - @Test - public 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 - public void testReplaceStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - byte[] data = new byte[512]; - for(int i=0; i 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 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 - public 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 - public 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 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 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 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 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); - try { - ministore.getBlockAt(184); - fail("Block 184 should be off the end of the list"); - } catch (NoSuchElementException e) { - } - - 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 - public 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 - byte[] data = new byte[512 * 4]; - POIFSStream stream = new POIFSStream(fs, 0); - try { - stream.updateContents(data); - fail("Loop should have been detected but wasn't!"); - } catch (IllegalStateException e) { - } - - // 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); - - data = new byte[512]; - stream = new POIFSStream(fs, 0); - try { - stream.updateContents(data); - fail("Loop should have been detected but wasn't!"); - } catch (IllegalStateException e) { - } - } - } - - /** - * Tests adding a new stream, writing and reading it. - */ - @Test - public 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()); - try { - stream.getBlockIterator(); - fail("Shouldn't be able to get an iterator before writing"); - } catch (IllegalStateException e) { - } - - // 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("Wrong value at " + i, data[i], read[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 - public 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 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); - try { - ministore.getBATBlockAndIndex(256); - fail("Should only be two SBATs, but a 3rd was found"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - // 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); - try { - fs.getBATBlockAndIndex(1040); - fail("Should only be one BAT, but a 2nd was found"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - // 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); - try { - ministore.getBATBlockAndIndex(1024); - fail("Should only be one SBAT, but a 2nd was found"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - // 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 - public 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 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 - public 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 - public 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 - public 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()); - try { - assertFalse(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - fail("Should only be one BAT"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - 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()); - try { - assertFalse(fs1.getBATBlockAndIndex(109 * 128).getBlock().hasFreeSectors()); - fail("Should only be 109 BATs"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - // 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("Had: " + free, free > 0); - - assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors()); - try { - assertFalse(fs1.getBATBlockAndIndex(110 * 128).getBlock().hasFreeSectors()); - fail("Should only be 110 BATs"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - 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()); - try { - assertFalse(fs1.getBATBlockAndIndex(236 * 128).getBlock().hasFreeSectors()); - fail("Should only be 236 BATs"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - assertBATCount(fs1, 236, 1); - - - // Ask for another, will get our 2nd XBAT - free = fs1.getFreeBlock(); - assertTrue("Had: " + free, free > 0); - - assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); - try { - assertFalse(fs1.getBATBlockAndIndex(237 * 128).getBlock().hasFreeSectors()); - fail("Should only be 237 BATs"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - - // 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()); - try { - assertFalse(fs2.getBATBlockAndIndex(237 * 128).getBlock().hasFreeSectors()); - fail("Should only be 237 BATs"); - } catch(IndexOutOfBoundsException e) { - // expected here - } - - - // All done - fs2.close(); - } - - /** - * Test that we can correctly get the list of directory - * entries, and the details on the files in them - */ - @Test - public 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 - public 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 - public 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 - public 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 - public 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 - public 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 - public 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 - public 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 - public 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 - @Ignore("Work in progress test for #60670") - public void creationAndExtensionPast2GB() throws Exception { - File big = TempFile.createTempFile("poi-test-", ".ole2"); - Assume.assumeTrue("2.5gb of free space is required on your tmp/temp " + - "partition/disk to run large file tests", - big.getFreeSpace() > 2.5*1024*1024*1024); - 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 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 + public 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 + public 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; } - assertTrue(file.delete()); - if (i % 10 == 0) System.out.print("."); - } - } + count++; + } + assertEquals(23, count); - System.out.println(); - System.out.println("NPOI took: " + (System.currentTimeMillis() - start)); + // 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()); - System.out.println(); - System.out.println(); - } + // 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()); - private static void copyAllEntries(DirectoryEntry srcDirectory, DirectoryEntry destDirectory) throws IOException { - Iterator iterator = srcDirectory.getEntries(); + // 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()); - while (iterator.hasNext()) { - Entry entry = iterator.next(); + fs.close(); + } - if (entry.isDirectoryEntry()) { - DirectoryEntry childDest = destDirectory.createDirectory(entry.getName()); - copyAllEntries((DirectoryEntry) entry, childDest); + /** + * Read a stream with several blocks in a 4096 byte block file + */ + @Test + public void testReadStream4096() throws Exception { + POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - } else { - DocumentEntry srcEntry = (DocumentEntry) entry; + // 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()); - try (InputStream inputStream = new DocumentInputStream(srcEntry)) { - destDirectory.createDocument(entry.getName(), inputStream); + // 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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") + public 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 + public 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 index f9fb199f02..aa50517cbf 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java @@ -17,9 +17,9 @@ package org.apache.poi.poifs.filesystem; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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; @@ -35,7 +35,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Verify the order of entries DirectoryProperty . diff --git a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java b/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java index caf1222359..9429961c61 100644 --- a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java +++ b/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java @@ -21,13 +21,13 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +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; @@ -52,7 +52,7 @@ public class TestVBAMacroReader { } String testMacroContents = new String(bytes, StringUtil.UTF8); - + if (! testMacroContents.startsWith("Sub ")) { throw new IllegalArgumentException("Not a macro"); } @@ -73,7 +73,7 @@ public class TestVBAMacroReader { } expectedMacroContents = Collections.unmodifiableMap(_expectedMacroContents); } - + //////////////////////////////// From Stream ///////////////////////////// @Test public void HSSFFromStream() throws Exception { @@ -83,7 +83,7 @@ public class TestVBAMacroReader { public void XSSFFromStream() throws Exception { fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); } - @Ignore("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + + @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 public void HSLFFromStream() throws Exception { @@ -101,7 +101,7 @@ public class TestVBAMacroReader { public void XWPFFromStream() throws Exception { fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); } - @Ignore("Found 0 macros") + @Disabled("Found 0 macros") @Test public void HDGFFromStream() throws Exception { fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); @@ -120,7 +120,7 @@ public class TestVBAMacroReader { public void XSSFFromFile() throws Exception { fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); } - @Ignore("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + + @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 public void HSLFFromFile() throws Exception { @@ -138,7 +138,7 @@ public class TestVBAMacroReader { public void XWPFFromFile() throws Exception { fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); } - @Ignore("Found 0 macros") + @Disabled("Found 0 macros") @Test public void HDGFFromFile() throws Exception { fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); @@ -153,7 +153,7 @@ public class TestVBAMacroReader { public void HSSFFromPOIFS() throws Exception { fromPOIFS(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); } - @Ignore("bug 59302: Found 0 macros") + @Disabled("bug 59302: Found 0 macros") @Test public void HSLFFromPOIFS() throws Exception { fromPOIFS(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); @@ -162,7 +162,7 @@ public class TestVBAMacroReader { public void HWPFFromPOIFS() throws Exception { fromPOIFS(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); } - @Ignore("Found 0 macros") + @Disabled("Found 0 macros") @Test public void HDGFFromPOIFS() throws Exception { fromPOIFS(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); @@ -191,21 +191,21 @@ public class TestVBAMacroReader { } } } - + private void assertMacroContents(POIDataSamples samples, VBAMacroReader r) throws IOException { assertNotNull(r); Map contents = r.readMacroModules(); assertNotNull(contents); - assertFalse("Found 0 macros", contents.isEmpty()); + 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"); @@ -214,7 +214,7 @@ public class TestVBAMacroReader { assertContains(content, "Attribute VB_Exposed = True"); } */ - + // Check the script one assertContains(contents, "Module1"); Module module = contents.get("Module1"); diff --git a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java index bb549f7a14..8373d8f795 100644 --- a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java +++ b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java @@ -19,10 +19,10 @@ package org.apache.poi.poifs.nio; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -35,31 +35,25 @@ import java.nio.ByteBuffer; import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for the datasource implementations */ public class TestDataSource { - private static POIDataSamples data = POIDataSamples.getPOIFSInstance(); + private static final POIDataSamples data = POIDataSamples.getPOIFSInstance(); @Test public void testFile() throws Exception { File f = data.getFile("Notes.ole2"); - FileBackedDataSource ds = new FileBackedDataSource(f); - try { + try (FileBackedDataSource ds = new FileBackedDataSource(f)) { checkDataSource(ds, false); - } finally { - ds.close(); } // try a second time - ds = new FileBackedDataSource(f); - try { + try (FileBackedDataSource ds = new FileBackedDataSource(f)) { checkDataSource(ds, false); - } finally { - ds.close(); } } @@ -69,25 +63,19 @@ public class TestDataSource { try { writeDataToFile(temp); - FileBackedDataSource ds = new FileBackedDataSource(temp, false); - try { + try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) { checkDataSource(ds, true); - } finally { - ds.close(); } // try a second time - ds = new FileBackedDataSource(temp, false); - try { + try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) { checkDataSource(ds, true); - } finally { - ds.close(); } writeDataToFile(temp); } finally { assertTrue(temp.exists()); - assertTrue("Could not delete file " + temp, temp.delete()); + assertTrue(temp.delete(), "Could not delete file " + temp); } } @@ -98,25 +86,21 @@ public class TestDataSource { try { writeDataToFile(temp); - FileBackedDataSource ds = new FileBackedDataSource(temp, true); - try { + ; + try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) { ByteBuffer buf = ds.read(0, 10); assertNotNull(buf); buf = ds.read(8, 0x400); assertNotNull(buf); - } finally { - ds.close(); } // try a second time - ds = new FileBackedDataSource(temp, true); - try { + ; + try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) { ByteBuffer buf = ds.read(0, 10); assertNotNull(buf); buf = ds.read(8, 0x400); assertNotNull(buf); - } finally { - ds.close(); } writeDataToFile(temp); @@ -140,7 +124,7 @@ public class TestDataSource { // rewriting changes the size if (writeable) { - assertTrue("Had: " + ds.size(), ds.size() == 8192 || ds.size() == 8198); + assertTrue(ds.size() == 8192 || ds.size() == 8198, "Had: " + ds.size()); } else { assertEquals(8192, ds.size()); } @@ -174,21 +158,16 @@ public class TestDataSource { // Can go to the end, but not past it bs = ds.read(8, 8190); - assertEquals(0, bs.position()); // TODO How best to warn of a short read? + // TODO How best to warn of a short read? + assertEquals(0, bs.position()); // Can't go off the end - try { - ds.read(4, 8192); - if (!writeable) { - fail("Shouldn't be able to read off the end of the file"); - } - } catch (IndexOutOfBoundsException e) { - // expected here - } + assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, ds.size()), + "Shouldn't be able to read off the end of the file"); } @Test - public void testByteArray() throws Exception { + public void testByteArray() { byte[] data = new byte[256]; byte b; for (int i = 0; i < data.length; i++) { @@ -226,20 +205,10 @@ public class TestDataSource { bs = ds.read(4, 254); assertEquals(-2, bs.get()); assertEquals(-1, bs.get()); - try { - bs.get(); - fail("Shouldn't be able to read off the end"); - } catch (BufferUnderflowException e) { - // expected here - } + assertThrows(BufferUnderflowException.class, bs::get, "Shouldn't be able to read off the end"); // Past the end - try { - ds.read(4, 256); - fail("Shouldn't be able to read off the end"); - } catch (IndexOutOfBoundsException e) { - // expected here - } + assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, 256), "Shouldn't be able to read off the end"); // Overwrite diff --git a/src/testcases/org/apache/poi/poifs/property/AllPOIFSPropertyTests.java b/src/testcases/org/apache/poi/poifs/property/AllPOIFSPropertyTests.java deleted file mode 100644 index 8df7314ee4..0000000000 --- a/src/testcases/org/apache/poi/poifs/property/AllPOIFSPropertyTests.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.poifs.property; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Tests for org.apache.poi.poifs.property
- */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDirectoryProperty.class, - TestDocumentProperty.class, - TestPropertyFactory.class, - TestPropertyTable.class, - TestRootProperty.class -}) -public final class AllPOIFSPropertyTests { -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java index 0a11d83a57..f43d32d136 100644 --- a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java +++ b/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java @@ -17,10 +17,10 @@ package org.apache.poi.poifs.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -31,7 +31,7 @@ import java.util.List; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.util.LocaleUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test DirectoryProperty functionality @@ -154,7 +154,7 @@ public final class TestDirectoryProperty { } private void createBasicDirectoryProperty() { - String name = "MyDirectory"; + final String name = "MyDirectory"; _property = new DirectoryProperty(name); _testblock = new byte[ 128 ]; @@ -164,7 +164,7 @@ public final class TestDirectoryProperty { { _testblock[ index ] = ( byte ) 0; } - int limit = Math.min(31, name.length()); + int limit = name.length(); _testblock[ index++ ] = ( byte ) (2 * (limit + 1)); _testblock[ index++ ] = ( byte ) 0; @@ -195,8 +195,7 @@ public final class TestDirectoryProperty { assertEquals(_testblock.length, output.length); for (int j = 0; j < _testblock.length; j++) { - assertEquals("mismatch at offset " + j, _testblock[ j ], - output[ j ]); + assertEquals(_testblock[ j ], output[ j ], "mismatch at offset " + j); } } @@ -205,26 +204,8 @@ public final class TestDirectoryProperty { createBasicDirectoryProperty(); _property.addChild(new LocalProperty(1)); _property.addChild(new LocalProperty(2)); - try - { - _property.addChild(new LocalProperty(1)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } - try - { - _property.addChild(new LocalProperty(2)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } + assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1))); + assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(2))); _property.addChild(new LocalProperty(3)); } @@ -234,16 +215,7 @@ public final class TestDirectoryProperty { Property p1 = new LocalProperty(1); _property.addChild(p1); - try - { - _property.addChild(new LocalProperty(1)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } + assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1))); assertTrue(_property.deleteChild(p1)); assertFalse(_property.deleteChild(p1)); _property.addChild(new LocalProperty(1)); @@ -292,7 +264,7 @@ public final class TestDirectoryProperty { assertEquals(128, output.length); for (int j = 0; j < 128; j++) { - assertEquals("mismatch at offset " + j, expected[j], output[j]); + assertEquals(expected[j], output[j], "mismatch at offset " + j); } assertEquals(index, property.getIndex()); assertEquals(name, property.getName()); diff --git a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java index 2ad3a7714a..ed10478d7b 100644 --- a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java +++ b/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java @@ -17,9 +17,9 @@ package org.apache.poi.poifs.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class to test DocumentProperty functionality @@ -88,10 +88,8 @@ public final class TestDocumentProperty { byte[] output = stream.toByteArray(); assertEquals(128, output.length); - for (int j = 0; j < 128; j++) - { - assertEquals("mismatch at offset " + j, expected[ j ], - output[ j ]); + for (int j = 0; j < 128; j++) { + assertEquals(expected[ j ], output[ j ], "mismatch at offset " + j); } assertEquals(index, property.getIndex()); assertEquals(name, property.getName()); @@ -156,8 +154,7 @@ public final class TestDocumentProperty { assertEquals(testblock.length, output.length); for (int j = 0; j < testblock.length; j++) { - assertEquals("mismatch at offset " + j, testblock[ j ], - output[ 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 index 27387ddf40..4c9f72817a 100644 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java +++ b/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java @@ -17,10 +17,10 @@ package org.apache.poi.poifs.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ import java.util.Arrays; import java.util.List; import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test PropertyFactory functionality @@ -145,21 +145,19 @@ public final class TestPropertyFactory { for (int j = 0; j < 64; j++) { if (isNull[j]) { - assertNull("Checking property " + j, properties.get(j)); + assertNull(properties.get(j), "Checking property " + j); } else { - assertNotNull("Checking property " + j, properties.get(j)); + assertNotNull(properties.get(j), "Checking property " + j); if (isRoot[j]) { - assertTrue("Checking property " + j, properties.get(j) instanceof RootProperty); + assertTrue(properties.get(j) instanceof RootProperty, "Checking property " + j); } if (isDirectory[j]) { - assertTrue("Checking property " + j, - properties.get(j) instanceof DirectoryProperty); + assertTrue(properties.get(j) instanceof DirectoryProperty, "Checking property " + j); } if (isDocument[j]) { - assertTrue("Checking property " + j, - properties.get(j) instanceof DocumentProperty); + assertTrue(properties.get(j) instanceof DocumentProperty, "Checking property " + j); } - assertEquals("Checking property " + j, names[j], properties.get(j).getName()); + 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 index dd9c507f0d..f8dc48df45 100644 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java +++ b/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java @@ -17,10 +17,10 @@ package org.apache.poi.poifs.property; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -37,7 +37,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class to test PropertyTable functionality @@ -180,7 +180,7 @@ public final class TestPropertyTable { } } - + // get property table from the document PropertyTable table = new PropertyTable(header_block, data_blocks); @@ -192,8 +192,8 @@ public final class TestPropertyTable { lastChild = p; ++count; } - - assertNotNull("no children found", lastChild); + + assertNotNull(lastChild, "no children found"); assertEquals(1, count); assertTrue(lastChild.isDirectory()); count = 0; diff --git a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java b/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java index 9bbb612f3d..a2e992ed11 100644 --- a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java +++ b/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java @@ -17,8 +17,8 @@ package org.apache.poi.poifs.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Class to test RootProperty functionality @@ -53,7 +53,7 @@ public final class TestRootProperty { _testblock[index] = (byte) 0; } String name = "Root Entry"; - int limit = Math.min(31, name.length()); + int limit = name.length(); _testblock[index++] = (byte) (2 * (limit + 1)); _testblock[index++] = (byte) 0; @@ -87,7 +87,7 @@ public final class TestRootProperty { assertEquals(_testblock.length, output.length); for (int j = 0; j < _testblock.length; j++) { - assertEquals("mismatch at offset " + j, _testblock[j], output[j]); + assertEquals(_testblock[j], output[j], "mismatch at offset " + j); } } @@ -96,7 +96,7 @@ public final class TestRootProperty { for (int j = 0; j < 10; j++) { createBasicRootProperty(); _property.setSize(j); - assertEquals("trying block count of " + j, j * 64, _property.getSize()); + assertEquals(j * 64, _property.getSize(), "trying block count of " + j); } } @@ -126,7 +126,7 @@ public final class TestRootProperty { assertEquals(128, output.length); for (int j = 0; j < 128; j++) { - assertEquals("mismatch at offset " + j, expected[j], output[j]); + assertEquals(expected[j], output[j], "mismatch at offset " + j); } assertEquals(index, property.getIndex()); assertEquals(name, property.getName()); diff --git a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java b/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java deleted file mode 100644 index 7b29d1b09e..0000000000 --- a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.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.poifs.storage; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Tests for org.apache.poi.poifs.storage - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBATBlock.class, - TestHeaderBlockReading.class -}) -public class AllPOIFSStorageTests { -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java index 10689b2e21..dac1ae1108 100644 --- a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java +++ b/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java @@ -17,9 +17,9 @@ package org.apache.poi.poifs.storage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -27,7 +27,7 @@ import java.util.List; import org.apache.poi.poifs.common.POIFSBigBlockSize; import org.apache.poi.poifs.common.POIFSConstants; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to test BATBlock functionality diff --git a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java b/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java index 3234676d17..40cb3bec52 100644 --- a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java +++ b/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java @@ -17,14 +17,14 @@ package org.apache.poi.poifs.storage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test HeaderBlockReader functionality @@ -58,24 +58,13 @@ public final class TestHeaderBlockReading { // verify we can't read a short block byte[] shortblock = Arrays.copyOf(content, 511); - try { - new HeaderBlock(new ByteArrayInputStream(shortblock)); - fail("Should have caught IOException reading a short block"); - } catch (IOException ignored) { - - // as expected - } + 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); - try { - new HeaderBlock(new ByteArrayInputStream(content)); - fail("Should have caught IOException corrupting byte " + index); - } catch (IOException ignored) { - - // as expected - } + 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 index 0d82c2ad3e..1fd8125749 100644 --- a/src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java +++ b/src/testcases/org/apache/poi/sl/draw/geom/TestFormulaParser.java @@ -18,9 +18,9 @@ */ package org.apache.poi.sl.draw.geom; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Date: 10/24/11 diff --git a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java b/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java index fe57570c5d..f7f623bb67 100644 --- a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java +++ b/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java @@ -18,17 +18,17 @@ */ package org.apache.poi.sl.draw.geom; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestPresetGeometries { @Test @@ -50,7 +50,7 @@ public class TestPresetGeometries { assertSame(shapes, PresetGeometries.getInstance()); } - @Ignore("problem solved? Turn back on if this debugging is still in process.") + @Disabled("problem solved? Turn back on if this debugging is still in process.") @Test public void testCheckXMLParser() throws Exception{ // Gump reports a strange error because of an unavailable XML Parser, let's try to find out where diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java index 6158c9de63..500f4c922f 100644 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java +++ b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.sl.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +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; @@ -34,7 +34,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public abstract class BaseTestSlideShow< S extends Shape, @@ -44,7 +44,7 @@ public abstract class BaseTestSlideShow< public abstract SlideShow createSlideShow(); - public abstract SlideShow reopen(SlideShow show); + public abstract SlideShow reopen(SlideShow show) throws IOException; @Test public void addPicture_File() throws IOException { diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java index 345bb7906e..090aeb0aa8 100644 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java +++ b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java @@ -17,9 +17,9 @@ package org.apache.poi.sl.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +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; @@ -54,23 +54,21 @@ public abstract class BaseTestSlideShowFactory { @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; - // from POIFS if (file.endsWith(".ppt")) { - POIFSFileSystem poifs = new POIFSFileSystem(fromFile(file)); - ss = SlideShowFactory.create(poifs); - assertNotNull(ss); - poifs.close(); + // from POIFS + try (POIFSFileSystem poifs = new POIFSFileSystem(fromFile(file))) { + ss = SlideShowFactory.create(poifs); + assertNotNull(ss); + } assertCloseDoesNotModifyFile(file, ss); - } - // from OPCPackage - else if (file.endsWith(".pptx")) { - // not implemented + } else { + // from OPCPackage ... not implemented throw new UnsupportedOperationException("Test not implemented"); } - else { - fail("Unexpected file extension: " + file); - } } @SuppressWarnings("resource") @@ -91,21 +89,19 @@ public abstract class BaseTestSlideShowFactory { @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 - if (protectedFile.endsWith(".ppt") || protectedFile.endsWith(".pptx")) { - POIFSFileSystem poifs = new POIFSFileSystem(fromFile(protectedFile)); + try (POIFSFileSystem poifs = new POIFSFileSystem(fromFile(protectedFile))) { ss = SlideShowFactory.create(poifs.getRoot(), password); assertNotNull(ss); - poifs.close(); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - else { - fail("Unrecognized file extension: " + protectedFile); } + assertCloseDoesNotModifyFile(protectedFile, ss); } @SuppressWarnings("SameParameterValue") @@ -169,8 +165,7 @@ public abstract class BaseTestSlideShowFactory { final byte[] after = readFile(filename); try { - assertArrayEquals(filename + " sample file was modified as a result of closing the slideshow", - before, after); + 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 diff --git a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java b/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java index c1c3a45306..7a2003fc74 100644 --- a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java +++ b/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java @@ -17,9 +17,9 @@ package org.apache.poi.ss; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Check that all enum values are properly set diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java index fa24171b9e..f87d42a22a 100644 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java +++ b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java @@ -16,9 +16,9 @@ ==================================================================== */ package org.apache.poi.ss.format; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -38,23 +38,23 @@ 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.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestCellFormat { private static TimeZone userTimeZone; - @BeforeClass + @BeforeAll public static void setTimeZone() { userTimeZone = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); LocaleUtil.setUserLocale(Locale.US); } - @AfterClass + @AfterAll public static void resetTimeZone() { LocaleUtil.setUserTimeZone(userTimeZone); LocaleUtil.setUserLocale(Locale.ROOT); @@ -1024,6 +1024,6 @@ public class TestCellFormat { 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(Assert::assertNotNull); + .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 index bda95024f8..87ea43ac15 100644 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java +++ b/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java @@ -16,10 +16,10 @@ ==================================================================== */ package org.apache.poi.ss.format; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCellFormatCondition { @Test diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java b/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java index 30ee2b9f67..51290e6e79 100644 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java +++ b/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java @@ -16,20 +16,20 @@ ==================================================================== */ package org.apache.poi.ss.format; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.awt.Color; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCellFormatResult { - @Test(expected = IllegalArgumentException.class) + @Test public void testNullTextRaisesException() { final boolean applies = true; final String text = null; final Color textColor = Color.BLACK; - final CellFormatResult result = new CellFormatResult(applies, text, textColor); - fail("Cannot initialize CellFormatResult with null text parameter"); + 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/AllSSFormulaTests.java b/src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.java deleted file mode 100644 index 14427df5d4..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.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; - -import org.apache.poi.ss.formula.eval.forked.BaseTestForkedEvaluator; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for org.apache.poi.ss.formula - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCellCacheEntry.class, - TestEvaluationCache.class, - TestWorkbookEvaluator.class, - BaseTestForkedEvaluator.class -}) -public class AllSSFormulaTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java b/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java index d71d955bbc..5472a92591 100644 --- a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java +++ b/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java @@ -16,10 +16,10 @@ ==================================================================== */ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -37,7 +37,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test setting / evaluating of Analysis Toolpack and user-defined functions @@ -96,42 +96,38 @@ public abstract class BaseTestExternalFunctions { @Test public void testExternalFunctions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sh = wb.createSheet(); + 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 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\")"); - try { - evaluator.evaluate(cell2); - fail("Expected NotImplementedFunctionException/NotImplementedException"); - } catch (final NotImplementedException e) { + 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()); } - - 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()); - - wb.close(); } /** diff --git a/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java b/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java index 9cb755cf27..087249022a 100644 --- a/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java +++ b/src/testcases/org/apache/poi/ss/formula/BaseTestMissingWorkbook.java @@ -19,11 +19,11 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -35,9 +35,9 @@ 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.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class BaseTestMissingWorkbook { protected Workbook mainWorkbook; @@ -58,7 +58,7 @@ public class BaseTestMissingWorkbook { this.SOURCE_WORKBOOK_FILENAME = SOURCE_WORKBOOK_FILENAME; } - @Before + @BeforeEach public void setUp() throws Exception { mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); @@ -67,7 +67,7 @@ public class BaseTestMissingWorkbook { assertNotNull(sourceWorkbook); } - @After + @AfterEach public void tearDown() throws Exception { if(mainWorkbook != null) { mainWorkbook.close(); @@ -87,12 +87,9 @@ public class BaseTestMissingWorkbook { Cell lA1Cell = lARow.getCell(0); assertEquals(CellType.FORMULA, lA1Cell.getCellType()); - try { - evaluator.evaluateFormulaCell(lA1Cell); - fail("Missing external workbook reference exception expected!"); - } catch(RuntimeException re) { - assertTrue("Unexpected exception: " + re, re.getMessage().contains(SOURCE_DUMMY_WORKBOOK_FILENAME)); - } + RuntimeException re = assertThrows(RuntimeException.class, () -> evaluator.evaluateFormulaCell(lA1Cell), + "Missing external workbook reference exception expected!"); + assertTrue(re.getMessage().contains(SOURCE_DUMMY_WORKBOOK_FILENAME)); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java b/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java index 43dd236d38..79897e6115 100644 --- a/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java +++ b/src/testcases/org/apache/poi/ss/formula/SheetRangeAndWorkbookIndexFormatterTest.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; public class SheetRangeAndWorkbookIndexFormatterTest { @Test diff --git a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java b/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java index f382b92d3f..4ac48ed808 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java +++ b/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java @@ -17,11 +17,11 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests {@link org.apache.poi.ss.formula.CellCacheEntry}. diff --git a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java b/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java index b022074274..80b6368d74 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java +++ b/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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; @@ -52,7 +52,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests {@link org.apache.poi.ss.formula.EvaluationCache}. Makes sure that where possible (previously calculated) cached @@ -219,11 +219,10 @@ public class TestEvaluationCache { private final HSSFSheet _sheet; private final WorkbookEvaluator _evaluator; - private final HSSFWorkbook _wb; private final EvalListener _evalListener; public MySheet() { - _wb = new HSSFWorkbook(); + HSSFWorkbook _wb = new HSSFWorkbook(); _evalListener = new EvalListener(_wb); _evaluator = WorkbookEvaluatorTestHelper.createEvaluator(_wb, _evalListener); _sheet = _wb.createSheet("Sheet1"); @@ -621,7 +620,7 @@ public class TestEvaluationCache { cv = fe.evaluate(cellA1); // looks like left-over cached result from before change to B1 - assertNotEquals("Identified bug 46053", 2.2, cv.getNumberValue()); + assertNotEquals(2.2, cv.getNumberValue(), "Identified bug 46053"); assertEquals(2.6, cv.getNumberValue(), 0.0); } @@ -666,7 +665,7 @@ public class TestEvaluationCache { private static void confirmLog(MySheet ms, String[] expectedLog) { String[] actualLog = ms.getAndClearLog(); - assertArrayEquals("Log entry mismatch", expectedLog, actualLog); + assertArrayEquals(expectedLog, actualLog, "Log entry mismatch"); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java b/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java index f4ceee0bcc..299fbf2058 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java +++ b/src/testcases/org/apache/poi/ss/formula/TestFormulaShifter.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -28,8 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link FormulaShifter}. @@ -121,7 +120,7 @@ public final class TestFormulaShifter { confirmAreaColumnShift(aptg, 18, 22, 5, 10, 25); // simple expansion at bottom } - + @Test public void testCopyAreasSourceRowsRelRel() { @@ -131,7 +130,7 @@ public final class TestFormulaShifter { confirmAreaRowCopy(aptg, 0, 30, 20, 30, 40, true); confirmAreaRowCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef } - + @Test public void testCopyAreasSourceRowsRelAbs() { @@ -142,7 +141,7 @@ public final class TestFormulaShifter { confirmAreaRowCopy(aptg, 0, 30, 20, 20, 30, true); confirmAreaRowCopy(aptg, 15, 25, -15, -1, -1, true); //DeletedRef } - + @Test public void testCopyAreasSourceRowsAbsRel() { // aptg is part of a formula in a cell that was just copied to another row @@ -158,7 +157,7 @@ public final class TestFormulaShifter { 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 public void testCopyAreasSourceRowsAbsAbs() { // aptg is part of a formula in a cell that was just copied to another row @@ -166,7 +165,7 @@ public final class TestFormulaShifter { // 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); @@ -227,9 +226,9 @@ public final class TestFormulaShifter { 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 @@ -278,7 +277,8 @@ public final class TestFormulaShifter { FormulaShifter fs = FormulaShifter.createForRowShift(0, "", firstRowMoved, lastRowMoved, numberRowsMoved, SpreadsheetVersion.EXCEL2007); boolean expectedChanged = aptg.getFirstRow() != expectedAreaFirstRow || aptg.getLastRow() != expectedAreaLastRow; - AreaPtg copyPtg = (AreaPtg) aptg.copy(); // clone so we can re-use aptg in calling method + // 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) { @@ -286,7 +286,8 @@ public final class TestFormulaShifter { return; } assertEquals(expectedChanged, actualChanged); - assertEquals(copyPtg, ptgs[0]); // expected to change in place (although this is not a strict requirement) + // expected to change in place (although this is not a strict requirement) + assertEquals(copyPtg, ptgs[0]); assertEquals(expectedAreaFirstRow, copyPtg.getFirstRow()); assertEquals(expectedAreaLastRow, copyPtg.getLastRow()); @@ -300,7 +301,8 @@ public final class TestFormulaShifter { FormulaShifter fs = FormulaShifter.createForColumnShift(0, "", firstColumnMoved, lastColumnMoved, numberColumnsMoved, SpreadsheetVersion.EXCEL2007); boolean expectedChanged = aptg.getFirstColumn() != expectedAreaFirstColumn || aptg.getLastColumn() != expectedAreaLastColumn; - AreaPtg copyPtg = (AreaPtg) aptg.copy(); // clone so we can re-use aptg in calling method + // 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) { @@ -308,59 +310,61 @@ public final class TestFormulaShifter { return; } assertEquals(expectedChanged, actualChanged); - assertEquals(copyPtg, ptgs[0]); // expected to change in place (although this is not a strict requirement) + // 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) { - - final AreaPtg copyPtg = (AreaPtg) aptg.copy(); // clone so we can re-use aptg in calling method + // 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("Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0], - AreaErrPtg.class, ptgs[0].getClass()); + assertEquals(AreaErrPtg.class, ptgs[0].getClass(), "Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0]); return; } - - assertEquals("Should this AreaPtg change due to row copy?", expectedChanged, actualChanged); - assertEquals("AreaPtgs should be modified in-place when a row containing the AreaPtg is copied", copyPtg, ptgs[0]); // expected to change in place (although this is not a strict requirement) - assertEquals("AreaPtg first row", expectedFirstRow, copyPtg.getFirstRow()); - assertEquals("AreaPtg last row", expectedLastRow, copyPtg.getLastRow()); + + 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) { - - final AreaPtg copyPtg = (AreaPtg) aptg.copy(); // clone so we can re-use aptg in calling method + // 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("Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0], - AreaErrPtg.class, ptgs[0].getClass()); + assertEquals(AreaErrPtg.class, ptgs[0].getClass(), + "Reference should have shifted off worksheet, producing #REF! error: " + ptgs[0]); return; } - assertEquals("Should this AreaPtg change due to column copy?", expectedChanged, actualChanged); - assertEquals("AreaPtgs should be modified in-place when a column containing the AreaPtg is copied", copyPtg, ptgs[0]); // expected to change in place (although this is not a strict requirement) - assertEquals("AreaPtg first column", expectedFirstColumn, copyPtg.getFirstColumn()); - assertEquals("AreaPtg last column", expectedLastColumn, copyPtg.getLastColumn()); + 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); } @@ -368,7 +372,7 @@ public final class TestFormulaShifter { 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); } @@ -379,33 +383,33 @@ public final class TestFormulaShifter { @Test public void testShiftSheet() { - // 4 sheets, move a sheet from pos 2 to pos 0, i.e. current 0 becomes 1, current 1 becomes pos 2 + // 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("formula previously pointing to sheet 0 should now point to sheet 1", - 1, ((Ref3DPtg)ptgs[0]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 1 should now point to sheet 2", - 2, ((Ref3DPtg)ptgs[1]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 2 should now point to sheet 0", - 0, ((Ref3DPtg)ptgs[2]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 3 should be unchanged", - 3, ((Ref3DPtg)ptgs[3]).getExternSheetIndex()); + + 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 public void testShiftSheet2() { - // 4 sheets, move a sheet from pos 1 to pos 2, i.e. current 2 becomes 1, current 1 becomes pos 2 + // 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), @@ -414,34 +418,25 @@ public final class TestFormulaShifter { }; shifter.adjustFormula(ptgs, -1); - - assertEquals("formula previously pointing to sheet 0 should be unchanged", - 0, ((Ref3DPtg)ptgs[0]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 1 should now point to sheet 2", - 2, ((Ref3DPtg)ptgs[1]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 2 should now point to sheet 1", - 1, ((Ref3DPtg)ptgs[2]).getExternSheetIndex()); - assertEquals("formula previously pointing to sheet 3 should be unchanged", - 3, ((Ref3DPtg)ptgs[3]).getExternSheetIndex()); + + 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 public void testInvalidArgument() { - try { - FormulaShifter.createForRowShift(1, "name", 1, 2, 0, SpreadsheetVersion.EXCEL97); - fail("Should catch exception here"); - } catch (IllegalArgumentException e) { - // expected here - } - - try { - FormulaShifter.createForRowShift(1, "name", 2, 1, 2, SpreadsheetVersion.EXCEL97); - fail("Should catch exception here"); - } catch (IllegalArgumentException e) { - // expected here - } + 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 public void testConstructor() { assertNotNull(FormulaShifter.createForRowShift(1, "name", 1, 2, 2, SpreadsheetVersion.EXCEL97)); diff --git a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java b/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java index 7faedd8c03..915510bd4d 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java +++ b/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java @@ -19,9 +19,9 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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; @@ -36,13 +36,13 @@ 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.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +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; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodOrderer.MethodName.class) public class TestFunctionRegistry { HSSFWorkbook wb; @@ -50,7 +50,7 @@ public class TestFunctionRegistry { HSSFRow row; HSSFFormulaEvaluator fe; - @Before + @BeforeEach public void setup() { wb = new HSSFWorkbook(); sheet = wb.createSheet("Sheet1"); @@ -58,7 +58,7 @@ public class TestFunctionRegistry { fe = new HSSFFormulaEvaluator(wb); } - @After + @AfterEach public void teardown() throws IOException { wb.close(); wb = null; @@ -67,11 +67,11 @@ public class TestFunctionRegistry { fe = null; } - @Test(expected = NotImplementedException.class) + @Test public void testRegisterInRuntimeA() { HSSFCell cellA = row.createCell(0); cellA.setCellFormula("FISHER(A5)"); - fe.evaluate(cellA); + assertThrows(NotImplementedException.class, () -> fe.evaluate(cellA)); } @Test @@ -83,11 +83,11 @@ public class TestFunctionRegistry { assertEquals(ErrorEval.NA.getErrorCode(), cv.getErrorValue()); } - @Test(expected = NotImplementedException.class) + @Test public void testRegisterInRuntimeC() { HSSFCell cellB = row.createCell(1); cellB.setCellFormula("CUBEMEMBERPROPERTY(A5)"); - fe.evaluate(cellB); + assertThrows(NotImplementedException.class, () -> fe.evaluate(cellB)); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java b/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java index bc89b8dc8a..1f06565fc3 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java +++ b/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java @@ -19,13 +19,13 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +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.Test; +import org.junit.jupiter.api.Test; public class TestPlainCellCache { diff --git a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java b/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java index 76a4fc7ac2..22b9224a0a 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java +++ b/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java @@ -17,37 +17,38 @@ package org.apache.poi.ss.formula; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link SheetNameFormatter} - * + * * @author Josh Micich */ public final class TestSheetNameFormatter { /** - * Tests main public method 'format' + * Tests main public method 'format' */ @Test public 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("A12220", "'A12220'"); confirmFormat("TAXRETURN19980415", "TAXRETURN19980415"); confirmFormat(null, "#REF"); @@ -130,19 +131,8 @@ public final class TestSheetNameFormatter { } }; - try { - SheetNameFormatter.appendFormat(mock, null, null); - fail("Should catch exception here"); - } catch (RuntimeException e) { - // expected here - } - - try { - SheetNameFormatter.appendFormat(mock, null); - fail("Should catch exception here"); - } catch (RuntimeException e) { - // expected here - } + assertThrows(RuntimeException.class, () -> SheetNameFormatter.appendFormat(mock, null, null)); + assertThrows(RuntimeException.class, () -> SheetNameFormatter.appendFormat(mock, null)); } @Test @@ -151,22 +141,22 @@ public final class TestSheetNameFormatter { 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 public void testLooksLikePlainCellReference() { - + confirmCellNameMatch("A1", true); confirmCellNameMatch("a111", true); confirmCellNameMatch("AA", false); @@ -176,13 +166,13 @@ public final class TestSheetNameFormatter { 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). diff --git a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java index bf89fca10c..05cebd4cc2 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java +++ b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java @@ -17,11 +17,13 @@ package org.apache.poi.ss.formula; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -47,8 +49,8 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests {@link WorkbookEvaluator}. @@ -194,12 +196,9 @@ public class TestWorkbookEvaluator { HSSFCell cell = row.createCell(0); cell.setCellFormula("1+IF(1,,)"); HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = null; - try { - cv = fe.evaluate(cell); - } catch (RuntimeException e) { - fail("Missing arg result not being handled correctly."); - } + 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); @@ -260,7 +259,7 @@ public class TestWorkbookEvaluator { public void testNamesInFormulas() throws IOException { Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("Sheet1"); - + Name name1 = wb.createName(); name1.setNameName("aConstant"); name1.setRefersToFormula("3.14"); @@ -272,27 +271,27 @@ public class TestWorkbookEvaluator { 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)"); @@ -307,10 +306,10 @@ public class TestWorkbookEvaluator { 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 public void testIgnoreMissingWorkbooks() { // TODO: update this test for meaningful functional behavior @@ -336,9 +335,9 @@ public class TestWorkbookEvaluator { 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"); @@ -347,7 +346,7 @@ public class TestWorkbookEvaluator { Cell B1 = row.createCell(1); Cell C1 = row.createCell(2); Cell D1 = row.createCell(3); - + switch (a1CellType) { case NUMERIC: A1.setCellValue(1.0); @@ -376,38 +375,34 @@ public class TestWorkbookEvaluator { B1.setCellValue(2.0); C1.setCellValue(3.0); D1.setCellFormula(formula); - + return wb; } - + private void testIFEqualsFormulaEvaluation_teardown(Workbook wb) { - try { - wb.close(); - } catch (final IOException e) { - fail("Unable to close workbook"); - } + 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); @@ -416,7 +411,7 @@ public class TestWorkbookEvaluator { testIFEqualsFormulaEvaluation_evaluateAll(formula, cellType, expectedFormula, expectedValue); testIFEqualsFormulaEvaluation_evaluateAllFormulaCells(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_NumericLiteral() { final String formula = "IF(A1=1, 2, 3)"; @@ -425,7 +420,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_Numeric() { final String formula = "IF(A1=1, B1, C1)"; @@ -434,7 +429,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_NumericCoerceToString() { final String formula = "IF(A1&\"\"=\"1\", B1, C1)"; @@ -443,7 +438,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_String() { final String formula = "IF(A1=1, B1, C1)"; @@ -452,7 +447,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 3.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_StringCompareToString() { final String formula = "IF(A1=\"1\", B1, C1)"; @@ -461,7 +456,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_StringCoerceToNumeric() { final String formula = "IF(A1+0=1, B1, C1)"; @@ -470,8 +465,8 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - - @Ignore("Bug 58591: this test currently fails") + + @Disabled("Bug 58591: this test currently fails") @Test public void testIFEqualsFormulaEvaluation_Boolean() { final String formula = "IF(A1=1, B1, C1)"; @@ -480,8 +475,8 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - - @Ignore("Bug 58591: this test currently fails") + + @Disabled("Bug 58591: this test currently fails") @Test public void testIFEqualsFormulaEvaluation_BooleanSimple() { final String formula = "3-(A1=1)"; @@ -490,7 +485,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_Formula() { final String formula = "IF(A1=1, B1, C1)"; @@ -499,7 +494,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_Blank() { final String formula = "IF(A1=1, B1, C1)"; @@ -508,7 +503,7 @@ public class TestWorkbookEvaluator { final double expectedValue = 3.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - + @Test public void testIFEqualsFormulaEvaluation_BlankCompareToZero() { final String formula = "IF(A1=0, B1, C1)"; @@ -517,8 +512,8 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - - @Ignore("Bug 58591: this test currently fails") + + @Disabled("Bug 58591: this test currently fails") @Test public void testIFEqualsFormulaEvaluation_BlankInverted() { final String formula = "IF(NOT(A1)=1, B1, C1)"; @@ -527,8 +522,8 @@ public class TestWorkbookEvaluator { final double expectedValue = 2.0; testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); } - - @Ignore("Bug 58591: this test currently fails") + + @Disabled("Bug 58591: this test currently fails") @Test public void testIFEqualsFormulaEvaluation_BlankInvertedSimple() { final String formula = "3-(NOT(A1)=1)"; @@ -537,81 +532,77 @@ public class TestWorkbookEvaluator { 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 - assertSame(D1, result); // returns the same cell that was provided as an argument so that calls can be chained. - try { - D1.getCellFormula(); - fail("cell formula should be overwritten with formula result"); - } catch (final IllegalStateException expected) { - // expected here - } + // 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); } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java b/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java deleted file mode 100644 index 95f5ea09ed..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.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.ss.formula.atp; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -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.Test; - -public class TestDateParser { - @Test - public void testFailWhenNoDate() { - try { - DateParser.parseDate("potato"); - fail("Shouldn't parse potato!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenLooksLikeDateButItIsnt() { - try { - DateParser.parseDate("potato/cucumber/banana"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenIsInvalidDate() { - try { - DateParser.parseDate("13/13/13"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testShouldParseValidDate() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); - } - - @Test - public void testShouldIgnoreTimestamp() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20 12:34:56"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java b/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java index 7ac623ac86..c94ec8c42d 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Testcase for 'Analysis Toolpak' function IFERROR() @@ -79,21 +79,20 @@ public class TestIfError { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Checks that the cell is numeric", - CellType.NUMERIC, evaluator.evaluate(cell1).getCellType()); - assertEquals("Divides 210 by 35 and returns 6.0", - 6.0, evaluator.evaluate(cell1).getNumberValue(), accuracy); + 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("Checks that the cell is numeric", - CellType.STRING, evaluator.evaluate(cell2).getCellType()); - assertEquals("Rounds -10 to a nearest multiple of -3 (-9)", - "Error in calculation", evaluator.evaluate(cell2).getStringValue()); - - assertEquals("Check that C1 returns string", - CellType.STRING, evaluator.evaluate(cell3).getCellType()); - assertEquals("Check that C1 returns string \"error\"", - "error", evaluator.evaluate(cell3).getStringValue()); + 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 index b9aa6f1663..290e4663fc 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.formula.eval.ErrorEval; @@ -24,7 +24,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Testcase for 'Analysis Toolpak' function MROUND() @@ -56,19 +56,19 @@ public class TestMRound { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Rounds 10 to a nearest multiple of 3 (9)", - 9.0, evaluator.evaluate(cell1).getNumberValue(), accuracy); + assertEquals(9.0, evaluator.evaluate(cell1).getNumberValue(), accuracy, + "Rounds 10 to a nearest multiple of 3 (9)"); - assertEquals("Rounds -10 to a nearest multiple of -3 (-9)", - -9.0, evaluator.evaluate(cell2).getNumberValue(), accuracy); + assertEquals(-9.0, evaluator.evaluate(cell2).getNumberValue(), accuracy, + "Rounds -10 to a nearest multiple of -3 (-9)"); - assertEquals("Rounds 1.3 to a nearest multiple of 0.2 (1.4)", - 1.4, evaluator.evaluate(cell3).getNumberValue(), accuracy); + assertEquals(1.4, evaluator.evaluate(cell3).getNumberValue(), accuracy, + "Rounds 1.3 to a nearest multiple of 0.2 (1.4)"); - assertEquals("Returns an error, because -2 and 5 have different signs (#NUM!)", - ErrorEval.NUM_ERROR.getErrorCode(), evaluator.evaluate(cell4).getErrorValue()); + assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), evaluator.evaluate(cell4).getErrorValue(), + "Returns an error, because -2 and 5 have different signs (#NUM!)"); - assertEquals("Returns 0 because the multiple is 0", - 0.0, evaluator.evaluate(cell5).getNumberValue(), 0); + 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 index 4c6dc8b048..2d87aca37e 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java @@ -19,7 +19,7 @@ package org.apache.poi.ss.formula.atp; import static org.apache.poi.ss.formula.eval.ErrorEval.NAME_INVALID; import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; @@ -31,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestNetworkdaysFunction { diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java b/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java index 367109b61e..6c3ecbfc3c 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.eval.AreaEval; import org.apache.poi.ss.formula.eval.BlankEval; @@ -26,7 +26,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Testcase for Excel function PERCENTILE() diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java b/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java index a4d387f5d9..666d6cb643 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java @@ -16,8 +16,8 @@ ==================================================================== */ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -27,23 +27,22 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Testcase for 'Analysis Toolpak' function RANDBETWEEN() */ public class TestRandBetween { - private Workbook wb; private FormulaEvaluator evaluator; private Cell bottomValueCell; private Cell topValueCell; private Cell formulaCell; - @Before + @BeforeEach public void setUp() throws Exception { - wb = HSSFTestDataSamples.openSampleWorkbook("TestRandBetween.xls"); + Workbook wb = HSSFTestDataSamples.openSampleWorkbook("TestRandBetween.xls"); evaluator = wb.getCreationHelper().createFormulaEvaluator(); Sheet sheet = wb.createSheet("RandBetweenSheet"); @@ -76,8 +75,8 @@ public class TestRandBetween { formulaCell.setCellFormula("RANDBETWEEN(0,9999999999)"); evaluator.evaluateFormulaCell(formulaCell); double value = formulaCell.getNumericCellValue(); - assertTrue("rand is greater than or equal to lowerbound", value >= 0.0); - assertTrue("rand is less than or equal to upperbound", value <= 9999999999.0); + assertTrue(value >= 0.0, "rand is greater than or equal to lowerbound"); + assertTrue(value <= 9999999999.0, "rand is less than or equal to upperbound"); } } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java index 3ea70b9947..06a69c03a8 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java @@ -18,14 +18,14 @@ package org.apache.poi.ss.formula.atp; import static java.util.Calendar.SATURDAY; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public class TestWorkdayCalculator { @@ -139,8 +139,7 @@ public class TestWorkdayCalculator { 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("Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2, - 1, count); + assertEquals(1, count, "Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2); } @Test @@ -150,7 +149,6 @@ public class TestWorkdayCalculator { 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("Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2, - 1, count); + 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 index aba965bbf6..5772103fbf 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java @@ -20,7 +20,7 @@ package org.apache.poi.ss.formula.atp; import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Calendar; @@ -36,7 +36,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestWorkdayFunction { @@ -89,7 +89,7 @@ public class TestWorkdayFunction { 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); } @@ -140,7 +140,7 @@ public class TestWorkdayFunction { 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); } @@ -152,7 +152,7 @@ public class TestWorkdayFunction { 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); } @@ -166,7 +166,7 @@ public class TestWorkdayFunction { 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); } diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java index 6094d1860b..c9737102c6 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Specific test cases for YearFracCalculator @@ -56,7 +56,7 @@ public final class TestYearFracCalculator { System.out.println(startDate + " " + endDate + " off by " + hours + " hours"); assertEquals(expectedValue, actualValue, 0.000000001); } - + } private static double md(int year, int month, int day) { diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java index 42675eea2f..b3dd5db273 100644 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.atp; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -35,13 +35,13 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests YearFracCalculator using test-cases listed in a sample spreadsheet */ public final class TestYearFracCalculatorFromSpreadsheet { - + private static final class SS { public static final int BASIS_COLUMN = 1; // "B" @@ -53,7 +53,7 @@ public final class TestYearFracCalculatorFromSpreadsheet { @Test public void testAll() throws Exception { - + HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("yearfracExamples.xls"); HSSFSheet sheet = wb.getSheetAt(0); HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(wb); @@ -61,7 +61,7 @@ public final class TestYearFracCalculatorFromSpreadsheet { 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; @@ -70,26 +70,26 @@ public final class TestYearFracCalculatorFromSpreadsheet { nSuccess++; } - assertTrue("No test sample cases found", nSuccess > 0); + 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("Direct calculate failed"+loc, expectedValue, actualValue, 0); + assertEquals(expectedValue, actualValue, 0, "Direct calculate failed"+loc); actualValue = formulaEvaluator.evaluate(cell).getNumberValue(); - assertEquals("Formula evaluate failed"+loc, expectedValue, actualValue, 0); + assertEquals(expectedValue, actualValue, 0, "Formula evaluate failed"+loc); } private static double makeDate(HSSFRow row, int yearColumn) { @@ -103,13 +103,13 @@ public final class TestYearFracCalculatorFromSpreadsheet { 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(msg, Math.floor(dVal), dVal, 0); + assertEquals(Math.floor(dVal), dVal, 0, msg); return (int)dVal; } private static double getDoubleCell(HSSFRow row, int colIx) { HSSFCell cell = row.getCell(colIx); - assertNotNull("No cell found at column " + colIx, cell); + 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 index 72a9bcc0d8..aad09be92a 100644 --- a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java +++ b/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java @@ -18,17 +18,16 @@ package org.apache.poi.ss.formula.constant; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Arrays; +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.Test; +import org.junit.jupiter.api.Test; public final class TestConstantValueParser { private static final Object[] SAMPLE_VALUES = { @@ -58,9 +57,7 @@ public final class TestConstantValueParser { ConstantValueParser.encode(new LittleEndianByteArrayOutputStream(data, 0), SAMPLE_VALUES); - if (!Arrays.equals(data, SAMPLE_ENCODING)) { - fail("Encoding differs"); - } + assertArrayEquals(SAMPLE_ENCODING, data, "Encoding differs"); } @Test @@ -69,9 +66,7 @@ public final class TestConstantValueParser { Object[] values = ConstantValueParser.parse(in, 4); for (int i = 0; i < values.length; i++) { - if(!isEqual(SAMPLE_VALUES[i], values[i])) { - fail("Decoded result differs"); - } + assertTrue(isEqual(SAMPLE_VALUES[i], values[i]), "Decoded result differs"); } } private static boolean isEqual(Object a, Object b) { diff --git a/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java b/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java deleted file mode 100644 index d30e5e585a..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.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.ss.formula.eval; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests the package org.apache.poi.hssf.record.formula.eval. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaEval.class, - TestHSSFCircularReferences.class, - TestDivideEval.class, - TestEqualEval.class, - TestExternalFunction.class, - TestFormulaBugs.class, - TestFormulasFromSpreadsheet.class, - TestMinusZeroResult.class, - TestMissingArgEval.class, - TestPercentEval.class, - TestRangeEval.class, - TestUnaryPlusEval.class -}) -public class AllFormulaEvalTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java b/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java index ef9ab269e8..9ab60c9fb2 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +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; @@ -32,7 +32,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Common superclass for testing cases of circular references diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java index f7f65231f2..83c7616459 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java @@ -18,14 +18,14 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for AreaEval @@ -46,7 +46,7 @@ public final class TestAreaEval { new NumberEval(6), }; AreaEval ae = EvalFactory.createAreaEval(ptg, values); - assertNotEquals("Identified bug 44950 a", one, ae.getAbsoluteValue(1, 2)); + 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); diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java index a0d4d96497..1d786f9e01 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java @@ -17,11 +17,11 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Test for divide operator evaluator. diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java index 22dfd56338..c22583dbaa 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Test for EqualEval @@ -42,7 +42,7 @@ public final class TestEqualEval { BoolEval.FALSE, }; ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - assertNotEquals("Identified bug in evaluation of 1x1 area", ErrorEval.VALUE_INVALID, result); + assertNotEquals(ErrorEval.VALUE_INVALID, result, "Identified bug in evaluation of 1x1 area"); assertTrue(result instanceof BoolEval); assertTrue(((BoolEval)result).getBooleanValue()); } @@ -60,7 +60,7 @@ public final class TestEqualEval { ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); assertEquals(BoolEval.class, result.getClass()); BoolEval be = (BoolEval) result; - assertTrue("Identified bug blank/empty string equality", be.getBooleanValue()); + assertTrue(be.getBooleanValue(), "Identified bug blank/empty string equality"); } /** @@ -133,11 +133,11 @@ public final class TestEqualEval { public void testZeroEquality_bug47198() { NumberEval zero = new NumberEval(0.0); NumberEval mZero = (NumberEval) evaluate(UnaryMinusEval.instance, new ValueEval[] { zero, }, 0, 0); - assertNotEquals("Identified bug 47198: unary minus should convert -0.0 to 0.0", - 0x8000000000000000L, Double.doubleToLongBits(mZero.getNumberValue())); + 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("Identified bug 47198: -0.0 != 0.0", result.getBooleanValue()); + assertTrue(result.getBooleanValue(), "Identified bug 47198: -0.0 != 0.0"); } @Test @@ -151,7 +151,7 @@ public final class TestEqualEval { ValueEval[] args = { a, b, }; BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - assertTrue("Identified bug 47598: 1+1.0028-0.9973 != 1.0055", result.getBooleanValue()); + 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) { diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java b/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java index 9f86c1eadc..6fcca886c0 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -32,7 +32,7 @@ import org.apache.poi.ss.formula.functions.FreeRefFunction; import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; import org.apache.poi.ss.formula.udf.DefaultUDFFinder; import org.apache.poi.ss.formula.udf.UDFFinder; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestExternalFunction { diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java index db2a20c1e2..c74d1050f8 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java @@ -17,17 +17,23 @@ package org.apache.poi.ss.formula.eval; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.junit.Test; +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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 @@ -61,14 +67,14 @@ public final class TestFormulaBugs { 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 @@ -102,18 +108,18 @@ public final class TestFormulaBugs { // 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(); } @@ -122,49 +128,48 @@ public final class TestFormulaBugs { */ @Test public void test42448() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); + try (Workbook wb = new HSSFWorkbook()) { + Sheet sheet1 = wb.createSheet("Sheet1"); - Row row = sheet1.createRow(0); - Cell cell = row.createCell(0); + 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 + // 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"); + 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); } - - 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); - - wb.close(); } private static void addCell(Sheet sheet, int rowIx, int colIx, @@ -183,21 +188,21 @@ public final class TestFormulaBugs { 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 public 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 @@ -212,33 +217,33 @@ public final class TestFormulaBugs { 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); @@ -248,7 +253,7 @@ public final class TestFormulaBugs { 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 index a3062efc36..422d82c5f0 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java @@ -17,14 +17,15 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +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; @@ -36,12 +37,10 @@ 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.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +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.

@@ -51,7 +50,6 @@ import org.junit.runners.Parameterized.Parameters; * corresponding test class (TestXxxx) of the target (Xxxx) implementor, * where execution can be observed more easily. */ -@RunWith(Parameterized.class) public final class TestFormulasFromSpreadsheet { private static HSSFWorkbook workbook; @@ -97,22 +95,13 @@ public final class TestFormulasFromSpreadsheet { int NUMBER_OF_ROWS_PER_FUNCTION = 4; } - @SuppressWarnings("DefaultAnnotationParam") - @Parameter(value = 0) - public String targetFunctionName; - @Parameter(value = 1) - public int formulasRowIdx; - @Parameter(value = 2) - public int expectedValuesRowIdx; - - @AfterClass + @AfterAll public static void closeResource() throws Exception { LocaleUtil.setUserLocale(userLocale); workbook.close(); } - @Parameters(name="{0}") - public static Collection data() { + 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 @@ -123,7 +112,7 @@ public final class TestFormulasFromSpreadsheet { sheet = workbook.getSheetAt( 0 ); evaluator = new HSSFFormulaEvaluator(workbook); - List data = new ArrayList<>(); + List data = new ArrayList<>(); processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX); processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX); @@ -131,20 +120,20 @@ public final class TestFormulasFromSpreadsheet { // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - return data; + 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) { + 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("Test spreadsheet cell empty on row (" + assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); + + SS.FUNCTION_NAMES_END_SENTINEL + "'"); if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { // found end of functions list break; @@ -153,15 +142,16 @@ public final class TestFormulasFromSpreadsheet { // expected results are on the row below Row expectedValuesRow = sheet.getRow(rowIndex + 1); int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row - assertNotNull("Missing expected values row for function '" - + targetFunctionName + " (row " + missingRowNum + ")", expectedValuesRow); + assertNotNull(expectedValuesRow, "Missing expected values row for function '" + + targetFunctionName + " (row " + missingRowNum + ")"); - data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); + data.add(Arguments.of(targetFunctionName, rowIndex, rowIndex + 1)); } } - @Test - public void processFunctionRow() { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { Row formulasRow = sheet.getRow(formulasRowIdx); Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); @@ -180,31 +170,31 @@ public final class TestFormulasFromSpreadsheet { String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); + 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(msg, CellType.BLANK, actValue.getCellType()); + assertEquals(CellType.BLANK, actValue.getCellType(), msg); break; case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellType()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); break; case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellType()); - assertEquals(msg, ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue())); + 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(msg, CellType.NUMERIC, actValue.getCellType()); - TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + TestMathX.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); break; case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellType()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + cellType); @@ -224,14 +214,11 @@ public final class TestFormulasFromSpreadsheet { System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); return null; } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - fail("Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - 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/TestMinusZeroResult.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java index e725bf7746..e278665d42 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * IEEE 754 defines a quantity '-0.0' which is distinct from '0.0'. diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java index 122882d609..b63f38d8e7 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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; @@ -28,7 +28,7 @@ import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link MissingArgEval} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java index 1c3350f6c0..a8914d2264 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java @@ -17,15 +17,16 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import 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; @@ -36,15 +37,13 @@ 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.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; +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)) */ -@RunWith(Parameterized.class) public final class TestMultiSheetEval { /** * This class defines constants for navigating around the test data spreadsheet used for these tests. @@ -89,27 +88,14 @@ public final class TestMultiSheetEval { private static HSSFFormulaEvaluator evaluator; private static Collection funcs; - @SuppressWarnings("DefaultAnnotationParam") - @Parameter(value = 0) - public String testName; - @Parameter(value = 1) - public String functionName; - - @Parameter(value = 2) - public Cell expected; - - @Parameter(value = 3) - public Row testRow; - - @Parameterized.Parameters(name="{0}") - public static Collection data() { + 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<>(); + List data = new ArrayList<>(); for (int rowIndex = SS.START_FUNCTIONS_ROW_INDEX;true;rowIndex++) { Row r = sheet.getRow(rowIndex); @@ -119,7 +105,7 @@ public final class TestMultiSheetEval { } String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); + 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; @@ -128,29 +114,30 @@ public final class TestMultiSheetEval { // expected results are on the row below Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull("Missing expected values cell for function '" + targetFunctionName, expectedValueCell); + assertNotNull(expectedValueCell, "Missing expected values cell for function '" + targetFunctionName); - data.add(new Object[]{ targetTestName, targetFunctionName, expectedValueCell, r }); + data.add(Arguments.of( targetTestName, targetFunctionName, expectedValueCell, r )); } - return data; + return data.stream(); } - @Test - public void testFunction() { + @ParameterizedTest + @MethodSource("data") + public 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("unsupported function", funcs.contains(functionName.toUpperCase(Locale.ROOT))); + assertTrue(funcs.contains(functionName.toUpperCase(Locale.ROOT)), "unsupported function"); return; } CellValue actual = evaluator.evaluate(c); - assertNotNull("Bad setup data expected value is null", expected); - assertNotNull("actual value was null", actual); + assertNotNull(expected, "Bad setup data expected value is null"); + assertNotNull(actual, "actual value was null"); final CellType cellType = expected.getCellType(); @@ -171,7 +158,7 @@ public final class TestMultiSheetEval { break; case NUMERIC: assertEquals(CellType.NUMERIC, actual.getCellType()); - TestMathX.assertEquals("", expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); + TestMathX.assertDouble("", expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); break; case STRING: assertEquals(CellType.STRING, actual.getCellType()); @@ -184,17 +171,17 @@ public final class TestMultiSheetEval { } private static String getTargetFunctionName(Row r) { - assertNotNull("given null row, can't figure out function name", r); + assertNotNull(r, "given null row, can't figure out function name"); Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - assertNotNull("Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", cell); + 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("Given null row, can't figure out test name", r); + assertNotNull(r, "Given null row, can't figure out test name"); Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME); - assertNotNull("Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name", cell); + 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 index 6aa0370f07..7785a425b3 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for OperandResolver @@ -42,7 +42,7 @@ public final class TestOperandResolver { String value = ".1"; Double resolvedValue = OperandResolver.parseDouble(value); - assertNotNull("Identified bug 49723", resolvedValue); + assertNotNull(resolvedValue, "Identified bug 49723"); } /** diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java index 26bd6bf5dc..8357fd6e9e 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -30,7 +30,7 @@ import org.apache.poi.ss.formula.functions.EvalFactory; import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test for percent operator evaluator. diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java index 1139cfac24..5fdfda90ad 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestPowerEval.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -26,7 +26,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for power operator evaluator. diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java index c1becf6cf3..dfde9986a3 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; @@ -34,7 +34,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test for unary plus operator evaluator. diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java index d85332067f..9846c192b5 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.eval; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Test for unary plus operator evaluator. 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 index 70745ef979..8f67e87d65 100644 --- a/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java +++ b/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.eval.forked; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +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; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class BaseTestForkedEvaluator { diff --git a/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java b/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java deleted file mode 100644 index 1931bdbcd1..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.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.ss.formula.function; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for this org.apache.poi.hssf.record.formula.function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestFunctionMetadataRegistry.class, - TestParseMissingBuiltInFuncs.class, - TestReadMissingBuiltInFuncs.class -}) -public class AllFormulaFunctionTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java b/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java index dcf2277796..7c100f76b0 100644 --- a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java +++ b/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestFunctionMetadataRegistry { @Test diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java index 554afa9751..3f5c55fb1f 100644 --- a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java +++ b/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.io.IOException; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests parsing of some built-in functions that were not properly @@ -53,7 +53,7 @@ public final class TestParseMissingBuiltInFuncs { throw new RuntimeException("function token missing"); } AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF; - assertNotEquals("Failed to recognise built-in function in formula", 255, func.getFunctionIndex()); + 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; diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java index 2073d45ff1..d5f4a81800 100644 --- a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java +++ b/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java @@ -17,8 +17,10 @@ package org.apache.poi.ss.formula.function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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; @@ -26,9 +28,9 @@ 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.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +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 @@ -44,7 +46,7 @@ public final class TestReadMissingBuiltInFuncs { private static HSSFWorkbook wb; private static HSSFSheet _sheet; - @BeforeClass + @BeforeAll public static void initSheet() { wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME); try { @@ -54,9 +56,8 @@ public final class TestReadMissingBuiltInFuncs { InvocationTargetException ite = (InvocationTargetException) e.getCause(); if(ite.getTargetException() instanceof RuntimeException) { RuntimeException re = (RuntimeException) ite.getTargetException(); - if(re.getMessage().equals("Invalid built-in function index (189)")) { - fail("DPRODUCT() registered with wrong index"); - } + assertNotEquals("Invalid built-in function index (189)", re.getMessage(), + "DPRODUCT() registered with wrong index"); } } // some other unexpected error @@ -64,7 +65,7 @@ public final class TestReadMissingBuiltInFuncs { } } - @AfterClass + @AfterAll public static void closeResources() throws Exception { wb.close(); } @@ -76,9 +77,8 @@ public final class TestReadMissingBuiltInFuncs { formula = getCellFormula(0); } catch (IllegalStateException e) { if(e.getMessage().startsWith("Too few arguments")) { - if(e.getMessage().indexOf("AttrPtg") > 0) { - fail("tAttrVolatile not supported in FormulaParser.toFormulaString"); - } + 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")) { @@ -89,31 +89,25 @@ public final class TestReadMissingBuiltInFuncs { } assertEquals("DATEDIF(NOW(),NOW(),\"d\")", formula); } - + @Test public void testDdb() { String formula = getCellFormula(1); - if("externalflag(1,1,1,1,1)".equals(formula)) { - fail("DDB() not registered"); - } + assertNotEquals("externalflag(1,1,1,1,1)", formula, "DDB() not registered"); assertEquals("DDB(1,1,1,1,1)", formula); } - + @Test public void testAtan() { String formula = getCellFormula(2); - if("ARCTAN(1)".equals(formula)) { - fail("func ix 18 registered as ARCTAN() instead of ATAN()"); - } + assertNotEquals("ARCTAN(1)", formula, "func ix 18 registered as ARCTAN() instead of ATAN()"); assertEquals("ATAN(1)", formula); } @Test public void testUsdollar() { String formula = getCellFormula(3); - if("YEN(1)".equals(formula)) { - fail("func ix 204 registered as YEN() instead of USDOLLAR()"); - } + assertNotEquals("YEN(1)", formula, "func ix 204 registered as YEN() instead of USDOLLAR()"); assertEquals("USDOLLAR(1)", formula); } @@ -123,35 +117,29 @@ public final class TestReadMissingBuiltInFuncs { try { formula = getCellFormula(4); } catch (IllegalStateException e) { - if(e.getMessage().startsWith("too much stuff")) { - fail("DBCS() not registered"); - } + 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"); } - if("JIS(\"abc\")".equals(formula)) { - fail("func ix 215 registered as JIS() instead of DBCS()"); - } + assertNotEquals("JIS(\"abc\")", formula, "func ix 215 registered as JIS() instead of DBCS()"); assertEquals("DBCS(\"abc\")", formula); } - + @Test public void testIsnontext() { String formula; try { formula = getCellFormula(5); } catch (IllegalStateException e) { - if(e.getMessage().startsWith("too much stuff")) { - fail("ISNONTEXT() registered with wrong index"); - } + assertFalse(e.getMessage().startsWith("too much stuff"), "ISNONTEXT() registered with wrong index"); // some other unexpected error throw e; } assertEquals("ISNONTEXT(\"abc\")", formula); } - + @Test public void testDproduct() { String formula = getCellFormula(6); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java b/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java deleted file mode 100644 index bbcf2829d8..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.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.functions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Direct tests for all implementors of Function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAverage.class, - TestCountFuncs.class, - TestDate.class, - TestDays360.class, - TestFinanceLib.class, - TestFind.class, - TestIndex.class, - TestIndexFunctionFromSpreadsheet.class, - TestIndirect.class, - TestIsBlank.class, - TestLen.class, - TestLookupFunctionsFromSpreadsheet.class, - TestMatch.class, - TestMathX.class, - TestMid.class, - TestNper.class, - TestOffset.class, - TestPmt.class, - TestRoundFuncs.class, - TestRowCol.class, - TestStatsLib.class, - TestSubtotal.class, - TestSumif.class, - TestSumproduct.class, - TestText.class, - TestTFunc.class, - TestTime.class, - TestTrim.class, - TestTrunc.class, - TestValue.class, - TestXYNumericFunction.class, - TestAddress.class, - TestAreas.class, - TestClean.class -}) -public class AllIndividualFunctionEvaluationTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java b/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java deleted file mode 100644 index 0dc5ed9233..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.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.formula.functions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Direct tests for all implementors of Function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCodeFunctionsFromSpreadsheet.class, - TestComplexFunctionsFromSpreadsheet.class, - TestDeltaFunctionsFromSpreadsheet.class, - TestDGetFunctionsFromSpreadsheet.class, - TestDStarFunctionsFromSpreadsheet.class, - TestFactDoubleFunctionsFromSpreadsheet.class, - TestFixedFunctionsFromSpreadsheet.class, - TestImaginaryFunctionsFromSpreadsheet.class, - TestImRealFunctionsFromSpreadsheet.class, - TestIndexFunctionFromSpreadsheet.class, - TestIndirectFunctionFromSpreadsheet.class, - TestLookupFunctionsFromSpreadsheet.class, - TestMatchFunctionsFromSpreadsheet.class, - TestQuotientFunctionsFromSpreadsheet.class, - TestReptFunctionsFromSpreadsheet.class, - TestRomanFunctionsFromSpreadsheet.class, - TestTrendFunctionsFromSpreadsheet.class, - TestWeekNumFunctionsFromSpreadsheet.class, - TestWeekNumFunctionsFromSpreadsheet2013.class -}) -public class AllSpreadsheetBasedTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java index 7b899350c1..594b7b68a2 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java @@ -17,16 +17,16 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.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.HSSFCell; @@ -34,16 +34,14 @@ 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.util.CellReference; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; +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; -@RunWith(Parameterized.class) public abstract class BaseTestFunctionsFromSpreadsheet { /** @@ -68,26 +66,13 @@ public abstract class BaseTestFunctionsFromSpreadsheet { } - @Parameter() - public String testName; - @Parameter(value = 1) - public String filename; - @Parameter(value = 2) - public HSSFSheet sheet; - @Parameter(value = 3) - public int formulasRowIdx; - @Parameter(value = 4) - public HSSFFormulaEvaluator evaluator; - @Parameter(value = 5) - public int precisionColumnIndex; - - protected static Collection data(Class clazz, String filename) throws Exception { + protected static Stream data(Class clazz, String filename) throws Exception { HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(filename); confirmReadMeSheet(workbook, clazz); - List data = new ArrayList<>(); + List data = new ArrayList<>(); int nSheets = workbook.getNumberOfSheets(); for(int sheetIdx=1; sheetIdx< nSheets; sheetIdx++) { @@ -96,11 +81,11 @@ public abstract class BaseTestFunctionsFromSpreadsheet { } workbook.close(); - - return data; + + return data.stream(); } - private static void processFunctionGroup(List data, HSSFSheet sheet, final int startRowIndex, String filename) { + private static void processFunctionGroup(List data, HSSFSheet sheet, final int startRowIndex, String filename) { HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet.getWorkbook()); int precisionColumnIndex = -1; @@ -118,7 +103,7 @@ public abstract class BaseTestFunctionsFromSpreadsheet { if(r == null) { continue; } - String newMarkerValue = getCellTextValue(r, SS.COLUMN_INDEX_MARKER, "marker"); + String newMarkerValue = getCellTextValue(r, SS.COLUMN_INDEX_MARKER, "marker"); if(SS.TEST_CASES_END_MARKER.equalsIgnoreCase(newMarkerValue)) { // normal exit point return; @@ -140,14 +125,17 @@ public abstract class BaseTestFunctionsFromSpreadsheet { if (testName.isEmpty()) { testName = evalCell.getCellFormula(); } - - data.add(new Object[]{testName, filename, sheet, rowIndex, evaluator, precisionColumnIndex}); + + data.add(Arguments.of(testName, filename, sheet, rowIndex, evaluator, precisionColumnIndex)); } fail("Missing end marker '" + SS.TEST_CASES_END_MARKER + "' on sheet '" + sheet.getSheetName() + "'"); } - @Test - public void processFunctionRow() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void processFunctionRow( + String testName, String filename, HSSFSheet sheet, int formulasRowIdx, HSSFFormulaEvaluator evaluator, int precisionColumnIndex + ) throws Exception { HSSFRow r = sheet.getRow(formulasRowIdx); HSSFCell evalCell = r.getCell(SS.COLUMN_INDEX_EVALUATION); HSSFCell expectedCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_RESULT); @@ -159,29 +147,29 @@ public abstract class BaseTestFunctionsFromSpreadsheet { CellValue actualValue = evaluator.evaluate(evalCell); - assertNotNull(msg + " - Bad setup data expected value is null", expectedCell); - assertNotNull(msg + " - actual value was null", actualValue); + assertNotNull(expectedCell, msg + " - Bad setup data expected value is null"); + assertNotNull(actualValue, msg + " - actual value was null"); if (expectedCell.getCellType() == CellType.ERROR) { int expectedErrorCode = expectedCell.getErrorCellValue(); - assertEquals(msg, CellType.ERROR, actualValue.getCellType()); - assertEquals(msg, ErrorEval.getText(expectedErrorCode), actualValue.formatAsString()); - assertEquals(msg, expectedErrorCode, actualValue.getErrorValue()); - assertEquals(msg, ErrorEval.getText(expectedErrorCode), ErrorEval.getText(actualValue.getErrorValue())); + assertEquals(CellType.ERROR, actualValue.getCellType(), msg); + assertEquals(ErrorEval.getText(expectedErrorCode), actualValue.formatAsString(), msg); + assertEquals(expectedErrorCode, actualValue.getErrorValue(), msg); + assertEquals(ErrorEval.getText(expectedErrorCode), ErrorEval.getText(actualValue.getErrorValue()), msg); return; } // unexpected error - assertNotEquals(msg, CellType.ERROR, actualValue.getCellType()); + assertNotEquals(CellType.ERROR, actualValue.getCellType(), msg); assertNotEquals(msg, formatValue(expectedCell), ErrorEval.getText(actualValue.getErrorValue())); // wrong type error - assertEquals(msg, expectedCell.getCellType(), actualValue.getCellType()); + assertEquals(expectedCell.getCellType(), actualValue.getCellType(), msg); final CellType expectedCellType = expectedCell.getCellType(); switch (expectedCellType) { case BOOLEAN: - assertEquals(msg, expectedCell.getBooleanCellValue(), actualValue.getBooleanValue()); + assertEquals(expectedCell.getBooleanCellValue(), actualValue.getBooleanValue(), 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); @@ -191,7 +179,7 @@ public abstract class BaseTestFunctionsFromSpreadsheet { assertEquals(expectedCell.getNumericCellValue(), actualValue.getNumberValue(), precision); break; case STRING: - assertEquals(msg, expectedCell.getRichStringCellValue().getString(), actualValue.getStringValue()); + assertEquals(expectedCell.getRichStringCellValue().getString(), actualValue.getStringValue(), msg); break; default: fail("Unexpected cell type: " + expectedCellType); @@ -205,11 +193,11 @@ public abstract class BaseTestFunctionsFromSpreadsheet { */ private static void confirmReadMeSheet(HSSFWorkbook workbook, Class clazz) { String firstSheetName = workbook.getSheetName(0); - assertTrue("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'", - firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)); + 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("Test class name in spreadsheet comment", clazz.getName(), specifiedClassName); + assertEquals(clazz.getName(), specifiedClassName, "Test class name in spreadsheet comment"); HSSFRow precisionRow = sheet.getRow(11); HSSFCell precisionCell = precisionRow == null ? null : precisionRow.getCell(0); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java index ea1055cf7a..d5e02e0de8 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestNumeric.java @@ -20,7 +20,7 @@ */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Amol S. Deshmukh < amolweb at ya hoo dot com > @@ -37,35 +37,30 @@ public abstract class BaseTestNumeric { * 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. - * @param message - * @param baseval - * @param checkval */ - public static void assertEquals(String message, double baseval, double checkval, double almostZero, double diffToleranceFactor) { + 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(message+": Expected " + baseval + " but was " + checkval - , Double.isNaN(baseval)); + assertTrue(Double.isNaN(baseval), message+": Expected " + baseval + " but was " + checkval); } else if (Double.isInfinite(baseval)) { - assertTrue(message+": Expected " + baseval + " but was " + checkval - , Double.isInfinite(baseval) && ((baseval<0) == (checkval<0))); + assertTrue(Double.isInfinite(baseval) && ((baseval<0) == (checkval<0)), message+": Expected " + baseval + " but was " + checkval); } else { - assertTrue(message+": Expected " + baseval + " but was " + checkval - ,baseval != 0 - ? Math.abs(baseval - checkval) <= Math.abs(diffToleranceFactor * baseval) - : checkval < posZero && checkval > negZero); + assertTrue(baseval != 0 + ? Math.abs(baseval - checkval) <= Math.abs(diffToleranceFactor * baseval) + : checkval < posZero && checkval > negZero, + message+": Expected " + baseval + " but was " + checkval); } } - public static void assertEquals(String msg, double baseval, double checkval) { - assertEquals(msg, baseval, checkval, POS_ZERO, DIFF_TOLERANCE_FACTOR); + public static void assertDouble(String msg, double baseval, double checkval) { + assertDouble(msg, baseval, checkval, POS_ZERO, DIFF_TOLERANCE_FACTOR); } - public static void assertEquals(double baseval, double checkval) { - assertEquals("", 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/NumericFunctionInvoker.java b/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java index e53f88e1fb..bf49dad45d 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.NotImplementedException; diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java index e8b302b3ef..62f7f5e647 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestAddress { diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java index 08de5131de..5861d42ecf 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestAreas.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestAreas { diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java index e24dd080f2..32ac46a525 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function AVERAGE() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java index f35d5253c6..ab906cdb24 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java @@ -17,18 +17,17 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.IStabilityClassifier; 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Bin2Dec} @@ -44,14 +43,14 @@ public final class TestBin2Dec { private static void confirmValue(String msg, String number1, String expected) { ValueEval result = invokeValue(number1); - assertEquals("Had: " + result, NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test @@ -95,15 +94,8 @@ public final class TestBin2Dec { HSSFWorkbook wb = new HSSFWorkbook(); wb.createSheet(); HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - return new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); + WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); + return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java index ef69a9c65b..1689cba236 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestBooleanFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; -import java.util.Collection; +import org.junit.jupiter.params.provider.Arguments; /** * Tests boolean functions as loaded from a test data spreadsheet.

*/ public class TestBooleanFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 1180c2dbcd..cf5dcb6fee 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -25,8 +25,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test for YEAR / MONTH / DAY / HOUR / MINUTE / SECOND @@ -36,7 +36,7 @@ public final class TestCalendarFieldFunction { private HSSFCell cell11; private HSSFFormulaEvaluator evaluator; - @Before + @BeforeEach public void setUp() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); @@ -108,7 +108,7 @@ public final class TestCalendarFieldFunction { cell11.setCellFormula(formulaText); evaluator.clearAllCachedResultValues(); CellValue cv = evaluator.evaluate(cell11); - assertEquals("Wrong result type", CellType.NUMERIC, cv.getCellType()); + 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 index ef8d9a08e1..d6542611c1 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public final class TestClean { diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java index 8c1a176b6c..9b9e315a24 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Code} @@ -37,13 +37,13 @@ public class TestCode { private static void confirmValue(String msg, String number1, String expected) { ValueEval result = invokeValue(number1); assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java index 1d2e2cf0a7..7e9257bbc0 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests CODE() as loaded from a test data spreadsheet.

*/ public class TestCodeFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 54f7241df1..dd16248742 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java @@ -16,12 +16,12 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Complex} @@ -37,13 +37,13 @@ public class TestComplex { 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(msg, expected, ((StringEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java index f16246fd1c..6761090ed0 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests COMPLEX() as loaded from a test data spreadsheet.

*/ public class TestComplexFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 36a6f8dfa1..65238d17fb 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -41,7 +41,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for COUNT(), COUNTA() COUNTIF(), COUNTBLANK() @@ -151,7 +151,7 @@ public final class TestCountFuncs { assertNotNull(mp); StringEval seA = new StringEval("aa"); // this should not match the criteria '<>aa' StringEval seB = new StringEval("bb"); // this should match - assertFalse("Identified bug 46647", mp.matches(seA) && !mp.matches(seB)); + assertFalse(mp.matches(seA) && !mp.matches(seB), "Identified bug 46647"); assertFalse(mp.matches(seA)); assertTrue(mp.matches(seB)); @@ -420,10 +420,8 @@ public final class TestCountFuncs { double expectedValue = cellRef.getNumericCellValue(); double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - assertEquals( - "Problem with a formula at " + - new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] ", - expectedValue, actualValue, 0.0001); + assertEquals(expectedValue, actualValue, 0.0001, + "Problem with a formula at " + new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] "); } // string criteria @@ -434,10 +432,8 @@ public final class TestCountFuncs { double expectedValue = cellRef.getNumericCellValue(); double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - assertEquals( - "Problem with a formula at " + - new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] ", - expectedValue, actualValue, 0.0001); + assertEquals(expectedValue, actualValue, 0.0001, + "Problem with a formula at " + new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] "); } } @@ -533,11 +529,8 @@ public final class TestCountFuncs { CellValue cv = fe.evaluate(cellA); double actualValue = cv.getNumberValue(); double expectedValue = cellC.getNumericCellValue(); - assertEquals( - "Problem with a formula at " + new CellReference(cellA).formatAsString() - + ": " + cellA.getCellFormula() + " :" - + "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ", - expectedValue, actualValue, 0.0001); + 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"); @@ -552,12 +545,9 @@ public final class TestCountFuncs { double actualValue = cv.getNumberValue(); double expectedValue = cellC.getNumericCellValue(); - assertEquals( - "Problem with a formula at " + - new CellReference(cellA).formatAsString() + "[" + cellA.getCellFormula()+"]: " - + "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ", - expectedValue, actualValue, 0.0001); - + assertEquals(expectedValue, actualValue, 0.0001, + "Problem with a formula at " + new CellReference(cellA).formatAsString() + "[" + + cellA.getCellFormula()+"]: Expected = (" + expectedValue + ") Actual=(" + actualValue + ") "); } } @@ -589,6 +579,6 @@ public final class TestCountFuncs { } } - assertEquals(failureCount + " " + functionName + " evaluations failed.", 0, failureCount); + assertEquals(0, failureCount, failureCount + " " + functionName + " evaluations failed."); } } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java index 4ac7b9861e..2f5a487730 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java @@ -16,16 +16,15 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests DGET() as loaded from a test data spreadsheet. */ public class TestDGetFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + public static Stream 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 index 0d20d98d5d..3eb684bd89 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java @@ -16,16 +16,15 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests D*() functions as loaded from a test data spreadsheet. */ public class TestDStarFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index f1b528d2c9..851b8da32d 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -25,9 +25,9 @@ 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.Before; -import org.junit.Ignore; -import org.junit.Test; +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) @@ -37,7 +37,7 @@ public final class TestDate { private HSSFCell cell11; private HSSFFormulaEvaluator evaluator; - @Before + @BeforeEach public void setUp() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); @@ -50,7 +50,7 @@ public final class TestDate { * TODO - create MissingArgEval and modify the formula evaluator to handle this */ @Test - @Ignore + @Disabled public void testSomeArgumentsMissing() { confirm("DATE(, 1, 0)", 0.0); confirm("DATE(, 1, 1)", 1.0); @@ -87,7 +87,7 @@ public final class TestDate { cell11.setCellFormula(formulaText); evaluator.clearAllCachedResultValues(); CellValue cv = evaluator.evaluate(cell11); - assertEquals("Wrong result type", CellType.NUMERIC, cv.getCellType()); + 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 index 87f709d91d..e53d46da69 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDateTimeToNumberFromSpreadsheet.java @@ -17,13 +17,12 @@ package org.apache.poi.ss.formula.functions; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; -import java.util.Collection; +import org.junit.jupiter.params.provider.Arguments; public class TestDateTimeToNumberFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index a25fa270d1..05da127bd9 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDateValue.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Locale; @@ -27,9 +27,9 @@ 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.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests for Excel function DATEVALUE() @@ -38,12 +38,12 @@ import org.junit.Test; */ public final class TestDateValue { - @BeforeClass + @BeforeAll public static void init() { LocaleUtil.setUserLocale(Locale.US); } - @AfterClass + @AfterAll public static void clear() { LocaleUtil.setUserLocale(null); } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java index a20f444d70..590a33a5d8 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Calendar; import java.util.Date; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public final class TestDays360 { @@ -60,7 +60,7 @@ public final class TestDays360 { // 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); @@ -78,7 +78,7 @@ public final class TestDays360 { 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. @@ -148,17 +148,17 @@ public final class TestDays360 { } else { ve = invokeDays360(convert(firstArg), convert(secondArg)); } - assertTrue("wrong return type (" + ve.getClass().getName() + ")", ve instanceof NumberEval); + 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(err, expResult, numberEval.getNumberValue(), 0); + 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 index 336871811a..dd13c85aee 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java @@ -17,11 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.IStabilityClassifier; import org.apache.poi.ss.formula.OperationEvaluationContext; import org.apache.poi.ss.formula.WorkbookEvaluator; import org.apache.poi.ss.formula.eval.ErrorEval; @@ -31,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Dec2Bin} @@ -52,14 +51,14 @@ public final class TestDec2Bin { private static void confirmValue(String msg, String number1, String expected) { ValueEval result = invokeValue(number1); - assertEquals("Had: " + result, StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test @@ -115,15 +114,8 @@ public final class TestDec2Bin { cell.setCellValue("1"); HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - return new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); + WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); + return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); } @Test @@ -133,7 +125,7 @@ public final class TestDec2Bin { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); assertEquals("1101", ((StringEval) result).getStringValue()); } @@ -144,7 +136,7 @@ public final class TestDec2Bin { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); // TODO: documentation and behavior do not match here! assertEquals("1101", ((StringEval) result).getStringValue()); } @@ -156,7 +148,7 @@ public final class TestDec2Bin { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; ValueEval result = new Dec2Bin().evaluate(args, ctx); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); // TODO: documentation and behavior do not match here! assertEquals("1101", ((StringEval) result).getStringValue()); } @@ -242,15 +234,12 @@ public final class TestDec2Bin { public void testBackAndForth() { for (int i = -512; i < 512; i++) { ValueEval result = invokeValue(Integer.toString(i)); - assertEquals("Had: " + result, StringEval.class, - result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals("Had: " + back, NumberEval.class, - back.getClass()); + assertEquals(NumberEval.class, back.getClass(), "Had: " + back); - assertEquals(Integer.toString(i), - ((NumberEval) back).getStringValue()); + 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 index ac88365dde..286c3c837e 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java @@ -17,11 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.IStabilityClassifier; import org.apache.poi.ss.formula.OperationEvaluationContext; import org.apache.poi.ss.formula.WorkbookEvaluator; import org.apache.poi.ss.formula.eval.ErrorEval; @@ -31,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Dec2Hex} @@ -58,19 +57,19 @@ public final class TestDec2Hex { private static void confirmValue(String msg, String number1, String number2, String expected) { ValueEval result = invokeValue(number1, number2); assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); + 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(msg, expected, ((StringEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test @@ -98,11 +97,11 @@ public final class TestDec2Hex { assertEquals("2147483648", maxIntPlusOne); confirmValue("Converts INT_MAX + 1 to hexadecimal", maxIntPlusOne, "80000000"); - String maxLong = Long.toString(549755813887l); + String maxLong = Long.toString(549755813887L); assertEquals("549755813887", maxLong); confirmValue("Converts the max supported value to hexadecimal", maxLong, "7FFFFFFFFF"); - String minLong = Long.toString(-549755813888l); + String minLong = Long.toString(-549755813888L); assertEquals("-549755813888", minLong); confirmValue("Converts the min supported value to hexadecimal", minLong, "FF80000000"); } @@ -139,15 +138,8 @@ public final class TestDec2Hex { cell.setCellValue("-8"); HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - return new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); + WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, (sheetIndex, rowIndex, columnIndex) -> true, null); + return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); } @Test @@ -157,7 +149,7 @@ public final class TestDec2Hex { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); assertEquals("7B", ((StringEval) result).getStringValue()); } @@ -168,7 +160,7 @@ public final class TestDec2Hex { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); assertEquals("0000007B", ((StringEval) result).getStringValue()); } @@ -179,7 +171,7 @@ public final class TestDec2Hex { ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; ValueEval result = new Dec2Hex().evaluate(args, ctx); - assertEquals("Had: " + result, StringEval.class, result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); assertEquals("0000007B", ((StringEval) result).getStringValue()); } @@ -242,15 +234,12 @@ public final class TestDec2Hex { public void testBackAndForth() { for (int i = -512; i < 512; i++) { ValueEval result = invokeValue(Integer.toString(i)); - assertEquals("Had: " + result, StringEval.class, - result.getClass()); + assertEquals(StringEval.class, result.getClass(), "Had: " + result); ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals("Had: " + back, NumberEval.class, - back.getClass()); + assertEquals(NumberEval.class, back.getClass(), "Had: " + back); - assertEquals(Integer.toString(i), - ((NumberEval) back).getStringValue()); + 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 index 756b532bf2..b7f64c22e6 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link org.apache.poi.ss.formula.functions.Delta} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java index f1725d70bc..75755db7e0 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java @@ -16,16 +16,15 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests DELTA() as loaded from a test data spreadsheet.

*/ public class TestDeltaFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 1b134483de..3bcebaa613 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Calendar; import java.util.Date; @@ -30,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestEDate { @@ -53,7 +53,7 @@ public class TestEDate { NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(startDate), new NumberEval(monthInc)}, null); assertEquals(expectedResult, result.getNumberValue(), 0); } - + @Test public void testEDateInvalidValues() { EDate eDate = new EDate(); @@ -87,9 +87,9 @@ public class TestEDate { instance.add(Calendar.MONTH, offset); assertEquals(resultDate, instance.getTime()); } - + @Test - public void testBug56688() { + public 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); @@ -119,11 +119,9 @@ public class TestEDate { public void testEDateBlankRefValueEval() { EDate eDate = new EDate(); NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(BlankEval.instance), new NumberEval(0)}, null); - assertEquals("0 startDate triggers BAD_DATE currently, thus -1.0!", - -1.0d, result.getNumberValue(), 0); + 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("Blank is handled as 0 otherwise", - 1.0d, result.getNumberValue(), 0); + 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 index 8fbfa69961..0d7f60e2f0 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Calendar; import java.util.Date; @@ -32,7 +32,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestEOMonth { @@ -76,10 +76,10 @@ public class TestEOMonth { @Test public void testEOMonthZeroDate() { NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(0)}, ec); - assertEquals("0 startDate is 1900-01-00", DATE_1900_01_31, result.getNumberValue(), 0); + 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("0 startDate is 1900-01-00", DATE_1900_02_28, result.getNumberValue(), 0); + assertEquals(DATE_1900_02_28, result.getNumberValue(), 0, "0 startDate is 1900-01-00"); } @Test @@ -114,7 +114,7 @@ public class TestEOMonth { }; NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); Date actDate = DateUtil.getJavaDate(result.getNumberValue()); - + assertEquals(expDate, actDate); } } @@ -136,17 +136,17 @@ public class TestEOMonth { @Test public void testEOMonthBlankValueEval() { NumberEval evaluate = (NumberEval) eOMonth.evaluate(new ValueEval[] {BlankEval.instance, new NumberEval(0)}, ec); - assertEquals("Blank is handled as 0", DATE_1900_01_31, evaluate.getNumberValue(), 0); + assertEquals(DATE_1900_01_31, evaluate.getNumberValue(), 0, "Blank is handled as 0"); } @Test public void testEOMonthBlankRefValueEval() { ValueEval[] ve1 = {new RefEvalImplementation(BlankEval.instance), new NumberEval(1)}; NumberEval result = (NumberEval) eOMonth.evaluate(ve1, ec); - assertEquals("Blank is handled as 0", DATE_1900_02_28, result.getNumberValue(), 0); + 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("Blank is handled as 0", DATE_1900_01_31, result.getNumberValue(), 0); + 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 index 2d21db2260..ff28a5fd34 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests FactDouble() as loaded from a test data spreadsheet.

*/ public class TestFactDoubleFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 2e08083ca2..8a151ea2ac 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java @@ -21,7 +21,7 @@ package org.apache.poi.ss.formula.functions; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Amol S. Deshmukh < amolweb at ya hoo dot com > @@ -38,38 +38,38 @@ public class TestFinanceLib extends BaseTestNumeric { r = 0; n = 3; y = 2; p = 7; t = true; f = FinanceLib.fv(r, n, y, p, t); x = -13; - assertEquals("fv ", x, f); + assertDouble("fv ", x, f); r = 1; n = 10; y = 100; p = 10000; t = false; f = FinanceLib.fv(r, n, y, p, t); x = -10342300; - assertEquals("fv ", x, f); + assertDouble("fv ", x, f); r = 1; n = 10; y = 100; p = 10000; t = true; f = FinanceLib.fv(r, n, y, p, t); x = -10444600; - assertEquals("fv ", x, f); + assertDouble("fv ", x, f); r = 2; n = 12; y = 120; p = 12000; t = false; f = FinanceLib.fv(r, n, y, p, t); x = -6409178400d; - assertEquals("fv ", x, f); + assertDouble("fv ", x, f); r = 2; n = 12; y = 120; p = 12000; t = true; f = FinanceLib.fv(r, n, y, p, t); x = -6472951200d; - assertEquals("fv ", x, f); + 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 - assertEquals("fv ", x, f); + 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 - assertEquals("fv ", x, f); + assertDouble("fv ", x, f); } @@ -83,22 +83,22 @@ public class TestFinanceLib extends BaseTestNumeric { r = 1; v = new double[]{100, 200, 300, 400}; npv = FinanceLib.npv(r, v); x = 162.5; - assertEquals("npv ", x, npv); + 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; - assertEquals("npv ", x, npv); + assertDouble("npv ", x, npv); r = 12.33333; v = new double[]{1000, 0, -900, -7777.5765}; npv = FinanceLib.npv(r, v); x = 74.3742433377061; - assertEquals("npv ", x, npv); + 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; - assertEquals("npv ", x, npv); + assertDouble("npv ", x, npv); } @Test @@ -110,29 +110,29 @@ public class TestFinanceLib extends BaseTestNumeric { r = 0; n = 3; p = 2; f = 7; t = true; y = FinanceLib.pmt(r, n, p, f, t); x = -3; - assertEquals("pmt ", x, y); + 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; - assertEquals("pmt ", x, y); + 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; - assertEquals("pmt ", x, y); + 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; - assertEquals("pmt ", x, y); + assertDouble("pmt ", x, y); r = 2; n = 12; f = -6472951200d; p = 12000; t = true; y = FinanceLib.pmt(r, n, p, f, t); x = 120; - assertEquals("pmt ", x, y); + assertDouble("pmt ", x, y); } @Test @@ -144,38 +144,38 @@ public class TestFinanceLib extends BaseTestNumeric { r = 0; n = 3; y = 2; f = 7; t = true; f = FinanceLib.pv(r, n, y, f, t); x = -13; - assertEquals("pv ", x, f); + 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; - assertEquals("pv ", x, p); + 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; - assertEquals("pv ", x, p); + 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; - assertEquals("pv ", x, p); + 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; - assertEquals("pv ", x, p); + 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; - assertEquals("pv ", x, p); + assertDouble("pv ", x, p); r = 2; n = 12; y = 120; f = -6472951200d; t = true; p = FinanceLib.pv(r, n, y, f, t); x = 12000; - assertEquals("pv ", x, p); + assertDouble("pv ", x, p); } @@ -187,28 +187,28 @@ public class TestFinanceLib extends BaseTestNumeric { 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!?? - assertEquals("nper ", x, n); + 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; - assertEquals("nper ", x, n); + 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; - assertEquals("nper ", x, n); + 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; - assertEquals("nper ", x, n); + assertDouble("nper ", x, n); r = 2; y = 120; f = -6472951200d; p = 12000; t = true; n = FinanceLib.nper(r, y, p, f, t); x = 12; - assertEquals("nper ", x, n); + 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 index 0bfff626af..520cd435b1 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Financed} @@ -57,7 +57,7 @@ public final class TestFind { 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(); } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java index 462acd3115..9b2da6b1ec 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -34,15 +34,15 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public final class TestFixed { private HSSFCell cell11; private HSSFFormulaEvaluator evaluator; - @Before + @BeforeEach public void setUp() throws IOException { try (HSSFWorkbook wb = new HSSFWorkbook()) { HSSFSheet sheet = wb.createSheet("new sheet"); @@ -86,14 +86,14 @@ public final class TestFixed { // rounding propagation confirm("FIXED(99.9,0,TRUE)", "100"); } - + @Test public void testOptionalParams() { Fixed fixed = new Fixed(); ValueEval evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789)); 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()); @@ -113,17 +113,17 @@ public final class TestFixed { cell11.setCellFormula(formulaText); evaluator.clearAllCachedResultValues(); CellValue cv = evaluator.evaluate(cell11); - assertEquals("Wrong result type: " + cv.formatAsString(), CellType.STRING, cv.getCellType()); + 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("Wrong result type: " + cv.formatAsString(), - cv.getCellType() == CellType.ERROR - && cv.getErrorValue() == FormulaError.VALUE.getCode()); + 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 index a5efd75e2e..050b61d676 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests FIXED() as loaded from a test data spreadsheet. */ public class TestFixedFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index c441c82ade..271cba7d20 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFrequency.java @@ -16,14 +16,19 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - import static org.apache.poi.ss.formula.functions.Frequency.histogram; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +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) diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java b/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java index 50b57b3671..50fbf41cab 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestGeomean.java @@ -16,11 +16,17 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import org.apache.poi.ss.formula.eval.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.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: diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java index dac6dda140..d09810bd98 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Hex2Dec} @@ -44,13 +44,13 @@ public final class TestHex2Dec { private static void confirmValue(String msg, String number1, String expected) { ValueEval result = invokeValue(number1); assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test @@ -93,8 +93,7 @@ public final class TestHex2Dec { 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); + return new OperationEvaluationContext(workbookEvaluator, workbook, 0, 0, 0, null); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java index cbdbfa5043..8e6fb4573b 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIFFunctionFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; -import java.util.Collection; +import org.junit.jupiter.params.provider.Arguments; /** * Tests IF() as loaded from a test data spreadsheet.

*/ public class TestIFFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index abd265bdf6..2fc27bbdb2 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java @@ -19,14 +19,14 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for IPMT() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java index 4fcd937597..b9ba1ae580 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests ImReal() as loaded from a test data spreadsheet.

*/ public class TestImRealFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index cb03894316..a0ffeb2849 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests Imaginary() as loaded from a test data spreadsheet.

*/ public class TestImaginaryFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index fbb63dc0bd..bc44ab3c15 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; @@ -35,7 +35,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for the INDEX() function.

diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java index 6a543f3ff7..c477104ffb 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests INDEX() as loaded from a test data spreadsheet.

*/ public final class TestIndexFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index ea5ac9c7aa..7bd3025c1c 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java @@ -17,8 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; @@ -32,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for the INDIRECT() function.

@@ -175,35 +174,26 @@ public final class TestIndirect { // 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) { + private static void confirm(FormulaEvaluator fe, Cell cell, String formula, double expectedResult) { fe.clearAllCachedResultValues(); cell.setCellFormula(formula); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.NUMERIC) { - fail("expected numeric cell type but got " + cv.formatAsString()); - } + 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) { + + private static void confirm(FormulaEvaluator fe, Cell cell, String formula, ErrorEval expectedResult) { fe.clearAllCachedResultValues(); cell.setCellFormula(formula); CellValue cv = fe.evaluate(cell); - if (cv.getCellType() != CellType.ERROR) { - fail("expected error cell type but got " + cv.formatAsString()); - } + assertEquals(CellType.ERROR, cv.getCellType(), "expected error cell type but got " + cv.formatAsString()); int expCode = expectedResult.getErrorCode(); - if (cv.getErrorValue() != expCode) { - fail("Expected error '" + ErrorEval.getText(expCode) - + "' but got '" + cv.formatAsString() + "'."); - } + assertEquals(expCode, cv.getErrorValue(), "Expected error '" + ErrorEval.getText(expCode) + "' but got '" + cv.formatAsString() + "'."); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java index 5df83b43bd..8f7f15fffb 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests INDIRECT() as loaded from a test data spreadsheet.

@@ -29,8 +29,7 @@ import org.junit.runners.Parameterized.Parameters; * more easily. */ public final class TestIndirectFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 393ebb3710..e375051c12 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java @@ -19,7 +19,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFCell; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test for Excel function INTERCEPT() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java index 9dc7558485..3630f48b0e 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFCell; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Irr} @@ -40,28 +40,28 @@ public final class TestIrr { double[] incomes = {-4000d, 1200d, 1410d, 1875d, 1050d}; double irr = Irr.irr(incomes); double irrRounded = Math.round(irr * 1000d) / 1000d; - assertEquals("irr", 0.143d, irrRounded, 0); + 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("irr", 0.28d, irrRounded, 0); + assertEquals(0.28d, irrRounded, 0); incomes = new double[]{-10000d, 3400d, 6500d, 1000d}; irr = Irr.irr(incomes); irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", 0.05, irrRounded, 0); + assertEquals(0.05, irrRounded, 0); incomes = new double[]{100d, -10d, -110d}; irr = Irr.irr(incomes); irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", 0.1, irrRounded, 0); + assertEquals(0.1, irrRounded, 0); incomes = new double[]{-70000d, 12000, 15000}; irr = Irr.irr(incomes, -0.1); irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", -0.44, irrRounded, 0); + assertEquals(-0.44, irrRounded, 0); } @Test @@ -92,7 +92,6 @@ public final class TestIrr { HSSFSheet sheet = wb.getSheet("IRR-NPV"); HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); StringBuilder failures = new StringBuilder(); - 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++){ @@ -105,7 +104,6 @@ public final class TestIrr { if(failures.length() > 0) failures.append('\n'); failures.append("Row[" + (cellA.getRowIndex() + 1)+ "]: " + cellA.getCellFormula() + " "); failures.append(e.getMessage()); - failureCount++; } HSSFCell cellC = row.getCell(2); //IRR-NPV relationship: NPV(IRR(values), values) = 0 @@ -116,17 +114,15 @@ public final class TestIrr { if(failures.length() > 0) failures.append('\n'); failures.append("Row[" + (cellC.getRowIndex() + 1)+ "]: " + cellC.getCellFormula() + " "); failures.append(e.getMessage()); - failureCount++; } } - - assertEquals("IRR assertions failed", 0, failures.length()); + 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("Invalid formula result: " + cv, CellType.NUMERIC, cv.getCellType()); + 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 index 5d142c8ec6..989d88f474 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function ISBLANK() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java index a564f07b25..a96def2d7e 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java index 4350569aaa..6ff7be55a5 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.eval.BlankEval; import org.apache.poi.ss.formula.eval.BoolEval; @@ -25,7 +25,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function LEN() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java index 712ff361de..d14e9f6591 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -31,8 +31,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * LogicalFunction unit tests. @@ -44,7 +44,7 @@ public class TestLogicalFunction { private Cell cell1; private Cell cell2; - @Before + @BeforeEach public void setUp() throws IOException { try (Workbook wb = new HSSFWorkbook()) { buildWorkbook(wb); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java index 6432eb2f42..7552bf5af3 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; -import java.util.Collection; +import org.junit.jupiter.params.provider.Arguments; /** * Tests for logical ISxxx functions as loaded from a test data spreadsheet.

*/ public class TestLogicalFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index d3c27ce1d1..ad0a60ec9b 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests lookup functions (VLOOKUP, HLOOKUP, LOOKUP, MATCH) as loaded from a test data spreadsheet.

@@ -31,8 +31,7 @@ import org.junit.runners.Parameterized.Parameters; * more easily. */ public final class TestLookupFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 21ede8af66..8e172a3646 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java @@ -17,8 +17,9 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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; @@ -27,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for MATCH() @@ -52,9 +53,7 @@ public final class TestMatch { } private static void confirmInt(int expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - fail("Expected numeric result but had " + actualEval); - } + assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result but had " + actualEval); NumericValueEval nve = (NumericValueEval)actualEval; assertEquals(expected, nve.getNumberValue(), 0); } @@ -283,7 +282,7 @@ public final class TestMatch { confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - assertEquals("Should return #REF! for invalid match type", - ErrorEval.REF_INVALID, invokeMatch(new StringEval("Ben"), ae, MATCH_INVALID)); + 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 index cff3216107..ef7ee77195 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests Match functions as loaded from a test data spreadsheet.

@@ -29,8 +29,7 @@ import org.junit.runners.Parameterized.Parameters; * more easily. */ public final class TestMatchFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 22506bd00e..a5b0a53499 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java @@ -20,10 +20,10 @@ */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.poi.ss.formula.functions.XYNumericFunction.Accumulator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -37,22 +37,22 @@ public class TestMathX extends BaseTestNumeric { double d; d = MathX.acosh(0); - assertTrue("Acosh 0 is NaN", Double.isNaN(d)); + assertTrue( Double.isNaN(d), "Acosh 0 is NaN" ); d = MathX.acosh(1); - assertEquals("Acosh 1 ", 0, d); + assertDouble("Acosh 1 ", 0, d); d = MathX.acosh(-1); - assertTrue("Acosh -1 is NaN", Double.isNaN(d)); + assertTrue( Double.isNaN(d), "Acosh -1 is NaN" ); d = MathX.acosh(100); - assertEquals("Acosh 100 ", 5.298292366d, d); + assertDouble("Acosh 100 ", 5.298292366d, d); d = MathX.acosh(101.001); - assertEquals("Acosh 101.001 ", 5.308253091d, d); + assertDouble("Acosh 101.001 ", 5.308253091d, d); d = MathX.acosh(200000); - assertEquals("Acosh 200000 ", 12.89921983d, d); + assertDouble("Acosh 200000 ", 12.89921983d, d); } @@ -61,25 +61,25 @@ public class TestMathX extends BaseTestNumeric { double d; d = MathX.asinh(0); - assertEquals("asinh 0", d, 0); + assertDouble("asinh 0", d, 0); d = MathX.asinh(1); - assertEquals("asinh 1 ", 0.881373587, d); + assertDouble("asinh 1 ", 0.881373587, d); d = MathX.asinh(-1); - assertEquals("asinh -1 ", -0.881373587, d); + assertDouble("asinh -1 ", -0.881373587, d); d = MathX.asinh(-100); - assertEquals("asinh -100 ", -5.298342366, d); + assertDouble("asinh -100 ", -5.298342366, d); d = MathX.asinh(100); - assertEquals("asinh 100 ", 5.298342366, d); + assertDouble("asinh 100 ", 5.298342366, d); d = MathX.asinh(200000); - assertEquals("asinh 200000", 12.899219826096400, d); + assertDouble("asinh 200000", 12.899219826096400, d); d = MathX.asinh(-200000); - assertEquals("asinh -200000 ", -12.899223853137, d); + assertDouble("asinh -200000 ", -12.899223853137, d); } @@ -87,31 +87,31 @@ public class TestMathX extends BaseTestNumeric { public void testAtanh() { double d; d = MathX.atanh(0); - assertEquals("atanh 0", d, 0); + assertDouble("atanh 0", d, 0); d = MathX.atanh(1); - assertEquals("atanh 1 ", Double.POSITIVE_INFINITY, d); + assertDouble("atanh 1 ", Double.POSITIVE_INFINITY, d); d = MathX.atanh(-1); - assertEquals("atanh -1 ", Double.NEGATIVE_INFINITY, d); + assertDouble("atanh -1 ", Double.NEGATIVE_INFINITY, d); d = MathX.atanh(-100); - assertEquals("atanh -100 ", Double.NaN, d); + assertDouble("atanh -100 ", Double.NaN, d); d = MathX.atanh(100); - assertEquals("atanh 100 ", Double.NaN, d); + assertDouble("atanh 100 ", Double.NaN, d); d = MathX.atanh(200000); - assertEquals("atanh 200000", Double.NaN, d); + assertDouble("atanh 200000", Double.NaN, d); d = MathX.atanh(-200000); - assertEquals("atanh -200000 ", Double.NaN, d); + assertDouble("atanh -200000 ", Double.NaN, d); d = MathX.atanh(0.1); - assertEquals("atanh 0.1", 0.100335348, d); + assertDouble("atanh 0.1", 0.100335348, d); d = MathX.atanh(-0.1); - assertEquals("atanh -0.1 ", -0.100335348, d); + assertDouble("atanh -0.1 ", -0.100335348, d); } @@ -119,31 +119,31 @@ public class TestMathX extends BaseTestNumeric { public void testCosh() { double d; d = MathX.cosh(0); - assertEquals("cosh 0", 1, d); + assertDouble("cosh 0", 1, d); d = MathX.cosh(1); - assertEquals("cosh 1 ", 1.543080635, d); + assertDouble("cosh 1 ", 1.543080635, d); d = MathX.cosh(-1); - assertEquals("cosh -1 ", 1.543080635, d); + assertDouble("cosh -1 ", 1.543080635, d); d = MathX.cosh(-100); - assertEquals("cosh -100 ", 1.344058570908070E+43, d); + assertDouble("cosh -100 ", 1.344058570908070E+43, d); d = MathX.cosh(100); - assertEquals("cosh 100 ", 1.344058570908070E+43, d); + assertDouble("cosh 100 ", 1.344058570908070E+43, d); d = MathX.cosh(15); - assertEquals("cosh 15", 1634508.686, d); + assertDouble("cosh 15", 1634508.686, d); d = MathX.cosh(-15); - assertEquals("cosh -15 ", 1634508.686, d); + assertDouble("cosh -15 ", 1634508.686, d); d = MathX.cosh(0.1); - assertEquals("cosh 0.1", 1.005004168, d); + assertDouble("cosh 0.1", 1.005004168, d); d = MathX.cosh(-0.1); - assertEquals("cosh -0.1 ", 1.005004168, d); + assertDouble("cosh -0.1 ", 1.005004168, d); } @@ -151,31 +151,31 @@ public class TestMathX extends BaseTestNumeric { public void testTanh() { double d; d = MathX.tanh(0); - assertEquals("tanh 0", 0, d); + assertDouble("tanh 0", 0, d); d = MathX.tanh(1); - assertEquals("tanh 1 ", 0.761594156, d); + assertDouble("tanh 1 ", 0.761594156, d); d = MathX.tanh(-1); - assertEquals("tanh -1 ", -0.761594156, d); + assertDouble("tanh -1 ", -0.761594156, d); d = MathX.tanh(-100); - assertEquals("tanh -100 ", -1, d); + assertDouble("tanh -100 ", -1, d); d = MathX.tanh(100); - assertEquals("tanh 100 ", 1, d); + assertDouble("tanh 100 ", 1, d); d = MathX.tanh(15); - assertEquals("tanh 15", 1, d); + assertDouble("tanh 15", 1, d); d = MathX.tanh(-15); - assertEquals("tanh -15 ", -1, d); + assertDouble("tanh -15 ", -1, d); d = MathX.tanh(0.1); - assertEquals("tanh 0.1", 0.099667995, d); + assertDouble("tanh 0.1", 0.099667995, d); d = MathX.tanh(-0.1); - assertEquals("tanh -0.1 ", -0.099667995, d); + assertDouble("tanh -0.1 ", -0.099667995, d); } @@ -189,11 +189,11 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; double m = MathX.max(d); - assertEquals("Max ", 20.1, m); + assertDouble("Max ", 20.1, m); d = new double[1000]; m = MathX.max(d); - assertEquals("Max ", 0, m); + 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; @@ -201,7 +201,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Max ", 20.1, m); + 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; @@ -210,7 +210,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Max ", -1.1, m); + assertDouble("Max ", -1.1, m); } @@ -224,7 +224,7 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; double m = MathX.min(d); - assertEquals("Min ", 0, m); + assertDouble("Min ", 0, m); d = new double[20]; d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; @@ -234,11 +234,11 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; m = MathX.min(d); - assertEquals("Min ", 1.1, m); + assertDouble("Min ", 1.1, m); d = new double[1000]; m = MathX.min(d); - assertEquals("Min ", 0, m); + 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; @@ -246,7 +246,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Min ", -19.1, m); + 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; @@ -255,20 +255,20 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Min ", -20.1, m); + assertDouble("Min ", -20.1, m); } @Test public void testProduct() { - assertEquals("Product ", 0, MathX.product(null)); - assertEquals("Product ", 0, MathX.product(new double[] {})); - assertEquals("Product ", 0, MathX.product(new double[] {1, 0})); + assertDouble("Product ", 0, MathX.product(null)); + assertDouble("Product ", 0, MathX.product(new double[] {})); + assertDouble("Product ", 0, MathX.product(new double[] {1, 0})); - assertEquals("Product ", 1, MathX.product(new double[] { 1 })); - assertEquals("Product ", 1, MathX.product(new double[] { 1, 1 })); - assertEquals("Product ", 10, MathX.product(new double[] { 10, 1 })); - assertEquals("Product ", -2, MathX.product(new double[] { 2, -1 })); - assertEquals("Product ", 99988000209999d, MathX.product(new double[] { 99999, 99999, 9999 })); + 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; @@ -278,7 +278,7 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; double m = MathX.product(d); - assertEquals("Product ", 0, m); + assertDouble("Product ", 0, m); d = new double[20]; d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; @@ -288,11 +288,11 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; m = MathX.product(d); - assertEquals("Product ", 3459946360003355534d, m); + assertDouble("Product ", 3459946360003355534d, m); d = new double[1000]; m = MathX.product(d); - assertEquals("Product ", 0, m); + assertDouble("Product ", 0, m); d = new double[20]; d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; @@ -301,29 +301,29 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Product ", 3459946360003355534d, m); + assertDouble("Product ", 3459946360003355534d, m); } @Test public void testMod() { //example from Excel help - assertEquals(1.0, MathX.mod(3, 2)); - assertEquals(1.0, MathX.mod(-3, 2)); - assertEquals(-1.0, MathX.mod(3, -2)); - assertEquals(-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(-1.0, MathX.mod(-3, -2)); - assertEquals(0.0, MathX.mod(0, 2)); - assertEquals(Double.NaN, MathX.mod(3, 0)); - assertEquals(1.4, MathX.mod(3.4, 2)); - assertEquals(-1.4, MathX.mod(-3.4, -2)); - assertEquals(0.6000000000000001, MathX.mod(-3.4, 2.0));// should actually be 0.6 - assertEquals(-0.6000000000000001, MathX.mod(3.4, -2.0));// should actually be -0.6 - assertEquals(3.0, MathX.mod(3, Double.MAX_VALUE)); - assertEquals(2.0, MathX.mod(Double.MAX_VALUE, 3)); + 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 - assertEquals(1.0, MathX.mod(13, 12)); + assertDouble(1.0, MathX.mod(13, 12)); } @Test @@ -331,47 +331,47 @@ public class TestMathX extends BaseTestNumeric { int n=100; int k=50; double d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1.00891344545564E29, d); + assertDouble("NChooseK ", 1.00891344545564E29, d); n = -1; k = 1; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); + assertDouble("NChooseK ", Double.NaN, d); n = 1; k = -1; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); + assertDouble("NChooseK ", Double.NaN, d); n = 0; k = 1; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); + assertDouble("NChooseK ", Double.NaN, d); n = 1; k = 0; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1, d); + assertDouble("NChooseK ", 1, d); n = 10; k = 9; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 10, d); + assertDouble("NChooseK ", 10, d); n = 10; k = 10; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1, d); + assertDouble("NChooseK ", 1, d); n = 10; k = 1; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 10, d); + assertDouble("NChooseK ", 10, d); n = 1000; k = 1; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1000, d); // awesome ;) + assertDouble("NChooseK ", 1000, d); // awesome ;) n = 1000; k = 2; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 499500, d); // awesome ;) + assertDouble("NChooseK ", 499500, d); // awesome ;) n = 13; k = 7; d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1716, d); + assertDouble("NChooseK ", 1716, d); } @@ -383,48 +383,48 @@ public class TestMathX extends BaseTestNumeric { double d; - assertEquals("Sign ", minus, MathX.sign(minus)); - assertEquals("Sign ", plus, MathX.sign(plus)); - assertEquals("Sign ", zero, MathX.sign(zero)); + assertDouble("Sign ", minus, MathX.sign(minus)); + assertDouble("Sign ", plus, MathX.sign(plus)); + assertDouble("Sign ", zero, MathX.sign(zero)); d = 0; - assertEquals("Sign ", zero, MathX.sign(d)); + assertDouble("Sign ", zero, MathX.sign(d)); d = -1.000001; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = -.000001; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = -1E-200; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = Double.NEGATIVE_INFINITY; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = -200.11; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = -2000000000000.11; - assertEquals("Sign ", minus, MathX.sign(d)); + assertDouble("Sign ", minus, MathX.sign(d)); d = 1.000001; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); d = .000001; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); d = 1E-200; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); d = Double.POSITIVE_INFINITY; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); d = 200.11; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); d = 2000000000000.11; - assertEquals("Sign ", plus, MathX.sign(d)); + assertDouble("Sign ", plus, MathX.sign(d)); } @@ -432,31 +432,31 @@ public class TestMathX extends BaseTestNumeric { public void testSinh() { double d; d = MathX.sinh(0); - assertEquals("sinh 0", 0, d); + assertDouble("sinh 0", 0, d); d = MathX.sinh(1); - assertEquals("sinh 1 ", 1.175201194, d); + assertDouble("sinh 1 ", 1.175201194, d); d = MathX.sinh(-1); - assertEquals("sinh -1 ", -1.175201194, d); + assertDouble("sinh -1 ", -1.175201194, d); d = MathX.sinh(-100); - assertEquals("sinh -100 ", -1.344058570908070E+43, d); + assertDouble("sinh -100 ", -1.344058570908070E+43, d); d = MathX.sinh(100); - assertEquals("sinh 100 ", 1.344058570908070E+43, d); + assertDouble("sinh 100 ", 1.344058570908070E+43, d); d = MathX.sinh(15); - assertEquals("sinh 15", 1634508.686, d); + assertDouble("sinh 15", 1634508.686, d); d = MathX.sinh(-15); - assertEquals("sinh -15 ", -1634508.686, d); + assertDouble("sinh -15 ", -1634508.686, d); d = MathX.sinh(0.1); - assertEquals("sinh 0.1", 0.10016675, d); + assertDouble("sinh 0.1", 0.10016675, d); d = MathX.sinh(-0.1); - assertEquals("sinh -0.1 ", -0.10016675, d); + assertDouble("sinh -0.1 ", -0.10016675, d); } @@ -470,11 +470,11 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; double s = MathX.sum(d); - assertEquals("Sum ", 212, s); + assertDouble("Sum ", 212, s); d = new double[1000]; s = MathX.sum(d); - assertEquals("Sum ", 0, s); + 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; @@ -482,7 +482,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Sum ", 10, s); + 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; @@ -490,7 +490,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Sum ", -212, s); + assertDouble("Sum ", -212, s); } @@ -504,11 +504,11 @@ public class TestMathX extends BaseTestNumeric { d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; double s = MathX.sumsq(d); - assertEquals("Sumsq ", 2912.2, s); + assertDouble("Sumsq ", 2912.2, s); d = new double[1000]; s = MathX.sumsq(d); - assertEquals("Sumsq ", 0, s); + 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; @@ -516,7 +516,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Sumsq ", 2912.2, s); + 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; @@ -524,7 +524,7 @@ public class TestMathX extends BaseTestNumeric { 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); - assertEquals("Sumsq ", 2912.2, s); + assertDouble("Sumsq ", 2912.2, s); } @Test @@ -534,27 +534,27 @@ public class TestMathX extends BaseTestNumeric { n = 0; s = MathX.factorial(n); - assertEquals("Factorial ", 1, s); + assertDouble("Factorial ", 1, s); n = 1; s = MathX.factorial(n); - assertEquals("Factorial ", 1, s); + assertDouble("Factorial ", 1, s); n = 10; s = MathX.factorial(n); - assertEquals("Factorial ", 3628800, s); + assertDouble("Factorial ", 3628800, s); n = 99; s = MathX.factorial(n); - assertEquals("Factorial ", 9.33262154439E+155, s); + assertDouble("Factorial ", 9.33262154439E+155, s); n = -1; s = MathX.factorial(n); - assertEquals("Factorial ", Double.NaN, s); + assertDouble("Factorial ", Double.NaN, s); n = Integer.MAX_VALUE; s = MathX.factorial(n); - assertEquals("Factorial ", Double.POSITIVE_INFINITY, s); + assertDouble("Factorial ", Double.POSITIVE_INFINITY, s); } @Test @@ -651,7 +651,7 @@ public class TestMathX extends BaseTestNumeric { for (int i = 0; i < xarr.length; i++) { result += acc.accumulate(xarr[i], yarr[i]); } - assertEquals(expectedResult, result); + assertDouble(expectedResult, result); } @Test @@ -660,70 +660,70 @@ public class TestMathX extends BaseTestNumeric { int p; d = 0; p = 0; - assertEquals("round ", 0, MathX.round(d, p)); + assertDouble("round ", 0, MathX.round(d, p)); d = 10; p = 0; - assertEquals("round ", 10, MathX.round(d, p)); + assertDouble("round ", 10, MathX.round(d, p)); d = 123.23; p = 0; - assertEquals("round ", 123, MathX.round(d, p)); + assertDouble("round ", 123, MathX.round(d, p)); d = -123.23; p = 0; - assertEquals("round ", -123, MathX.round(d, p)); + assertDouble("round ", -123, MathX.round(d, p)); d = 123.12; p = 2; - assertEquals("round ", 123.12, MathX.round(d, p)); + assertDouble("round ", 123.12, MathX.round(d, p)); d = 88.123459; p = 5; - assertEquals("round ", 88.12346, MathX.round(d, p)); + assertDouble("round ", 88.12346, MathX.round(d, p)); d = 0; p = 2; - assertEquals("round ", 0, MathX.round(d, p)); + assertDouble("round ", 0, MathX.round(d, p)); d = 0; p = -1; - assertEquals("round ", 0, MathX.round(d, p)); + assertDouble("round ", 0, MathX.round(d, p)); d = 0.01; p = -1; - assertEquals("round ", 0, MathX.round(d, p)); + assertDouble("round ", 0, MathX.round(d, p)); d = 123.12; p = -2; - assertEquals("round ", 100, MathX.round(d, p)); + assertDouble("round ", 100, MathX.round(d, p)); d = 88.123459; p = -3; - assertEquals("round ", 0, MathX.round(d, p)); + assertDouble("round ", 0, MathX.round(d, p)); d = 49.00000001; p = -1; - assertEquals("round ", 50, MathX.round(d, p)); + assertDouble("round ", 50, MathX.round(d, p)); d = 149.999999; p = -2; - assertEquals("round ", 100, MathX.round(d, p)); + assertDouble("round ", 100, MathX.round(d, p)); d = 150.0; p = -2; - assertEquals("round ", 200, MathX.round(d, p)); + assertDouble("round ", 200, MathX.round(d, p)); d = 2162.615d; p = 2; - assertEquals("round ", 2162.62d, MathX.round(d, p)); + assertDouble("round ", 2162.62d, MathX.round(d, p)); d = 0.049999999999999975d; p = 2; - assertEquals("round ", 0.05d, MathX.round(d, p)); + assertDouble("round ", 0.05d, MathX.round(d, p)); d = 0.049999999999999975d; p = 1; - assertEquals("round ", 0.1d, MathX.round(d, p)); + assertDouble("round ", 0.1d, MathX.round(d, p)); d = Double.NaN; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); + assertDouble("round ", Double.NaN, MathX.round(d, p)); d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); + assertDouble("round ", Double.NaN, MathX.round(d, p)); d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); + assertDouble("round ", Double.NaN, MathX.round(d, p)); d = Double.MAX_VALUE; p = 1; - assertEquals("round ", Double.MAX_VALUE, MathX.round(d, p)); + assertDouble("round ", Double.MAX_VALUE, MathX.round(d, p)); d = Double.MIN_VALUE; p = 1; - assertEquals("round ", 0.0d, MathX.round(d, p)); + assertDouble("round ", 0.0d, MathX.round(d, p)); } @Test @@ -732,70 +732,70 @@ public class TestMathX extends BaseTestNumeric { int p; d = 0; p = 0; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0, MathX.roundDown(d, p)); d = 10; p = 0; - assertEquals("roundDown ", 10, MathX.roundDown(d, p)); + assertDouble("roundDown ", 10, MathX.roundDown(d, p)); d = 123.99; p = 0; - assertEquals("roundDown ", 123, MathX.roundDown(d, p)); + assertDouble("roundDown ", 123, MathX.roundDown(d, p)); d = -123.99; p = 0; - assertEquals("roundDown ", -123, MathX.roundDown(d, p)); + assertDouble("roundDown ", -123, MathX.roundDown(d, p)); d = 123.99; p = 2; - assertEquals("roundDown ", 123.99, MathX.roundDown(d, p)); + assertDouble("roundDown ", 123.99, MathX.roundDown(d, p)); d = 88.123459; p = 5; - assertEquals("roundDown ", 88.12345, MathX.roundDown(d, p)); + assertDouble("roundDown ", 88.12345, MathX.roundDown(d, p)); d = 0; p = 2; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0, MathX.roundDown(d, p)); d = 0; p = -1; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0, MathX.roundDown(d, p)); d = 0.01; p = -1; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0, MathX.roundDown(d, p)); d = 199.12; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); + assertDouble("roundDown ", 100, MathX.roundDown(d, p)); d = 88.123459; p = -3; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0, MathX.roundDown(d, p)); d = 99.00000001; p = -1; - assertEquals("roundDown ", 90, MathX.roundDown(d, p)); + assertDouble("roundDown ", 90, MathX.roundDown(d, p)); d = 100.00001; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); + assertDouble("roundDown ", 100, MathX.roundDown(d, p)); d = 150.0; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); + assertDouble("roundDown ", 100, MathX.roundDown(d, p)); d = 0.0499999999999975d; p = 2; - assertEquals("roundDown ", 0.04d, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0.04d, MathX.roundDown(d, p)); d = 0.049999999999999975d; p = 1; - assertEquals("roundDown ", 0.0d, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0.0d, MathX.roundDown(d, p)); d = Double.NaN; p = 1; - assertEquals("roundDown ", Double.NaN, MathX.roundDown(d, p)); + assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("roundDown ", Double.NaN, MathX.roundDown(d, p)); + assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("roundDown ", Double.NaN, MathX.roundDown(d, p)); + assertDouble("roundDown ", Double.NaN, MathX.roundDown(d, p)); d = Double.MAX_VALUE; p = 1; - assertEquals("roundDown ", Double.MAX_VALUE, MathX.roundDown(d, p)); + assertDouble("roundDown ", Double.MAX_VALUE, MathX.roundDown(d, p)); d = Double.MIN_VALUE; p = 1; - assertEquals("roundDown ", 0.0d, MathX.roundDown(d, p)); + assertDouble("roundDown ", 0.0d, MathX.roundDown(d, p)); d = 3987 * 0.2; p = 2; - assertEquals("roundDown ", 797.40, MathX.round(d, p)); + assertDouble("roundDown ", 797.40, MathX.round(d, p)); } @Test @@ -804,75 +804,75 @@ public class TestMathX extends BaseTestNumeric { int p; d = 0; p = 0; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0, MathX.roundUp(d, p)); d = 10; p = 0; - assertEquals("roundUp ", 10, MathX.roundUp(d, p)); + assertDouble("roundUp ", 10, MathX.roundUp(d, p)); d = 123.23; p = 0; - assertEquals("roundUp ", 124, MathX.roundUp(d, p)); + assertDouble("roundUp ", 124, MathX.roundUp(d, p)); d = -123.23; p = 0; - assertEquals("roundUp ", -124, MathX.roundUp(d, p)); + assertDouble("roundUp ", -124, MathX.roundUp(d, p)); d = 123.12; p = 2; - assertEquals("roundUp ", 123.12, MathX.roundUp(d, p)); + assertDouble("roundUp ", 123.12, MathX.roundUp(d, p)); d = 88.123459; p = 5; - assertEquals("roundUp ", 88.12346, MathX.roundUp(d, p)); + assertDouble("roundUp ", 88.12346, MathX.roundUp(d, p)); d = 0; p = 2; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0, MathX.roundUp(d, p)); d = 0; p = -1; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0, MathX.roundUp(d, p)); d = 0.01; p = -1; - assertEquals("roundUp ", 10, MathX.roundUp(d, p)); + assertDouble("roundUp ", 10, MathX.roundUp(d, p)); d = 123.12; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); + assertDouble("roundUp ", 200, MathX.roundUp(d, p)); d = 88.123459; p = -3; - assertEquals("roundUp ", 1000, MathX.roundUp(d, p)); + assertDouble("roundUp ", 1000, MathX.roundUp(d, p)); d = 49.00000001; p = -1; - assertEquals("roundUp ", 50, MathX.roundUp(d, p)); + assertDouble("roundUp ", 50, MathX.roundUp(d, p)); d = 149.999999; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); + assertDouble("roundUp ", 200, MathX.roundUp(d, p)); d = 150.0; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); + assertDouble("roundUp ", 200, MathX.roundUp(d, p)); d = 0.049999999999999975d; p = 2; - assertEquals("roundUp ", 0.05d, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0.05d, MathX.roundUp(d, p)); d = 0.049999999999999975d; p = 1; - assertEquals("roundUp ", 0.1d, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0.1d, MathX.roundUp(d, p)); d = Double.NaN; p = 1; - assertEquals("roundUp ", Double.NaN, MathX.roundUp(d, p)); + assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("roundUp ", Double.NaN, MathX.roundUp(d, p)); + assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("roundUp ", Double.NaN, MathX.roundUp(d, p)); + assertDouble("roundUp ", Double.NaN, MathX.roundUp(d, p)); d = Double.MAX_VALUE; p = 1; - assertEquals("roundUp ", Double.MAX_VALUE, MathX.roundUp(d, p)); + 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; - assertEquals("roundUp ", 0.0d, MathX.roundUp(d, p)); + assertDouble("roundUp ", 0.0d, MathX.roundUp(d, p)); d = 2.2259157957E-308; p = 1; - assertEquals("roundUp ", 0.1d, MathX.roundUp(d, p)); + 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; - assertEquals("roundUp ", 797.40, MathX.roundUp(d, p)); + assertDouble("roundUp ", 797.40, MathX.roundUp(d, p)); } @Test @@ -881,84 +881,84 @@ public class TestMathX extends BaseTestNumeric { double s; d = 0; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); + assertDouble("ceiling ", 0, MathX.ceiling(d, s)); d = 1; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); + assertDouble("ceiling ", 0, MathX.ceiling(d, s)); d = 0; s = 1; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); + assertDouble("ceiling ", 0, MathX.ceiling(d, s)); d = -1; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); + assertDouble("ceiling ", 0, MathX.ceiling(d, s)); d = 0; s = -1; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); + assertDouble("ceiling ", 0, MathX.ceiling(d, s)); d = 10; s = 1.11; - assertEquals("ceiling ", 11.1, MathX.ceiling(d, s)); + assertDouble("ceiling ", 11.1, MathX.ceiling(d, s)); d = 11.12333; s = 0.03499; - assertEquals("ceiling ", 11.12682, MathX.ceiling(d, s)); + assertDouble("ceiling ", 11.12682, MathX.ceiling(d, s)); d = -11.12333; s = 0.03499; - assertEquals("ceiling ", Double.NaN, MathX.ceiling(d, s)); + assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); d = 11.12333; s = -0.03499; - assertEquals("ceiling ", Double.NaN, MathX.ceiling(d, s)); + assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); d = -11.12333; s = -0.03499; - assertEquals("ceiling ", -11.12682, MathX.ceiling(d, s)); + assertDouble("ceiling ", -11.12682, MathX.ceiling(d, s)); d = 100; s = 0.001; - assertEquals("ceiling ", 100, MathX.ceiling(d, s)); + assertDouble("ceiling ", 100, MathX.ceiling(d, s)); d = -0.001; s = -9.99; - assertEquals("ceiling ", -9.99, MathX.ceiling(d, s)); + assertDouble("ceiling ", -9.99, MathX.ceiling(d, s)); d = 4.42; s = 0.05; - assertEquals("ceiling ", 4.45, MathX.ceiling(d, s)); + assertDouble("ceiling ", 4.45, MathX.ceiling(d, s)); d = 0.05; s = 4.42; - assertEquals("ceiling ", 4.42, MathX.ceiling(d, s)); + assertDouble("ceiling ", 4.42, MathX.ceiling(d, s)); d = 0.6666; s = 3.33; - assertEquals("ceiling ", 3.33, MathX.ceiling(d, s)); + assertDouble("ceiling ", 3.33, MathX.ceiling(d, s)); d = 2d/3; s = 3.33; - assertEquals("ceiling ", 3.33, MathX.ceiling(d, s)); + 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; - assertEquals("ceiling ", 22.3, MathX.ceiling(d, s)); + assertDouble("ceiling ", 22.3, MathX.ceiling(d, s)); d = 22.25; s = 0.5; - assertEquals("ceiling ", 22.5, MathX.ceiling(d, s)); + assertDouble("ceiling ", 22.5, MathX.ceiling(d, s)); d = 22.25; s = 1; - assertEquals("ceiling ", 23, MathX.ceiling(d, s)); + assertDouble("ceiling ", 23, MathX.ceiling(d, s)); d = 22.25; s = 10; - assertEquals("ceiling ", 30, MathX.ceiling(d, s)); + assertDouble("ceiling ", 30, MathX.ceiling(d, s)); d = 22.25; s = 20; - assertEquals("ceiling ", 40, MathX.ceiling(d, s)); + assertDouble("ceiling ", 40, MathX.ceiling(d, s)); d = -22.25; s = -0.1; - assertEquals("ceiling ", -22.3, MathX.ceiling(d, s)); + assertDouble("ceiling ", -22.3, MathX.ceiling(d, s)); d = -22.25; s = -1; - assertEquals("ceiling ", -23, MathX.ceiling(d, s)); + assertDouble("ceiling ", -23, MathX.ceiling(d, s)); d = -22.25; s = -5; - assertEquals("ceiling ", -25, MathX.ceiling(d, s)); + assertDouble("ceiling ", -25, MathX.ceiling(d, s)); d = 22.25; s = 1; - assertEquals("ceiling ", 23, MathX.ceiling(d, s)); + assertDouble("ceiling ", 23, MathX.ceiling(d, s)); d = 22.25; s = -1; - assertEquals("ceiling ", Double.NaN, MathX.ceiling(d, s)); + assertDouble("ceiling ", Double.NaN, MathX.ceiling(d, s)); d = -22.25; s = 1; - assertEquals("ceiling ", -22, MathX.ceiling(d, s)); // returns an error in Excel 2007 & earlier + assertDouble("ceiling ", -22, MathX.ceiling(d, s)); // returns an error in Excel 2007 & earlier d = -22.25; s = -1; - assertEquals("ceiling ", -23, MathX.ceiling(d, s)); + 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; - assertEquals("ceiling ", -11.09183, MathX.ceiling(d, s)); + assertDouble("ceiling ", -11.09183, MathX.ceiling(d, s)); } @Test @@ -967,69 +967,69 @@ public class TestMathX extends BaseTestNumeric { double s; d = 0; s = 0; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = 1; s = 0; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); + assertDouble("floor ", Double.NaN, MathX.floor(d, s)); d = 0; s = 1; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = -1; s = 0; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); + assertDouble("floor ", Double.NaN, MathX.floor(d, s)); d = 0; s = -1; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = 10; s = 1.11; - assertEquals("floor ", 9.99, MathX.floor(d, s)); + assertDouble("floor ", 9.99, MathX.floor(d, s)); d = 11.12333; s = 0.03499; - assertEquals("floor ", 11.09183, MathX.floor(d, s)); + assertDouble("floor ", 11.09183, MathX.floor(d, s)); d = -11.12333; s = 0.03499; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); + assertDouble("floor ", Double.NaN, MathX.floor(d, s)); d = 11.12333; s = -0.03499; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); + assertDouble("floor ", Double.NaN, MathX.floor(d, s)); d = -11.12333; s = -0.03499; - assertEquals("floor ", -11.09183, MathX.floor(d, s)); + assertDouble("floor ", -11.09183, MathX.floor(d, s)); d = 100; s = 0.001; - assertEquals("floor ", 100, MathX.floor(d, s)); + assertDouble("floor ", 100, MathX.floor(d, s)); d = -0.001; s = -9.99; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = 4.42; s = 0.05; - assertEquals("floor ", 4.4, MathX.floor(d, s)); + assertDouble("floor ", 4.4, MathX.floor(d, s)); d = 0.05; s = 4.42; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = 0.6666; s = 3.33; - assertEquals("floor ", 0, MathX.floor(d, s)); + assertDouble("floor ", 0, MathX.floor(d, s)); d = 2d/3; s = 3.33; - assertEquals("floor ", 0, MathX.floor(d, s)); + 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; - assertEquals("floor ", 2, MathX.floor(d, s)); + assertDouble("floor ", 2, MathX.floor(d, s)); d = -2.5; s = -2; - assertEquals("floor ", -2, MathX.floor(d, s)); + assertDouble("floor ", -2, MathX.floor(d, s)); d = 2.5; s = -2; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); + assertDouble("floor ", Double.NaN, MathX.floor(d, s)); d = 1.58; s = 0.1; - assertEquals("floor ", 1.5, MathX.floor(d, s)); + assertDouble("floor ", 1.5, MathX.floor(d, s)); d = 0.234; s = 0.01; - assertEquals("floor ", 0.23, MathX.floor(d, s)); + assertDouble("floor ", 0.23, MathX.floor(d, s)); // see bug 62839 d = -123; s = 10; - assertEquals("floor ", -130, MathX.floor(d, s)); + 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 index e141eff915..e1641528c3 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.eval.AreaEval; import org.apache.poi.ss.formula.eval.BlankEval; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function MID() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java index 5a5d123fff..9eabaa44a6 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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; @@ -30,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link org.apache.poi.ss.formula.functions.Mirr} @@ -51,28 +51,28 @@ public final class TestMirr { double[] values = {-120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; // MIRR should not failed with these parameters mirrValue = mirr.evaluate(values); - assertEquals("mirr", 0.126094130366, mirrValue, 0.0000000001); + 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("mirr", 0.18736225093, mirrValue, 0.0000000001); + 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("mirr", 0.07039493966, mirrValue, 0.0000000001); + 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("mirr", -1, mirrValue, 0.0); + assertEquals(-1, mirrValue, 0.0); } @@ -83,13 +83,9 @@ public final class TestMirr { double reinvestRate = 0.05; double financeRate = 0.08; double[] incomes = {120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; - try { - mirr.evaluate(incomes); - } catch (EvaluationException e) { - assertEquals(ErrorEval.DIV_ZERO, e.getErrorEval()); - return; - } - fail("MIRR should failed with all these positives values"); + + EvaluationException e = assertThrows(EvaluationException.class, () -> mirr.evaluate(incomes)); + assertEquals(ErrorEval.DIV_ZERO, e.getErrorEval()); } @Test @@ -141,13 +137,13 @@ public final class TestMirr { CellValue cv = fe.evaluate(cellA); assertEquals(ErrorEval.DIV_ZERO.getErrorCode(), cv.getErrorValue()); - assertEquals("IRR assertions failed", 0, failureCount); + 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("Invalid formula result: " + cv, CellType.NUMERIC, cv.getCellType()); + 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 index a03772086b..c077e47aaf 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestMultiOperandNumericFunction.java @@ -17,15 +17,15 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; public class TestMultiOperandNumericFunction { @@ -36,7 +36,7 @@ public class TestMultiOperandNumericFunction { protected double evaluate(double[] values) throws EvaluationException { return 0; } - + }; assertEquals(SpreadsheetVersion.EXCEL2007.getMaxFunctionArgs(), fun.getMaxNumOperands()); } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java index ec5553d84c..d2a82e2de1 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link FinanceFunction#NPER} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java index 4df5bc898d..c51158e959 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFCell; @@ -26,7 +26,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Npv} @@ -91,7 +91,7 @@ public final class TestNpv { } } - assertEquals("IRR evaluations failed", 0, failureCount); + assertEquals(0, failureCount, "IRR evaluations failed"); } private static void assertFormulaResult(CellValue cv, HSSFCell cell){ diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java index b496f26ef9..26cc445394 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link org.apache.poi.ss.formula.functions.Oct2Dec} @@ -40,13 +40,13 @@ public final class TestOct2Dec { private static void confirmValue(String msg, String number1, String expected) { ValueEval result = invokeValue(number1); assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java index ff18f417da..293796867e 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java @@ -17,10 +17,9 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -31,7 +30,9 @@ 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.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests for OFFSET function implementation @@ -40,42 +41,21 @@ import org.junit.Test; */ public final class TestOffset { - private static void confirmDoubleConvert(double doubleVal, int expected) { - try { - assertEquals(expected, Offset.evaluateIntArg(new NumberEval(doubleVal), -1, -1)); - } catch (EvaluationException e) { - fail("Unexpected error '" + e.getErrorEval() + "'."); - } - } /** * 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. */ - @Test - public void testDoubleConversion() { - - confirmDoubleConvert(100.09, 100); - confirmDoubleConvert(100.01, 100); - confirmDoubleConvert(100.00, 100); - confirmDoubleConvert(99.99, 99); - - confirmDoubleConvert(+2.01, +2); - confirmDoubleConvert(+2.00, +2); - confirmDoubleConvert(+1.99, +1); - confirmDoubleConvert(+1.01, +1); - confirmDoubleConvert(+1.00, +1); - confirmDoubleConvert(+0.99, 0); - confirmDoubleConvert(+0.01, 0); - confirmDoubleConvert( 0.00, 0); - confirmDoubleConvert(-0.01, -1); - confirmDoubleConvert(-0.99, -1); - confirmDoubleConvert(-1.00, -1); - confirmDoubleConvert(-1.01, -2); - confirmDoubleConvert(-1.99, -2); - confirmDoubleConvert(-2.00, -2); - confirmDoubleConvert(-2.01, -3); + @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" + }) + public void testDoubleConversion(double doubleVal, int expected) throws EvaluationException { + assertEquals(expected, Offset.evaluateIntArg(new NumberEval(doubleVal), -1, -1)); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java index e18e87b417..3ecffc04c3 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java @@ -19,14 +19,14 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for PPMT() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java index 0e4bd8224b..8a251707a7 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java @@ -17,14 +17,16 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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 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.Test; +import org.junit.jupiter.api.Test; public final class TestPmt { @@ -40,9 +42,7 @@ public final class TestPmt { */ private static NumberEval invokeNormal(ValueEval[] args) { ValueEval ev = invoke(args); - if(ev instanceof ErrorEval) { - fail("Normal evaluation failed with error code: " + ev); - } + assertFalse(ev instanceof ErrorEval, "Normal evaluation failed with error code: " + ev); return (NumberEval) ev; } @@ -74,9 +74,7 @@ public final class TestPmt { ValueEval ev = invoke(args); if(ev instanceof ErrorEval) { ErrorEval err = (ErrorEval) ev; - if(err.getErrorCode() == FormulaError.VALUE.getCode()) { - fail("Identified bug 44691"); - } + 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 index 9f21aa87f9..d8838e2c78 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function POISSON(x,mean,cumulative) diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java b/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java index e4af3bd866..9dce846c87 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestProduct.java @@ -21,10 +21,10 @@ 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.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestProduct { @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java index fc4fa001d8..b636e30811 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java @@ -16,13 +16,13 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Quotient} @@ -38,13 +38,13 @@ public class TestQuotient { private static void confirmValue(String msg, String numerator, String denominator, String expected) { ValueEval result = invokeValue(numerator, denominator); assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); + 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(msg, numError, result); + assertEquals(numError, result, msg); } @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java index 5f33111a34..0406d72ab8 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests QUOTIENT() as loaded from a test data spreadsheet.

*/ public class TestQuotientFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index a83f8b8de8..70923618fa 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java @@ -19,7 +19,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFCell; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for RANK() @@ -57,15 +57,15 @@ public final class TestRank { for(int rownum = 1; rownum<= 10; rownum ++){ HSSFCell cellD = example3.getRow(rownum).getCell(3); double cachedResultD = cellD.getNumericCellValue(); //cached formula result - assertEquals(new CellReference(cellD).formatAsString(), cachedResultD, fe.evaluate(cellD).getNumberValue(), 0); + 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(new CellReference(cellE).formatAsString(), cachedResultE, fe.evaluate(cellE).getNumberValue(), 0); + 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(new CellReference(cellF).formatAsString(), cachedResultF, fe.evaluate(cellF).getNumberValue(), 0); + 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 index dc9f7673c5..b63b6e3dcc 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestRelationalOperations.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.CacheAreaEval; import org.apache.poi.ss.formula.eval.BoolEval; @@ -25,7 +25,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestRelationalOperations { @@ -50,7 +50,7 @@ public class TestRelationalOperations { RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 2, 5); - assertEquals("expected CacheAreaEval", CacheAreaEval.class, result.getClass()); + assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); CacheAreaEval ce = (CacheAreaEval)result; assertEquals(2, ce.getWidth()); assertEquals(2, ce.getHeight()); @@ -73,7 +73,7 @@ public class TestRelationalOperations { RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 2, 5); - assertEquals("expected CacheAreaEval", CacheAreaEval.class, result.getClass()); + assertEquals(CacheAreaEval.class, result.getClass(), "expected CacheAreaEval"); CacheAreaEval ce = (CacheAreaEval)result; assertEquals(2, ce.getWidth()); assertEquals(2, ce.getHeight()); @@ -106,14 +106,14 @@ public class TestRelationalOperations { RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 5); - assertEquals("expected CacheAreaEval", CacheAreaEval.class, result.getClass()); + 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("[" + i + "," + j + "]", expected[idx++], ce.getRelativeValue(i, j)); + assertEquals(expected[idx++], ce.getRelativeValue(i, j), "[" + i + "," + j + "]"); } } } @@ -143,14 +143,14 @@ public class TestRelationalOperations { RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 6); - assertEquals("expected CacheAreaEval", CacheAreaEval.class, result.getClass()); + 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("[" + i + "," + j + "]", expected[idx++], ce.getRelativeValue(i, j)); + assertEquals(expected[idx++], ce.getRelativeValue(i, j), "[" + i + "," + j + "]"); } } } @@ -181,14 +181,14 @@ public class TestRelationalOperations { RelationalOperationEval eq = (RelationalOperationEval)RelationalOperationEval.EqualEval; ValueEval result = eq.evaluateArray(new ValueEval[]{ arg1, arg2}, 4, 6); - assertEquals("expected CacheAreaEval", CacheAreaEval.class, result.getClass()); + 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("[" + i + "," + j + "]", expected[idx++], ce.getRelativeValue(i, 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 index f505cd556a..a2a62f8b65 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests REPT() as loaded from a test data spreadsheet.

*/ public class TestReptFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 26b8745cf0..716dfc202b 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests Roman() as loaded from a test data spreadsheet.

*/ public class TestRomanFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index 6730cd2d9d..bee18ea272 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.ValueEval; @@ -35,7 +35,7 @@ import org.apache.poi.ss.formula.eval.StringEval; public final class TestRoundFuncs { // github-43 // https://github.com/apache/poi/pull/43 - @Ignore("ROUNDUP(3987*0.2, 2) currently fails by returning 797.41") + @Disabled("ROUNDUP(3987*0.2, 2) currently fails by returning 797.41") @Test public void testRoundUp() { assertRoundUpEquals(797.40, 3987*0.2, 2, 1e-10); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java index 8b194bb8ae..0b73dc5b69 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.eval.ValueEval; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for ROW(), ROWS(), COLUMN(), COLUMNS() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java index de3597e05d..a54d508f8d 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java @@ -19,12 +19,12 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Test for Excel function SLOPE() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java index 9c4fdcb2f2..a462448097 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java @@ -20,13 +20,14 @@ */ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertNotNull; + +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.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestStatsLib extends BaseTestNumeric { @@ -39,32 +40,32 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {1,2,3,4,5,6,7,8,9,10}; d = StatsLib.devsq(v); x = 82.5; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); v = new double[] {1,1,1,1,1,1,1,1,1,1}; d = StatsLib.devsq(v); x = 0; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); v = new double[] {0,0,0,0,0,0,0,0,0,0}; d = StatsLib.devsq(v); x = 0; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); v = new double[] {1,2,1,2,1,2,1,2,1,2}; d = StatsLib.devsq(v); x = 2.5; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; d = StatsLib.devsq(v); x = 10953.7416965767; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.devsq(v); x = 82.5; - assertEquals("devsq ", x, d); + assertDouble("devsq ", x, d); } @Test @@ -75,36 +76,36 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {1,2,3,4,5,6,7,8,9,10}; d = StatsLib.kthLargest(v, 3); x = 8; - assertEquals("kthLargest ", x, d); + assertDouble("kthLargest ", x, d); v = new double[] {1,1,1,1,1,1,1,1,1,1}; d = StatsLib.kthLargest(v, 3); x = 1; - assertEquals("kthLargest ", x, d); + assertDouble("kthLargest ", x, d); v = new double[] {0,0,0,0,0,0,0,0,0,0}; d = StatsLib.kthLargest(v, 3); x = 0; - assertEquals("kthLargest ", x, d); + assertDouble("kthLargest ", x, d); v = new double[] {1,2,1,2,1,2,1,2,1,2}; d = StatsLib.kthLargest(v, 3); x = 2; - assertEquals("kthLargest ", x, d); + 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; - assertEquals("kthLargest ", x, d); + assertDouble("kthLargest ", x, d); v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.kthLargest(v, 3); x = -3; - assertEquals("kthLargest ", x, d); + assertDouble("kthLargest ", x, d); } @Test - @Ignore("... implement ...") + @Disabled("... implement ...") public void testKthSmallest() { } @@ -116,32 +117,32 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {1,2,3,4,5,6,7,8,9,10}; d = StatsLib.avedev(v); x = 2.5; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); v = new double[] {1,1,1,1,1,1,1,1,1,1}; d = StatsLib.avedev(v); x = 0; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); v = new double[] {0,0,0,0,0,0,0,0,0,0}; d = StatsLib.avedev(v); x = 0; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); v = new double[] {1,2,1,2,1,2,1,2,1,2}; d = StatsLib.avedev(v); x = 0.5; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; d = StatsLib.avedev(v); x = 36.42176053333; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.avedev(v); x = 2.5; - assertEquals("avedev ", x, d); + assertDouble("avedev ", x, d); } @Test @@ -152,42 +153,42 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {1,2,3,4,5,6,7,8,9,10}; d = StatsLib.median(v); x = 5.5; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {1,1,1,1,1,1,1,1,1,1}; d = StatsLib.median(v); x = 1; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {0,0,0,0,0,0,0,0,0,0}; d = StatsLib.median(v); x = 0; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {1,2,1,2,1,2,1,2,1,2}; d = StatsLib.median(v); x = 1.5; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; d = StatsLib.median(v); x = 5.37828; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.median(v); x = -5.5; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.median(v); x = -6; - assertEquals("median ", x, d); + assertDouble("median ", x, d); v = new double[] {1,2,3,4,5,6,7,8,9}; d = StatsLib.median(v); x = 5; - assertEquals("median ", x, d); + assertDouble("median ", x, d); } @Test @@ -227,15 +228,15 @@ public class TestStatsLib extends BaseTestNumeric { double actual; try { actual = Mode.evaluate(v); - assertNotNull("Expected N/A exception was not thrown", expectedResult); + assertNotNull(expectedResult, "Expected N/A exception was not thrown"); } catch (EvaluationException e) { if (expectedResult == null) { - Assert.assertEquals(ErrorEval.NA, e.getErrorEval()); + assertEquals(ErrorEval.NA, e.getErrorEval()); return; } throw new RuntimeException(e); } - assertEquals("mode", expectedResult.doubleValue(), actual); + assertDouble("mode", expectedResult, actual); } @Test @@ -246,32 +247,32 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {1,2,3,4,5,6,7,8,9,10}; d = StatsLib.stdev(v); x = 3.02765035410; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); v = new double[] {1,1,1,1,1,1,1,1,1,1}; d = StatsLib.stdev(v); x = 0; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); v = new double[] {0,0,0,0,0,0,0,0,0,0}; d = StatsLib.stdev(v); x = 0; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); v = new double[] {1,2,1,2,1,2,1,2,1,2}; d = StatsLib.stdev(v); x = 0.52704627669; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; d = StatsLib.stdev(v); x = 52.33006233652; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; d = StatsLib.stdev(v); x = 3.02765035410; - assertEquals("stdev ", x, d); + assertDouble("stdev ", x, d); } @Test @@ -282,22 +283,22 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {3.50, 5.00, 7.23, 2.99}; d = StatsLib.var(v); x = 3.6178; - assertEquals("var ", x, d); + assertDouble("var ", x, d); v = new double[] {34.5, 2.0, 8.9, -4.0}; d = StatsLib.var(v); x = 286.99; - assertEquals("var ", x, d); + assertDouble("var ", x, d); v = new double[] {7.0, 25.0, 21.69}; d = StatsLib.var(v); x = 91.79203333; - assertEquals("var ", x, d); + assertDouble("var ", x, d); v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; d = StatsLib.var(v); x = 754.2666667; - assertEquals("var ", x, d); + assertDouble("var ", x, d); } @Test @@ -308,21 +309,21 @@ public class TestStatsLib extends BaseTestNumeric { v = new double[] {3.50, 5.00, 7.23, 2.99}; d = StatsLib.varp(v); x = 2.71335; - assertEquals("varp ", x, d); + assertDouble("varp ", x, d); v = new double[] {34.5, 2.0, 8.9, -4.0}; d = StatsLib.varp(v); x = 215.2425; - assertEquals("varp ", x, d); + assertDouble("varp ", x, d); v = new double[] {7.0, 25.0, 21.69}; d = StatsLib.varp(v); x = 61.19468889; - assertEquals("varp ", x, d); + assertDouble("varp ", x, d); v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; d = StatsLib.varp(v); x = 678.84; - assertEquals("varp ", x, d); + 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 index 68c868865b..9a076e9336 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSubstitute.java @@ -22,9 +22,9 @@ 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.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestSubstitute { @Test diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java index aa16314379..240d48b05a 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; @@ -37,7 +37,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Subtotal} @@ -345,7 +345,7 @@ public final class TestSubtotal { CellValue value = evaluator.evaluate(cell); if (value.getErrorValue() != 0) throw new RuntimeException(msg + ": " + value.formatAsString()); - assertEquals(msg, expected, value.getNumberValue(), 0); + assertEquals(expected, value.getNumberValue(), 0, msg); } @Test @@ -354,16 +354,16 @@ public final class TestSubtotal { HSSFSheet sheet = workbook.getSheetAt(0); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - assertEquals("B2", 10.0, sheet.getRow(1).getCell(1).getNumericCellValue(), 0); - assertEquals("B3", 20.0, sheet.getRow(2).getCell(1).getNumericCellValue(), 0); + 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("C2 must not be null", sheet.getRow(1).getCell(2)); - assertEquals("C2", 7.0, sheet.getRow(1).getCell(2).getNumericCellValue(), 0); + 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); @@ -375,7 +375,7 @@ public final class TestSubtotal { 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); @@ -383,8 +383,8 @@ public final class TestSubtotal { 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(); } @@ -396,7 +396,7 @@ public final class TestSubtotal { Sheet sh = wb.createSheet(); Cell a3 = sh.createRow(3).createCell(1); - + // formula, throws NotImplemnted? String[][] formulas = { { "SUBTOTAL(8,B2:B3)", NotImplementedException.class.getName() }, @@ -406,25 +406,25 @@ public final class TestSubtotal { { "SUBTOTAL(9)", FormulaParseException.class.getName() }, { "SUBTOTAL()", FormulaParseException.class.getName() }, }; - + for (String[] f : formulas) { Exception actualEx = null; try { a3.setCellFormula(f[0]); fe.evaluateAll(); - assertEquals(f[0], FormulaError.VALUE.getCode(), a3.getErrorCellValue()); + 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(msg, f[1], (actualEx == null ? null : actualEx.getClass().getName())); + 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 index 7f5aabcbd5..894c93609a 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for SUMPRODUCT() @@ -44,7 +44,7 @@ public final class TestSumif { } private static void confirmDouble(double expected, ValueEval actualEval) { - assertTrue("Expected numeric result", actualEval instanceof NumericValueEval); + assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); NumericValueEval nve = (NumericValueEval)actualEval; assertEquals(expected, nve.getNumberValue(), 0); } @@ -96,7 +96,7 @@ public final class TestSumif { ve = invokeSumif(0, 2, arg0, arg1); // invoking from cell C1 if (ve instanceof NumberEval) { NumberEval ne = (NumberEval) ve; - assertNotEquals("identified error in SUMIF - criteria arg not evaluated properly", 30.0, ne.getNumberValue()); + assertNotEquals(30.0, ne.getNumberValue(), "identified error in SUMIF - criteria arg not evaluated properly"); } confirmDouble(200, ve); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java index 4e441a066e..135cd1f1a6 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java @@ -19,8 +19,8 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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; @@ -33,7 +33,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for SUMIFS() @@ -47,7 +47,7 @@ public final class TestSumifs { } private static void confirmDouble(double expected, ValueEval actualEval) { - assertTrue("Expected numeric result", actualEval instanceof NumericValueEval); + assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); NumericValueEval nve = (NumericValueEval)actualEval; assertEquals(expected, nve.getNumberValue(), 0); } @@ -297,7 +297,7 @@ public final class TestSumifs { }; ValueEval result = invokeSumifs(args); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); + 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), @@ -306,7 +306,7 @@ public final class TestSumifs { }; result = invokeSumifs(args); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); + assertTrue(result instanceof ErrorEval, "Expect to have an error when an input is an invalid value, but had: " + result.getClass()); } @Test @@ -330,7 +330,7 @@ public final class TestSumifs { }; ValueEval result = invokeSumifs(args); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); + 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); } @@ -355,7 +355,7 @@ public final class TestSumifs { }; ValueEval result = invokeSumifs(args); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); + 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 index 422b154a04..47b1751ae9 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java @@ -17,8 +17,9 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.ErrorEval; @@ -26,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for SUMPRODUCT() @@ -41,9 +42,7 @@ public final class TestSumproduct { } private static void confirmDouble(double expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - fail("Expected numeric result"); - } + assertTrue(actualEval instanceof NumericValueEval, "Expected numeric result"); NumericValueEval nve = (NumericValueEval)actualEval; assertEquals(expected, nve.getNumberValue(), 0); } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java index a89a213091..efadacf610 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test cases for Excel function T() @@ -44,7 +44,7 @@ public final class TestTFunc { private static ValueEval invokeT(ValueEval arg) { ValueEval[] args = { arg, }; ValueEval result = new T().evaluate(args, -1, (short)-1); - assertNotNull("result may never be null", result); + assertNotNull(result, "result may never be null"); return result; } diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java index 0e6521ef23..4bde9abb10 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.DateFormatSymbols; import java.text.DecimalFormatSymbols; @@ -29,7 +29,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Test case for TEXT() @@ -104,28 +104,28 @@ public final class TestText { 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; diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java index 7f12c136aa..87b049585f 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.regex.Pattern; @@ -28,8 +28,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link TimeFunc} @@ -44,8 +44,8 @@ public final class TestTime { private HSSFWorkbook wb; private HSSFDataFormatter form; private HSSFCellStyle style; - - @Before + + @BeforeEach public void setUp() { wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java index 51871d16e5..49f9a714f7 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTrendFunctionsFromSpreadsheet.java @@ -16,16 +16,15 @@ ==================================================================== */ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests TREND() as loaded from a test data spreadsheet. */ public class TestTrendFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index d18c044d15..4d889116ae 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.ss.formula.eval.BlankEval; import org.apache.poi.ss.formula.eval.BoolEval; @@ -25,7 +25,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel function TRIM() diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java index 50d0adabc9..ba137bdd28 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java @@ -17,12 +17,13 @@ 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.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test case for TRUNC() @@ -38,7 +39,7 @@ public final class TestTrunc extends BaseTestNumeric { ValueEval strArg = new StringEval("abc"); ValueEval[] args = { strArg, new NumberEval(2) }; ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - Assert.assertEquals(ErrorEval.VALUE_INVALID, result); + assertEquals(ErrorEval.VALUE_INVALID, result); } @Test @@ -46,7 +47,7 @@ public final class TestTrunc extends BaseTestNumeric { ValueEval[] args = { new NumberEval(200), new NumberEval(2) }; @SuppressWarnings("static-access") ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(200d)).getNumberValue(), ((NumberEval)result).getNumberValue()); + assertDouble("TRUNC", (new NumberEval(200d)).getNumberValue(), ((NumberEval)result).getNumberValue()); } @Test @@ -54,14 +55,14 @@ public final class TestTrunc extends BaseTestNumeric { ValueEval[] args = { new NumberEval(2.612777), new NumberEval(3) }; @SuppressWarnings("static-access") ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(2.612d)).getNumberValue(), ((NumberEval)result).getNumberValue()); + assertDouble("TRUNC", (new NumberEval(2.612d)).getNumberValue(), ((NumberEval)result).getNumberValue()); } @Test public void testTruncWithProblematicDecimalNumber() { ValueEval[] args = { new NumberEval(0.29), new NumberEval(2) }; ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(0.29d)).getNumberValue(), ((NumberEval)result).getNumberValue()); + assertDouble("TRUNC", (new NumberEval(0.29d)).getNumberValue(), ((NumberEval)result).getNumberValue()); } @Test @@ -69,14 +70,14 @@ public final class TestTrunc extends BaseTestNumeric { ValueEval[] args = { new NumberEval(21.624d / 24d + .009d), new NumberEval(2) }; ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(0.91d)).getNumberValue(), ((NumberEval)result).getNumberValue()); + assertDouble("TRUNC", (new NumberEval(0.91d)).getNumberValue(), ((NumberEval)result).getNumberValue()); } @Test public void testTruncWithDecimalNumberOneArg() { ValueEval[] args = { new NumberEval(2.612777) }; ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(2d)).getNumberValue(), ((NumberEval)result).getNumberValue()); + assertDouble("TRUNC", (new NumberEval(2d)).getNumberValue(), ((NumberEval)result).getNumberValue()); } @Test @@ -84,6 +85,6 @@ public final class TestTrunc extends BaseTestNumeric { ValueEval[] args = { new NumberEval(-8.9), new NumberEval(0) }; @SuppressWarnings("static-access") ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(-8)).getNumberValue(), ((NumberEval)result).getNumberValue()); + 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 index f630af5cab..389d2bb5a0 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestTwoOperandNumericFunctionsFromSpreadsheet.java @@ -17,17 +17,16 @@ package org.apache.poi.ss.formula.functions; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; -import java.util.Collection; +import org.junit.jupiter.params.provider.Arguments; /** * Tests for numeric functions with two arguments such aqs +, -, *, POWER * as loaded from a test data spreadsheet. */ public class TestTwoOperandNumericFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index bed69af15f..701d1eafd3 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link Value} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java index 8fd8cef82b..10b6f4c773 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests WeekNum() as loaded from a test data spreadsheet.

*/ public class TestWeekNumFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index ccffa6f59e..92bf8dc217 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java @@ -17,16 +17,15 @@ package org.apache.poi.ss.formula.functions; -import java.util.Collection; +import java.util.stream.Stream; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; /** * Tests WeekNum() as loaded from a test data 2013 excel spreadsheet.

*/ public class TestWeekNumFunctionsFromSpreadsheet2013 extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { + 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 index a3d9511d19..dbcd5439b8 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java @@ -19,9 +19,9 @@ package org.apache.poi.ss.formula.functions; import org.apache.poi.ss.formula.eval.*; import org.apache.poi.util.StringUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Tests WEEKDAY(serial_number[, return_type]) excep function @@ -29,58 +29,58 @@ import static org.junit.Assert.*; */ public 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(formula, expected, result.getNumberValue(), TOLERANCE); + 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(formula, expected, result.getNumberValue(), TOLERANCE); + assertEquals(expected, result.getNumberValue(), TOLERANCE, formula); } - + @Test - public void testEvaluate() throws Exception { + public 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(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); + + 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(formula + ": " + message, expected, result); + assertEquals(expected, result, formula + ": " + message); } @Test - public void testEvaluateInvalid() throws Exception { + public 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)); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java index 1c8f439ce8..b191bb4cfd 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.functions; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Excel functions SUMX2MY2(), SUMX2PY2(), SUMXMY2() diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java b/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java deleted file mode 100644 index 93797a74f5..0000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.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.ss.formula.ptg; - -import org.apache.poi.ss.formula.TestSheetNameFormatter; -import org.apache.poi.ss.formula.eval.AllFormulaEvalTests; -import org.apache.poi.ss.formula.function.AllFormulaFunctionTests; -import org.apache.poi.ss.formula.functions.AllIndividualFunctionEvaluationTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.record.formula. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllFormulaEvalTests.class, - AllFormulaFunctionTests.class, - AllIndividualFunctionEvaluationTests.class, - TestArea3DPtg.class, - TestAreaErrPtg.class, - TestAreaPtg.class, - TestArrayPtg.class, - TestAttrPtg.class, - TestErrPtg.class, - TestExternalFunctionFormulas.class, - //TestFormulaShifter.class, //converted to junit4 - TestFuncPtg.class, - TestFuncVarPtg.class, - TestIntersectionPtg.class, - TestPercentPtg.class, - TestRangePtg.class, - TestRef3DPtg.class, - TestReferencePtg.class, - TestSheetNameFormatter.class, - TestUnionPtg.class -}) -public class AllFormulaTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java index e4b73a3de4..c7a618812f 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestAbstractFunctionPtg.java @@ -17,10 +17,11 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; public class TestAbstractFunctionPtg { @@ -32,14 +33,14 @@ public class TestAbstractFunctionPtg { assertEquals(255, ptg.getNumberOfOperands()); } - @Test(expected=RuntimeException.class) + @Test public void testInvalidFunctionIndex() { - new FunctionPtg(40000, 2, null, 255); + assertThrows(RuntimeException.class, () -> new FunctionPtg(40000, 2, null, 255)); } - @Test(expected=RuntimeException.class) + @Test public void testInvalidRuntimeClass() { - new FunctionPtg(1, 300, null, 255); + assertThrows(RuntimeException.class, () -> new FunctionPtg(1, 300, null, 255)); } private static class FunctionPtg extends AbstractFunctionPtg { diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java index 481d7c5051..9e89a4e9f0 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Area3DPtg diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java index 3d04da1db5..ab946e5953 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link AreaErrPtg}. @@ -34,8 +34,8 @@ public final class TestAreaErrPtg extends BaseTestPtg { @Test public void testReading() throws IOException { try (HSSFWorkbook workbook = loadWorkbook("AreaErrPtg.xls")) { - assertEquals("Wrong formula string for area error", "SUM(#REF!)", - workbook.getSheetAt(0).getRow(0).getCell(2).getCellFormula()); + 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 index d0cdb507c1..7c09db8f89 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java @@ -18,14 +18,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.util.AreaReference; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link AreaPtg}. @@ -35,7 +34,7 @@ public final class TestAreaPtg { AreaPtg relative; AreaPtg absolute; - @Before + @BeforeEach public void setUp() { short firstRow=5; short lastRow=13; @@ -50,11 +49,11 @@ public final class TestAreaPtg { AreaPtg ptg = new AreaPtg(new AreaReference("A$1:$B5", SpreadsheetVersion.EXCEL2007)); assertEquals("A$1:$B5", ptg.toFormulaString()); ptg.setFirstColumn(3); - assertEquals("Area Ptg should not implicitly re-sort itself (except during construction)", - "D$1:$B5", ptg.toFormulaString()); + assertEquals("D$1:$B5", ptg.toFormulaString(), + "Area Ptg should not implicitly re-sort itself (except during construction)"); ptg.sortTopLeftToBottomRight(); - assertEquals("Area Ptg should restore itself to top-left to lower-right order when explicitly asked", - "$B$1:D5", ptg.toFormulaString()); + assertEquals("$B$1:D5", ptg.toFormulaString(), + "Area Ptg should restore itself to top-left to lower-right order when explicitly asked"); } @Test @@ -70,10 +69,11 @@ public final class TestAreaPtg { } private void validateReference(boolean abs, AreaPtg ref) { - assertEquals("First column reference is not "+(abs?"absolute":"relative"),abs,!ref.isFirstColRelative()); - assertEquals("Last column reference is not "+(abs?"absolute":"relative"),abs,!ref.isLastColRelative()); - assertEquals("First row reference is not "+(abs?"absolute":"relative"),abs,!ref.isFirstRowRelative()); - assertEquals("Last row reference is not "+(abs?"absolute":"relative"),abs,!ref.isLastRowRelative()); + 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); } @@ -93,20 +93,20 @@ public final class TestAreaPtg { 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("first rel., last abs.", "G5:$H$6", sca1.toFormulaString()); - assertEquals("first abs., last rel.", "$G$5:H6", sca2.toFormulaString()); - assertEquals("first rel., last abs.", "H6:$H$6", sca3.toFormulaString()); - assertEquals("first abs., last rel.", "$H$6:H6", sca4.toFormulaString()); + 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("first rel., last abs.", "G5:$H$6", cla1.toFormulaString()); - assertEquals("first abs., last rel.", "$G$5:H6", cla2.toFormulaString()); - assertEquals("first rel., last abs.", "H6:$H$6", cla3.toFormulaString()); - assertEquals("first abs., last rel.", "$H$6:H6", cla4.toFormulaString()); + 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) { @@ -121,18 +121,17 @@ public final class TestAreaPtg { String formula1="SUM($E$5:$E$6)"; String expectedFormula1="SUM($F$5:$F$6)"; String newFormula1 = shiftAllColumnsBy1(formula1); - assertEquals("Absolute references changed", expectedFormula1, newFormula1); + assertEquals(expectedFormula1, newFormula1, "Absolute references changed"); String formula2="SUM(E5:E6)"; String expectedFormula2="SUM(F5:F6)"; String newFormula2 = shiftAllColumnsBy1(formula2); - assertEquals("Relative references changed", expectedFormula2, newFormula2); + assertEquals(expectedFormula2, newFormula2, "Relative references changed"); } private static String shiftAllColumnsBy1(String formula) { int letUsShiftColumn1By1Column=1; - HSSFWorkbook wb = null; - Ptg[] ptgs = HSSFFormulaParser.parse(formula, wb); + Ptg[] ptgs = HSSFFormulaParser.parse(formula, null); for (Ptg ptg : ptgs) { if (ptg instanceof AreaPtg ) { @@ -141,6 +140,6 @@ public final class TestAreaPtg { aptg.setLastColumn((short)(aptg.getLastColumn()+letUsShiftColumn1By1Column)); } } - return HSSFFormulaParser.toFormulaString(wb, ptgs); + 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 index 170c06719b..79114a6f8a 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java @@ -17,16 +17,16 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for ArrayPtg @@ -74,7 +74,7 @@ public final class TestArrayPtg { byte[] outBuf = new byte[ENCODED_CONSTANT_DATA.length]; ptg.writeTokenValueBytes(new LittleEndianByteArrayOutputStream(outBuf, 0)); - assertNotEquals("Identified bug 42564b", 4, outBuf[0]); + assertNotEquals(4, outBuf[0], "Identified bug 42564b"); assertArrayEquals(ENCODED_CONSTANT_DATA, outBuf); } diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java index d957a956aa..5d96832181 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertArrayEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link AttrPtg}. diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java index 0ff6ad78b6..c9cf488736 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ErrPtg}. @@ -36,8 +36,8 @@ public final class TestErrPtg extends BaseTestPtg { public void testReading() throws IOException { try (HSSFWorkbook workbook = loadWorkbook("ErrPtg.xls")) { HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(0); - assertEquals("Wrong cell value", 4.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "ERROR.TYPE(#REF!)", cell.getCellFormula()); + 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 index bb3220743c..8cc8014a32 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.model.HSSFFormulaParser; @@ -26,7 +26,7 @@ import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for functions from external workbooks (e.g. YEARFRAC). @@ -34,27 +34,27 @@ import org.junit.Test; public final class TestExternalFunctionFormulas { /** - * tests NameXPtg.toFormulaString(Workbook) and logic in Workbook below that + * tests NameXPtg.toFormulaString(Workbook) and logic in Workbook below that */ @Test public 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 public 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 @@ -70,7 +70,7 @@ public final class TestExternalFunctionFormulas { // } wb.close(); } - + @Test public void testEvaluate() throws Exception { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); @@ -84,7 +84,7 @@ public final class TestExternalFunctionFormulas { wb.close(); } - private static void confirmCellEval(HSSFSheet sheet, int rowIx, int colIx, + 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()); diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java index c70e5d63c9..7974f57a01 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java @@ -18,8 +18,8 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -27,7 +27,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for proper calculation of named ranges from external workbooks. diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java index fdd9a8c574..2b3b9415a0 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Make sure the FuncPtg performs as expected @@ -33,10 +33,10 @@ public final class TestFuncPtg { byte[] fakeData = { 0x20, 0x00,}; FuncPtg ptg = FuncPtg.create(TestcaseRecordInputStream.createLittleEndian(fakeData) ); - assertEquals( "Len formula index is not 32(20H)", 0x20, ptg.getFunctionIndex() ); - assertEquals( "Number of operands in the len formula", 1, ptg.getNumberOfOperands() ); - assertEquals( "Function Name", "LEN", ptg.getName() ); - assertEquals( "Ptg Size", 3, ptg.getSize() ); + 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 diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java index 62c5a125f0..9b5891bb90 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * @author Josh Micich diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java index 729920cb8a..a022c935b7 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link IntersectionPtg}. @@ -36,8 +36,8 @@ public final class TestIntersectionPtg extends BaseTestPtg { public void testReading() throws IOException { try (HSSFWorkbook workbook = loadWorkbook("IntersectionPtg.xls")) { HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals("Wrong cell value", 5.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(A1:B2 B2:C3)", cell.getCellFormula()); + 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 index 4b69d0743b..f6e658c162 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link PercentPtg}. @@ -37,12 +37,12 @@ public final class TestPercentPtg extends BaseTestPtg { try (HSSFWorkbook workbook = loadWorkbook("PercentPtg.xls")) { HSSFSheet sheet = workbook.getSheetAt(0); - assertEquals("Wrong numeric value for original number", 53000.0, - sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for percent formula result", 5300.0, - sheet.getRow(1).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for percent formula", "A1*10%", - sheet.getRow(1).getCell(0).getCellFormula()); + 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 index 5389538ab2..8d9b41d555 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RangePtg}. @@ -36,8 +36,8 @@ public final class TestRangePtg extends BaseTestPtg { public void testReading() throws IOException { try (HSSFWorkbook workbook = loadWorkbook("RangePtg.xls")) { HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(1); - assertEquals("Wrong cell value", 10.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(pineapple:B2)", cell.getCellFormula()); + 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 index 04de2cb6e3..b510cab68c 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for Ref3DPtg diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java index 00c225be15..acc2d6cf50 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.IOException; @@ -28,7 +28,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link RefPtg}. @@ -43,42 +43,29 @@ public final class TestReferencePtg { HSSFSheet sheet = workbook.getSheetAt(0); // First row - assertEquals("Wrong numeric value for original number", 55.0, - sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 55.0, - sheet.getRow(0).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A1", - sheet.getRow(0).getCell(1).getCellFormula()); + 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("Wrong numeric value for original number", 32767.0, - sheet.getRow(32766).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32767.0, - sheet.getRow(32766).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32767", - sheet.getRow(32766).getCell(1).getCellFormula()); + 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("Wrong numeric value for original number", 32768.0, - sheet.getRow(32767).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32768.0, - sheet.getRow(32767).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32768", - sheet.getRow(32767).getCell(1).getCellFormula()); + 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("Wrong numeric value for original number", 32769.0, - sheet.getRow(32768).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32769.0, - sheet.getRow(32768).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32769", - sheet.getRow(32768).getCell(1).getCellFormula()); + 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("Wrong numeric value for original number", 32770.0, - sheet.getRow(32769).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32770.0, - sheet.getRow(32769).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32770", - sheet.getRow(32769).getCell(1).getCellFormula()); + 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 @@ -98,7 +85,7 @@ public final class TestReferencePtg { Ptg[] ptgs = Ptg.readTokens(tRefN_data.length, in); byte[] outData = new byte[5]; Ptg.serializePtgs(ptgs, outData, 0); - assertNotEquals("Identified bug 45091", 0x24, outData[0]); + assertNotEquals(0x24, outData[0], "Identified bug 45091"); assertArrayEquals(tRefN_data, outData); } diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java index 446700f78d..dd2c423230 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.formula.ptg; -import static org.junit.Assert.assertEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link UnionPtg}. @@ -36,8 +36,8 @@ public final class TestUnionPtg extends BaseTestPtg { public void testReading() throws IOException { try (HSSFWorkbook workbook = loadWorkbook("UnionPtg.xls")) { HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals("Wrong cell value", 24.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(A1:B2,B2:C3)", cell.getCellFormula()); + 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/BaseTestUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java index ab3aa987c7..207e196ae3 100644 --- a/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java +++ b/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.ss.formula.udf; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.OperationEvaluationContext; +import org.apache.poi.ss.formula.eval.ValueEval; +import org.apache.poi.ss.formula.functions.FreeRefFunction; public class BaseTestUDFFinder { diff --git a/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java index 88d7e84fff..93b90a9f1b 100644 --- a/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java +++ b/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.udf; import org.apache.poi.ss.formula.atp.AnalysisToolPak; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestAggregatingUDFFinder extends BaseTestUDFFinder { diff --git a/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java index 010b19d4e2..0b166e8509 100644 --- a/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java +++ b/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.formula.udf; import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestDefaultUDFFinder extends BaseTestUDFFinder { diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java index 4a7c3e1784..ca30b3eb8d 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java @@ -16,23 +16,23 @@ 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 + 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.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.apache.poi.ss.ITestDataProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests of {@link BorderStyle} */ public abstract class BaseTestBorderStyle { - + private final ITestDataProvider _testDataProvider; protected BaseTestBorderStyle(ITestDataProvider testDataProvider) { @@ -48,7 +48,7 @@ public abstract class BaseTestBorderStyle { 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)); @@ -63,14 +63,14 @@ public abstract class BaseTestBorderStyle { 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()); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java index cb026e2ff5..91325fee38 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java @@ -17,12 +17,13 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -44,9 +45,8 @@ import org.apache.poi.ss.util.PaneInformation; import org.apache.poi.ss.util.SheetUtil; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; +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. @@ -74,9 +74,7 @@ public abstract class BaseTestBugzillaIssues { private static void assertAlmostEquals(double expected, double actual, float factor) { double diff = Math.abs(expected - actual); double fuzz = expected * factor; - if (diff > fuzz) { - fail(actual + " not within " + fuzz + " of " + expected); - } + assertTrue(diff <= fuzz, actual + " not within " + fuzz + " of " + expected); } /** @@ -160,14 +158,14 @@ public abstract class BaseTestBugzillaIssues { Sheet clone = wb.cloneSheet(0); int originalMerged = template.getNumMergedRegions(); - assertEquals("2 merged regions", 2, originalMerged); + assertEquals(2, originalMerged, "2 merged regions"); //remove merged regions from clone for (int i = template.getNumMergedRegions() - 1; i >= 0; i--) { clone.removeMergedRegion(i); } - assertEquals("Original Sheet's Merged Regions were removed", originalMerged, template.getNumMergedRegions()); + 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 @@ -352,13 +350,11 @@ public abstract class BaseTestBugzillaIssues { fmla = createFunction(name, ssVersion.getMaxFunctionArgs()); cell.setCellFormula(fmla); - try { - fmla = createFunction(name, ssVersion.getMaxFunctionArgs() + 1); - cell.setCellFormula(fmla); - fail("Expected FormulaParseException"); - } catch (FormulaParseException e) { - assertTrue(e.getMessage().startsWith("Too many arguments to function '" + name + "'")); - } + 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 + "'")); } } } @@ -396,13 +392,11 @@ public abstract class BaseTestBugzillaIssues { // autoSize will fail if required fonts are not installed, skip this test then Font font = wb.getFontAt(cell0.getCellStyle().getFontIndex()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); + assumeTrue(SheetUtil.canComputeColumnWidth(font), + "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); - assertEquals("Expecting no indentation in this test", - 0, cell0.getCellStyle().getIndention()); - assertEquals("Expecting no rotation in this test", - 0, cell0.getCellStyle().getRotation()); + 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(); @@ -417,16 +411,16 @@ public abstract class BaseTestBugzillaIssues { String info = widthManual + "/" + widthBeforeCell + "/" + widthBeforeCol + "/" + SheetUtil.canComputeColumnWidth(font) + "/" + computeCellWidthFixed(font, "1") + "/" + computeCellWidthFixed(font, "w") + "/" + computeCellWidthFixed(font, "1w") + "/" + computeCellWidthFixed(font, "0000") + "/" + computeCellWidthFixed(font, longValue); - assertTrue("Expected to have cell width > 0 when computing manually, but had " + info, widthManual > 0); - assertTrue("Expected to have cell width > 0 BEFORE auto-size, but had " + info, widthBeforeCell > 0); - assertTrue("Expected to have column width > 0 BEFORE auto-size, but had " + info, widthBeforeCol > 0); + 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("Expected to have column width > 0 AFTER auto-size, but had " + width, width > 0); + assertTrue(width > 0, "Expected to have column width > 0 AFTER auto-size, but had " + width); width = SheetUtil.getCellWidth(cell0, 8, null, false); - assertTrue("Expected to have cell width > 0 AFTER auto-size, but had " + width, width > 0); + 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 @@ -466,11 +460,11 @@ public abstract class BaseTestBugzillaIssues { double trailingWhitespaceRatio = ((double) leadingWhitespaceColWidth) / noWhitespaceColWidth; assertGreaterThan("leading whitespace is longer than no whitespace", - leadingWhitespaceRatio, expectedRatioThreshold); + leadingWhitespaceRatio, expectedRatioThreshold); assertGreaterThan("trailing whitespace is longer than no whitespace", - trailingWhitespaceRatio, expectedRatioThreshold); - assertEquals("cells with equal leading and trailing whitespace have equal width", - leadingWhitespaceColWidth, trailingWhitespaceColWidth); + trailingWhitespaceRatio, expectedRatioThreshold); + assertEquals(leadingWhitespaceColWidth, trailingWhitespaceColWidth, + "cells with equal leading and trailing whitespace have equal width"); } } @@ -479,10 +473,7 @@ public abstract class BaseTestBugzillaIssues { * Test if a > b. Fails if false. */ private void assertGreaterThan(String message, double a, double b) { - if (a <= b) { - String msg = "Expected: " + a + " > " + b; - fail(message + ": " + msg); - } + assertTrue(a > b, message + ": " + "Expected: " + a + " > " + b); } // FIXME: this function is a self-fulfilling prophecy: this test will always pass as long @@ -503,7 +494,7 @@ public abstract class BaseTestBugzillaIssues { TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); double frameWidth = getFrameWidth(layout); - return ((frameWidth / 1) / 8); + return (frameWidth / 8); } private double getFrameWidth(TextLayout layout) { @@ -878,82 +869,67 @@ public abstract class BaseTestBugzillaIssues { * TODO Fix this to evaluate for XSSF * TODO Fix this to work at all for HSSF */ - @Ignore("Fix this to evaluate for XSSF, Fix this to work at all for HSSF") + @Disabled("Fix this to evaluate for XSSF, Fix this to work at all for HSSF") @Test public void bug46670() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s = wb1.createSheet(); - Row r1 = s.createRow(0); + 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"; + // 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 - Cell c1 = r1.createCell(0, CellType.FORMULA); - c1.setCellFormula(refLocal); - - Cell c2 = r1.createCell(1, CellType.FORMULA); - c2.setCellFormula(refHttp); + // Create the references + r1.createCell(0, CellType.FORMULA).setCellFormula(refLocal); + r1.createCell(1, CellType.FORMULA).setCellFormula(refHttp); - // Check they were set correctly - assertEquals(refLocal, c1.getCellFormula()); - assertEquals(refHttp, c2.getCellFormula()); + // 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 - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r1 = s.getRow(0); + // Reload, and ensure they were serialised and read correctly + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + s = wb2.getSheetAt(0); + r1 = s.getRow(0); - c1 = r1.getCell(0); - c2 = r1.getCell(1); - assertEquals(refLocal, c1.getCellFormula()); - assertEquals(refHttp, c2.getCellFormula()); + 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"); - // Try to evaluate, without giving a way to get at the other file - try { - evaluateCell(wb2, c1); - fail("Shouldn't be able to evaluate without the other file"); - } catch (Exception e) { - // expected here + // 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()); + } + } } - try { - evaluateCell(wb2, c2); - fail("Shouldn't be able to evaluate without the other file"); - } catch (Exception e) { - // expected here - } - - - // Set up references to the other file - 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()); - - wb3.close(); - wb2.close(); } @Test @@ -1159,36 +1135,16 @@ public abstract class BaseTestBugzillaIssues { // Different ways of retrieving assertEquals(1.2, cn.getNumericCellValue(), 0); - try { - cn.getRichStringCellValue(); - fail(); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, cn::getRichStringCellValue); assertEquals("Testing", cs.getStringCellValue()); - try { - cs.getNumericCellValue(); - fail(); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, cs::getNumericCellValue); assertEquals(1.2, cfn.getNumericCellValue(), 0); - try { - cfn.getRichStringCellValue(); - fail(); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, cfn::getRichStringCellValue); assertEquals("Testing", cfs.getStringCellValue()); - try { - cfs.getNumericCellValue(); - fail(); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, cfs::getNumericCellValue); } } @@ -1203,8 +1159,8 @@ public abstract class BaseTestBugzillaIssues { // verify that null-values can be set, this was possible up to 3.11, but broken in 3.12 cell.setCellValue((String) null); String value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); + assertTrue(value == null || value.length() == 0, + "HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value); cell = row.createCell(1); cell.setCellFormula("0"); @@ -1213,20 +1169,20 @@ public abstract class BaseTestBugzillaIssues { wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); + assertTrue(value == null || value.length() == 0, + "HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value); // set some value cell.setCellValue("somevalue"); value = cell.getStringCellValue(); - assertEquals("can set value afterwards: " + value, "somevalue", value); + assertEquals("somevalue", value, "can set value afterwards: " + value); // verify that the null-value is actually set even if there was some value in the cell before cell.setCellValue((String) null); value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); + assertTrue(value == null || value.length() == 0, + "HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value); } } @@ -1312,12 +1268,7 @@ public abstract class BaseTestBugzillaIssues { //Row row = worksheet.createRow(i); //Create cell style - CellStyle style = null; - try { - style = wb.createCellStyle(); - } catch (IllegalStateException e) { - fail("Failed for row " + i); - } + CellStyle style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.RIGHT); if ((wb instanceof HSSFWorkbook)) { // there are some predefined styles @@ -1340,12 +1291,8 @@ public abstract class BaseTestBugzillaIssues { } // should fail if we try to add more now - try { - wb.createCellStyle(); - fail("Should fail after " + maxStyles + " styles, but did not fail"); - } catch (IllegalStateException e) { - // expected here - } + assertThrows(IllegalStateException.class, wb::createCellStyle, + "Should fail after " + maxStyles + " styles, but did not fail"); /*//add column width for appearance sake worksheet.setColumnWidth(0, 5000); @@ -1499,7 +1446,7 @@ public abstract class BaseTestBugzillaIssues { return time() - startTimeMillis; } - @Ignore("bug 59393") + @Disabled("bug 59393") @Test public void bug59393_commentsCanHaveSameAnchor() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { @@ -1580,7 +1527,7 @@ public abstract class BaseTestBugzillaIssues { } } - @Ignore + @Disabled @Test public void test57929() throws IOException { // Create a workbook with print areas on 2 sheets @@ -1599,13 +1546,14 @@ public abstract class BaseTestBugzillaIssues { wb.setPrintArea(1, "$A$1:$A$1"); // Verify that the changes were made - assertNull("Sheet0 before write", wb.getPrintArea(0)); - assertEquals("Sheet1 before write", "Sheet1!$A$1:$A$1", wb.getPrintArea(1)); + 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)) { - assertNull("Sheet0 after write", wb2.getPrintArea(0)); // CURRENTLY FAILS with "Sheet0!$A$1:$C$6" - assertEquals("Sheet1 after write", "Sheet1!$A$1:$A$1", wb2.getPrintArea(1)); + // 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"); } } } @@ -1657,18 +1605,13 @@ public abstract class BaseTestBugzillaIssues { assertEquals(10, row.getRowNum()); for (Cell cell : row) { - String cellValue; - switch (cell.getCellType()) { - case STRING: - cellValue = cell.getRichStringCellValue().getString(); - break; - case FORMULA: - cellValue = cell.getCellFormula(); - break; - default: - fail("unexpected cell type"); - return; - } + 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); @@ -1729,11 +1672,11 @@ public abstract class BaseTestBugzillaIssues { // The name should still refer to the same sheet after the sheets are re-ordered assertEquals(i % 3, wb.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); + 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)) { @@ -1747,11 +1690,11 @@ public abstract class BaseTestBugzillaIssues { // Saving the workbook should not change the sheet names assertEquals(i % 3, wb2.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); + 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"); @@ -1760,11 +1703,11 @@ public abstract class BaseTestBugzillaIssues { name = wb2.getName("WorkbookScopedName"); assertEquals(i % 3, wb2.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); + assertEquals("Sheet1", nameOnSheet1.getSheetName()); + assertEquals("Sheet2", nameOnSheet2.getSheetName()); + assertEquals("Sheet3", nameOnSheet3.getSheetName()); + assertEquals(-1, name.getSheetIndex()); + assertEquals("Sheet2!A1", name.getRefersToFormula()); } } } @@ -1783,20 +1726,24 @@ public abstract class BaseTestBugzillaIssues { // 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 - checkFailures(dataValidation, TEST_256, TEST_32, true); - checkFailures(dataValidation, TEST_32, TEST_256, true); + checkFails(dataValidation, TEST_256, TEST_32); + checkFails(dataValidation, TEST_32, TEST_256); // null does work - checkFailures(dataValidation, null, null, false); + checkPasses(dataValidation, null, null); // more than 32 title fail for HSSFWorkbook - checkFailures(dataValidation, TEST_255, TEST_32, wb instanceof HSSFWorkbook); + if (wb instanceof HSSFWorkbook) { + checkFails(dataValidation, TEST_255, TEST_32); + } else { + checkPasses(dataValidation, TEST_255, TEST_32); + } // special characters work - checkFailures(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL, false); + checkPasses(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL); // 32 length title and 255 length text work for both - checkFailures(dataValidation, TEST_32, TEST_255, false); + checkPasses(dataValidation, TEST_32, TEST_255); dataValidation.setShowErrorBox(false); sheet.addValidationData(dataValidation); @@ -1810,20 +1757,14 @@ public abstract class BaseTestBugzillaIssues { } } - private void checkFailures(DataValidation dataValidation, String title, String text, boolean shouldFail) { - try { - dataValidation.createPromptBox(title, text); - assertFalse("Should fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } catch (IllegalStateException e) { - assertTrue("Should not fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - // expected here - } - try { - dataValidation.createErrorBox(title, text); - assertFalse("Should fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } catch (IllegalStateException e) { - assertTrue("Should not fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } + 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 @@ -1836,7 +1777,7 @@ public abstract class BaseTestBugzillaIssues { DataValidationConstraint constraint = sheet.getDataValidationHelper().createCustomConstraint("A1<>\"\""); dataValidation = sheet.getDataValidationHelper().createValidation(constraint, headerCell); - checkFailures(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL, false); + checkPasses(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL); dataValidation.setShowErrorBox(true); dataValidation.setShowPromptBox(true); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java index caf976b4f9..d4545857d7 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java @@ -18,12 +18,13 @@ package org.apache.poi.ss.usermodel; import static org.apache.poi.ss.usermodel.FormulaError.forInt; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -42,9 +43,10 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Common superclass for testing implementations of @@ -198,32 +200,32 @@ public abstract class BaseTestCell { assertEquals(0, c.getRowIndex()); assertEquals(1, c.getColumnIndex()); c.setCellValue(true); - assertTrue("B1 value", c.getBooleanCellValue()); + assertTrue(c.getBooleanCellValue(), "B1 value"); // C1 c = r.createCell(2); assertEquals(0, c.getRowIndex()); assertEquals(2, c.getColumnIndex()); c.setCellValue(false); - assertFalse("C1 value", c.getBooleanCellValue()); + 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("Row 1 should have 2 cells", 2, r.getPhysicalNumberOfCells()); + 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("B1 value", c.getBooleanCellValue()); + assertTrue(c.getBooleanCellValue(), "B1 value"); c = r.getCell(2); assertEquals(0, c.getRowIndex()); assertEquals(2, c.getColumnIndex()); assertEquals(CellType.BOOLEAN, c.getCellType()); - assertFalse("C1 value", c.getBooleanCellValue()); + assertFalse(c.getBooleanCellValue(), "C1 value"); } } } @@ -246,32 +248,32 @@ public abstract class BaseTestCell { assertEquals(0, c.getRowIndex()); assertEquals(1, c.getColumnIndex()); c.setCellErrorValue(FormulaError.NULL.getCode()); - assertEquals("B1 value == #NULL!", FormulaError.NULL.getCode(), c.getErrorCellValue()); + 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("C1 value == #DIV/0!", FormulaError.DIV0.getCode(), c.getErrorCellValue()); + 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("Row 1 should have 2 cells", 2, r.getPhysicalNumberOfCells()); + 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("B1 value == #NULL!", FormulaError.NULL.getCode(), c.getErrorCellValue()); + 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("C1 value == #DIV/0!", FormulaError.DIV0.getCode(), c.getErrorCellValue()); + assertEquals(FormulaError.DIV0.getCode(), c.getErrorCellValue(), "C1 value == #DIV/0!"); } } } @@ -308,15 +310,15 @@ public abstract class BaseTestCell { r = s.getRow(0); c = r.getCell(0); - assertEquals("Formula Cell at 0,0", CellType.FORMULA, c.getCellType()); + assertEquals(CellType.FORMULA, c.getCellType(), "Formula Cell at 0,0"); cs = c.getCellStyle(); - assertNotNull("Formula Cell Style", cs); - assertEquals("Font Index Matches", f.getIndex(), cs.getFontIndex()); - assertEquals("Top Border", BorderStyle.THIN, cs.getBorderTop()); - assertEquals("Left Border", BorderStyle.THIN, cs.getBorderLeft()); - assertEquals("Right Border", BorderStyle.THIN, cs.getBorderRight()); - assertEquals("Bottom Border", BorderStyle.THIN, cs.getBorderBottom()); + 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"); } } } @@ -345,31 +347,31 @@ public abstract class BaseTestCell { dateStyle.setDataFormat(formatId); r.getCell(7).setCellStyle(dateStyle); - assertEquals("Boolean", "FALSE", r.getCell(0).toString()); - assertEquals("Boolean", "TRUE", r.getCell(1).toString()); - assertEquals("Numeric", "1.5", r.getCell(2).toString()); - assertEquals("String", "Astring", r.getCell(3).toString()); - assertEquals("Error", "#DIV/0!", r.getCell(4).toString()); - assertEquals("Formula", "A1+B1", r.getCell(5).toString()); - assertEquals("Blank", "", r.getCell(6).toString()); + 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("Date (Day)", dateCell1.startsWith("02-")); - assertTrue("Date (Year)", dateCell1.endsWith("-2010")); + 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("Boolean", "FALSE", r.getCell(0).toString()); - assertEquals("Boolean", "TRUE", r.getCell(1).toString()); - assertEquals("Numeric", "1.5", r.getCell(2).toString()); - assertEquals("String", "Astring", r.getCell(3).toString()); - assertEquals("Error", "#DIV/0!", r.getCell(4).toString()); - assertEquals("Formula", "A1+B1", r.getCell(5).toString()); - assertEquals("Blank", "", r.getCell(6).toString()); + 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("Date", dateCell1, dateCell2); + assertEquals(dateCell1, dateCell2, "Date"); } } } @@ -436,12 +438,7 @@ public abstract class BaseTestCell { private static void confirmFormulaWithUnknownUDF(String expectedFormula, Cell cell, FormulaEvaluator evaluator) { assertEquals(expectedFormula, cell.getCellFormula()); - try { - evaluator.evaluate(cell); - fail("Expected NotImplementedFunctionException/NotImplementedException"); - } catch (final org.apache.poi.ss.formula.eval.NotImplementedException e) { - // expected - } + assertThrows(NotImplementedException.class, () -> evaluator.evaluate(cell)); } @Test @@ -525,7 +522,7 @@ public abstract class BaseTestCell { assertEquals("abc", cellA1.getStringCellValue()); fe.evaluateInCell(cellA1); - assertFalse("Identified bug with writing back formula result of type string", cellA1.getStringCellValue().isEmpty()); + assertFalse(cellA1.getStringCellValue().isEmpty(), "Identified bug with writing back formula result of type string"); assertEquals("abc", cellA1.getStringCellValue()); } } @@ -587,7 +584,7 @@ public abstract class BaseTestCell { cell.setCellFormula("1=1"); cell.setCellValue(true); cell.setCellType(CellType.BOOLEAN); - assertTrue("Identified bug 46479d", cell.getBooleanCellValue()); + assertTrue(cell.getBooleanCellValue(), "Identified bug 46479d"); assertTrue(cell.getBooleanCellValue()); } } @@ -690,18 +687,18 @@ public abstract class BaseTestCell { Cell cell0 = row.createCell(0); cell0.setCellValue(Double.NaN); - assertEquals("Double.NaN should change cell type to CellType#ERROR", CellType.ERROR, cell0.getCellType()); - assertEquals("Double.NaN should change cell value to #NUM!", FormulaError.NUM, forInt(cell0.getErrorCellValue())); + 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("Double.POSITIVE_INFINITY should change cell type to CellType#ERROR", CellType.ERROR, cell1.getCellType()); - assertEquals("Double.POSITIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell1.getErrorCellValue())); + 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("Double.NEGATIVE_INFINITY should change cell type to CellType#ERROR", CellType.ERROR, cell2.getCellType()); - assertEquals("Double.NEGATIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell2.getErrorCellValue())); + 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); @@ -965,12 +962,8 @@ public abstract class BaseTestCell { b.append("X"); // 32768 produces an invalid XLS file - try { - cell.setCellValue(b.toString()); - fail("Expected exception"); - } catch (IllegalArgumentException e) { - assertEquals("The maximum length of cell contents (text) is 32767 characters", e.getMessage()); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> cell.setCellValue(b.toString())); + assertEquals("The maximum length of cell contents (text) is 32767 characters", e.getMessage()); } } @@ -1032,35 +1025,14 @@ public abstract class BaseTestCell { cell.setCellFormula("A2"); cell.setCellErrorValue(FormulaError.NAME.getCode()); - assertEquals("Should still be a formula even after we set an error value", - CellType.FORMULA, cell.getCellType()); - assertEquals("Should still be a formula even after we set an error value", - CellType.ERROR, cell.getCachedFormulaResultType()); + 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()); - try { - cell.getNumericCellValue(); - fail("Should catch exception here"); - } catch (IllegalStateException e) { - // expected here - } - try { - cell.getStringCellValue(); - fail("Should catch exception here"); - } catch (IllegalStateException e) { - // expected here - } - try { - cell.getRichStringCellValue(); - fail("Should catch exception here"); - } catch (IllegalStateException e) { - // expected here - } - try { - cell.getDateCellValue(); - fail("Should catch exception here"); - } catch (IllegalStateException e) { - // expected here - } + 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()); } @@ -1214,19 +1186,19 @@ public abstract class BaseTestCell { } } - @Test(expected = IllegalArgumentException.class) + @Test public void setCellType_null_throwsIAE() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Cell cell = getInstance(wb); - cell.setCellType(null); + assertThrows(IllegalArgumentException.class, () -> cell.setCellType(null)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void setCellType_NONE_throwsIAE() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Cell cell = getInstance(wb); - cell.setCellType(CellType._NONE); + assertThrows(IllegalArgumentException.class, () -> cell.setCellType(CellType._NONE)); } } @@ -1248,17 +1220,17 @@ public abstract class BaseTestCell { } } - @Test(expected = IllegalStateException.class) + @Test public 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"); - cell.setBlank(); + assertThrows(IllegalStateException.class, cell::setBlank); } } - @Test(expected = IllegalStateException.class) + @Test public void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Cell cell = getInstance(wb); @@ -1267,7 +1239,7 @@ public abstract class BaseTestCell { assertTrue(cell.isPartOfArrayFormulaGroup()); assertEquals(CellType.FORMULA, cell.getCellType()); - cell.setCellFormula("1"); + assertThrows(IllegalStateException.class, () -> cell.setCellFormula("1")); } } @@ -1349,8 +1321,7 @@ public abstract class BaseTestCell { cell.setCellFormula("\"foo\""); assertEquals(CellType.FORMULA, cell.getCellType()); assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue("Expected a boolean cell-value, but had 'false'", - cell.getBooleanCellValue()); + assertTrue(cell.getBooleanCellValue(), "Expected a boolean cell-value, but had 'false'"); } } @@ -1367,8 +1338,7 @@ public abstract class BaseTestCell { cell.setCellFormula("\"bar\""); assertEquals(CellType.FORMULA, cell.getCellType()); assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue("Expected a boolean cell-value, but had 'false'", - cell.getBooleanCellValue()); + assertTrue(cell.getBooleanCellValue(), "Expected a boolean cell-value, but had 'false'"); } } @@ -1386,18 +1356,18 @@ public abstract class BaseTestCell { cell.getSheet().setArrayFormula("\"bar\"", CellRangeAddress.valueOf("A1")); assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("Expected a boolean cell-value, but had " + cell.getCachedFormulaResultType(), - CellType.BOOLEAN, cell.getCachedFormulaResultType()); - assertTrue("Expected a boolean cell-value, but had 'false'", - cell.getBooleanCellValue()); + 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(expected = IllegalArgumentException.class) + @Test public void setCellType_FORMULA_onANonFormulaCell_throwsIllegalArgumentException() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Cell cell = getInstance(wb); - cell.setCellType(CellType.FORMULA); + assertThrows(IllegalArgumentException.class, () -> cell.setCellType(CellType.FORMULA)); } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java index 852c989009..c2cca1244f 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java @@ -18,20 +18,21 @@ package org.apache.poi.ss.usermodel; import static org.apache.poi.util.Units.EMU_PER_PIXEL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Common superclass for testing implementations of @@ -102,7 +103,7 @@ public abstract class BaseTestCellComment { Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); wb1.close(); - + sheet = wb2.getSheetAt(0); cell = sheet.getRow(cellRow).getCell(cellColumn); comment = cell.getCellComment(); @@ -135,7 +136,7 @@ public abstract class BaseTestCellComment { // Test Comment.equals and Comment.hashCode assertEquals(comment, cell.getCellComment()); assertEquals(comment.hashCode(), cell.getCellComment().hashCode()); - + wb3.close(); } @@ -157,7 +158,7 @@ public abstract class BaseTestCellComment { row = sheet.getRow(rownum); cell = row.getCell(0); comment = cell.getCellComment(); - assertNull("Cells in the first column are not commented", comment); + assertNull(comment, "Cells in the first column are not commented"); assertNull(sheet.getCellComment(new CellAddress(rownum, 0))); } @@ -165,15 +166,15 @@ public abstract class BaseTestCellComment { row = sheet.getRow(rownum); cell = row.getCell(1); comment = cell.getCellComment(); - assertNotNull("Cells in the second column have comments", comment); - assertNotNull("Cells in the second column have comments", sheet.getCellComment(new CellAddress(rownum, 1))); + 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(); } @@ -212,7 +213,7 @@ public abstract class BaseTestCellComment { assertEquals("Mofified[" + rownum + "] by Yegor", comment.getAuthor()); assertEquals("Modified comment at row " + rownum, comment.getString().getString()); } - + wb2.close(); } @@ -242,7 +243,7 @@ public abstract class BaseTestCellComment { assertNull(sheet.getRow(0).getCell(1).getCellComment()); assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); assertNull(sheet.getRow(2).getCell(1).getCellComment()); - + wb2.close(); } @@ -280,24 +281,24 @@ public abstract class BaseTestCellComment { assertEquals("Apache POI", comment.getAuthor()); assertEquals(3, comment.getRow()); assertEquals(5, comment.getColumn()); - + wb2.close(); } @Test public 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())/EMU_PER_PIXEL; + 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; @@ -313,12 +314,12 @@ public abstract class BaseTestCellComment { 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()); @@ -333,7 +334,7 @@ public abstract class BaseTestCellComment { comment = drawing.createCellComment(anchor); cell.setCellComment(comment); anchor = comment.getClientAnchor(); - + if (sheet instanceof HSSFSheet) { assertEquals(0, anchor.getCol1()); assertEquals(0, anchor.getDx1()); @@ -342,7 +343,7 @@ public abstract class BaseTestCellComment { assertEquals(0, anchor.getCol2()); assertEquals(0, anchor.getDx2()); assertEquals(0, anchor.getRow2()); - assertEquals(0, anchor.getDy2()); + 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() @@ -355,33 +356,35 @@ public abstract class BaseTestCellComment { assertEquals( 3, anchor.getRow2()); assertEquals(16*EMU_PER_PIXEL, anchor.getDy2()); } - + wb.close(); } - + @Test public void attemptToSave2CommentsWithSameCoordinates() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - patriarch.createCellComment(factory.createClientAnchor()); - - try { + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sh = wb.createSheet(); + CreationHelper factory = wb.getCreationHelper(); + Drawing patriarch = sh.createDrawingPatriarch(); patriarch.createCellComment(factory.createClientAnchor()); - _testDataProvider.writeOutAndReadBack(wb); - fail("Should not be able to create a corrupted workbook with multiple cell comments in one cell"); - } catch (IllegalStateException e) { - // HSSFWorkbooks fail when writing out workbook - assertEquals("found multiple cell comments for cell $A$1", e.getMessage()); - } catch (IllegalArgumentException e) { - // XSSFWorkbooks fail when creating and setting the cell address of the comment - assertEquals("Multiple cell comments in one cell are not allowed, cell: A1", e.getMessage()); - } finally { - wb.close(); + + 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 public void getAddress() { Workbook wb = _testDataProvider.createWorkbook(); @@ -389,13 +392,13 @@ public abstract class BaseTestCellComment { 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 public void setAddress() { Workbook wb = _testDataProvider.createWorkbook(); @@ -403,13 +406,13 @@ public abstract class BaseTestCellComment { 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); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java index f3970ff46c..22c5743628 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java @@ -17,13 +17,15 @@ package org.apache.poi.ss.usermodel; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; +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 static org.junit.Assert.*; +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 @@ -44,7 +46,7 @@ public abstract class BaseTestCloneSheet { assertEquals(0, s.addMergedRegion(new CellRangeAddress(0, 1, 0, 1))); Sheet clonedSheet = b.cloneSheet(0); - assertEquals("One merged area", 1, clonedSheet.getNumMergedRegions()); + assertEquals(1, clonedSheet.getNumMergedRegions(), "One merged area"); b.close(); } @@ -60,12 +62,12 @@ public abstract class BaseTestCloneSheet { s.setColumnBreak((short) 6); Sheet clone = b.cloneSheet(0); - assertTrue("Row 3 not broken", clone.isRowBroken(3)); - assertTrue("Column 6 not broken", clone.isColumnBroken((short) 6)); + assertTrue(clone.isRowBroken(3), "Row 3 not broken"); + assertTrue(clone.isColumnBroken((short) 6), "Column 6 not broken"); s.removeRowBreak(3); - assertTrue("Row 3 still should be broken", clone.isRowBroken(3)); + assertTrue(clone.isRowBroken(3), "Row 3 still should be broken"); b.close(); } @@ -76,24 +78,14 @@ public abstract class BaseTestCloneSheet { wb.createSheet("Sheet01"); wb.cloneSheet(0); assertEquals(2, wb.getNumberOfSheets()); - try { - wb.cloneSheet(2); - fail("ShouldFail"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> wb.cloneSheet(2)); } @Test public void testCloneSheetIntInvalid() { Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet01"); - try { - wb.cloneSheet(1); - fail("Should Fail"); - } catch (IllegalArgumentException e) { - // expected here - } + 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 index b0944ee27e..8127d8e4d7 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestColumnShifting.java @@ -18,21 +18,20 @@ */ package org.apache.poi.ss.usermodel; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; - @Before + @BeforeEach public void init() { int rowIndex = 0; sheet1 = wb.createSheet("sheet1"); @@ -63,7 +62,7 @@ public abstract class BaseTestColumnShifting { @Test public void testShift3ColumnsRight() { columnShifter.shiftColumns(1, 2, 3); - + Cell cell = sheet1.getRow(0).getCell(4); assertNull(cell); cell = sheet1.getRow(1).getCell(4); @@ -76,12 +75,7 @@ public abstract class BaseTestColumnShifting { @Test public void testShiftLeft() { - try { - columnShifter.shiftColumns(1, 2, -3); - fail("Shift to negative indices should throw exception"); - } - catch(IllegalStateException e){ - assertTrue(true); - } + 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 index 646b0bb4ad..3d972cd49c 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java @@ -19,12 +19,12 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -34,7 +34,8 @@ 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.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; /** * Base tests for Conditional Formatting, for both HSSF and XSSF @@ -50,70 +51,47 @@ public abstract class BaseTestConditionalFormatting { return true; } - protected abstract void assertColour(String hexExpected, Color actual); + protected abstract void assertColor(String hexExpected, Color actual); @Test - public void testBasic() throws IOException { + public void testBasic() throws Throwable { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sh = wb.createSheet(); SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> sheetCF.getConditionalFormattingAt(0)); + assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - try { - sheetCF.removeConditionalFormatting(0); - fail("expected exception"); - } catch (IllegalArgumentException e) { - 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"); - try { - sheetCF.addConditionalFormatting(null, rule1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("regions must not be null")); - } - try { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, - (ConditionalFormattingRule) null); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("cfRules must not be null")); - } - try { + 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[0]); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("cfRules must not be empty")); - } + new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, + new ConditionalFormattingRule[]{rule1, rule2, rule3, rule4}); if (applyLimitOf3()) { - try { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, - new ConditionalFormattingRule[]{rule1, rule2, rule3, rule4}); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3")); - } + e = assertThrows(IllegalArgumentException.class, exec); + assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3")); } else { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A3")}, - new ConditionalFormattingRule[]{rule1, rule2, rule3, rule4}); + exec.execute(); } } } @@ -273,34 +251,25 @@ public abstract class BaseTestConditionalFormatting { // adjacent address are merged int formatIndex = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); + new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A5")}, rule1); assertEquals(0, formatIndex); assertEquals(1, sheetCF.getNumConditionalFormattings()); sheetCF.removeConditionalFormatting(0); assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } + + 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); + new CellRangeAddress[]{CellRangeAddress.valueOf("A1:A5")}, rule1); assertEquals(0, formatIndex); assertEquals(1, sheetCF.getNumConditionalFormattings()); sheetCF.removeConditionalFormatting(0); assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } + + e = assertThrows(IllegalArgumentException.class, () -> sheetCF.getConditionalFormattingAt(0)); + assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); } } @@ -611,11 +580,11 @@ public abstract class BaseTestConditionalFormatting { // 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) { - assertColour("0:8080:0", cr.getFontFormatting().getFontColor()); - assertColour("CCCC:FFFF:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); + assertColor("0:8080:0", cr.getFontFormatting().getFontColor()); + assertColor("CCCC:FFFF:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); } else { - assertColour("006100", cr.getFontFormatting().getFontColor()); - assertColour("C6EFCE", cr.getPatternFormatting().getFillBackgroundColorColor()); + assertColor("006100", cr.getFontFormatting().getFontColor()); + assertColor("C6EFCE", cr.getPatternFormatting().getFillBackgroundColorColor()); } @@ -635,11 +604,11 @@ public abstract class BaseTestConditionalFormatting { // 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) { - assertColour("8080:0:8080", cr.getFontFormatting().getFontColor()); - assertColour("FFFF:9999:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); + assertColor("8080:0:8080", cr.getFontFormatting().getFontColor()); + assertColor("FFFF:9999:CCCC", cr.getPatternFormatting().getFillBackgroundColorColor()); } else { - assertColour("9C0006", cr.getFontFormatting().getFontColor()); - assertColour("FFC7CE", cr.getPatternFormatting().getFillBackgroundColorColor()); + assertColor("9C0006", cr.getFontFormatting().getFontColor()); + assertColor("FFC7CE", cr.getPatternFormatting().getFillBackgroundColorColor()); } @@ -798,7 +767,7 @@ public abstract class BaseTestConditionalFormatting { assertEquals(0, databar.getWidthMin()); assertEquals(100, databar.getWidthMax()); - assertColour(color, databar.getColor()); + assertColor(color, databar.getColor()); ConditionalFormattingThreshold th; th = databar.getMinThreshold(); @@ -877,7 +846,7 @@ public abstract class BaseTestConditionalFormatting { // Colors should match for (int i=0; i readCf.setFormattingRanges(null)); } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java index 2208cf5f49..4f6d4b6aa9 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests of implementation of {@link DataFormat} @@ -116,7 +116,7 @@ public abstract class BaseTestDataFormat { DataFormat dataFormat = wb.createDataFormat(); short fmtIdx = dataFormat.getFormat(fmt); String readbackFmt = dataFormat.getFormat(fmtIdx); - assertEquals(msg, fmt, readbackFmt); + assertEquals(fmt, readbackFmt, msg); } } @@ -158,10 +158,10 @@ public abstract class BaseTestDataFormat { String expWhole = r.getCell(2).getStringCellValue(); String exp3dp = r.getCell(4).getStringCellValue(); - assertEquals("Wrong formatting of " + value + " for row " + rn, - expWhole, fmt.formatCellValue(r.getCell(1), eval)); - assertEquals("Wrong formatting of " + value + " for row " + rn, - exp3dp, fmt.formatCellValue(r.getCell(3), eval)); + 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); } } @@ -198,7 +198,7 @@ public abstract class BaseTestDataFormat { assertEquals("-"+pound+" 12,345", formatter.formatCellValue(nve)); // TODO Fix this to not have an extra 0 at the end //assertEquals(pound+" - ", formatter.formatCellValue(zero)); - + wb.close(); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java index 5b8bdc84cc..162deac99f 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java @@ -25,7 +25,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class for testing Excel's data validation mechanism @@ -492,7 +492,7 @@ public abstract class BaseTestDataValidation { log("done !"); _testDataProvider.writeOutAndReadBack(wb).close(); - + wb.close(); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java index 5044bdcf34..501225aedc 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java @@ -17,18 +17,18 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java index 61d3f41e33..68dee47f29 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java @@ -17,15 +17,20 @@ 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.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; /** * Common superclass for testing implementation of {@link FormulaEvaluator} @@ -62,7 +67,7 @@ public abstract class BaseTestFormulaEvaluator { assertEquals(6.0, c1.getNumericCellValue(), 0.0001); assertEquals(5.0, c2.getNumericCellValue(), 0.0001); - + wb.close(); } @@ -107,7 +112,7 @@ public abstract class BaseTestFormulaEvaluator { assertEquals(17.5, c2.getNumericCellValue(), 0.0001); assertEquals(1, c3.getNumericCellValue(), 0.0001); assertEquals(4, c4.getNumericCellValue(), 0.0001); - + wb.close(); } @@ -134,7 +139,7 @@ public abstract class BaseTestFormulaEvaluator { cell = sheet.getRow(4).getCell(0); assertEquals("B5", cell.getCellFormula()); assertEquals("UniqueDocumentNumberID", evaluator.evaluate(cell).getStringValue()); - + wb.close(); } @@ -173,7 +178,7 @@ public abstract class BaseTestFormulaEvaluator { 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(); } @@ -207,10 +212,10 @@ public abstract class BaseTestFormulaEvaluator { 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 public void testRepeatedEvaluation() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); @@ -218,37 +223,37 @@ public abstract class BaseTestFormulaEvaluator { 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(); } @@ -323,10 +328,10 @@ public abstract class BaseTestFormulaEvaluator { 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 public void evaluateInCellReturnsSameCell() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { @@ -638,8 +643,8 @@ public abstract class BaseTestFormulaEvaluator { double result = a3.getNumericCellValue(); // result is correct - assertTrue(String.format(Locale.ROOT, "Expected %f to be greater than %f", result, 2.0), result > 2.0); - assertTrue(String.format(Locale.ROOT, "Expected %f to be less than %f", result, 4.0), result < 4.0); + 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()); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java index 54b306e039..c269e2e6ea 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java @@ -17,16 +17,16 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; +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.junit.Test; 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 diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java index e458a3e778..2c35c79302 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Arrays; @@ -34,7 +34,7 @@ import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; import org.apache.poi.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests of implementations of {@link org.apache.poi.ss.usermodel.Name}. @@ -51,159 +51,130 @@ public abstract class BaseTestNamedRange { @Test public final void testCreate() throws Exception { - // Create a new workbook - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Test1"); - wb.createSheet("Testing Named Ranges"); + try (Workbook wb = _testDataProvider.createWorkbook()) { + wb.createSheet("Test1"); + wb.createSheet("Testing Named Ranges"); - Name name1 = wb.createName(); - name1.setNameName("testOne"); + Name name1 = wb.createName(); + name1.setNameName("testOne"); - //setting a duplicate name should throw IllegalArgumentException - Name name2 = wb.createName(); - try { - name2.setNameName("testOne"); - fail("expected exception"); - } catch (IllegalArgumentException e){ + //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 - try { - name2.setNameName("TESTone"); - fail("expected exception"); - } catch (IllegalArgumentException e){ + + //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"); + name2.setNameName("testTwo"); - String ref1 = "Test1!$A$1:$B$1"; - name1.setRefersToFormula(ref1); - assertEquals(ref1, name1.getRefersToFormula()); - assertEquals("Test1", name1.getSheetName()); + 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()); + 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()); - try { - name1.setSheetIndex(2); - fail("should throw IllegalArgumentException"); - } catch(IllegalArgumentException e){ + 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()); + name1.setSheetIndex(1); + assertEquals(1, name1.getSheetIndex()); - //-1 means the name applies to the entire workbook - 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) { - try { - name1.setNameName(name); - fail("should have thrown exceptiuon due to invalid name: " + name); - } catch (IllegalArgumentException e) { - // expected during successful test + //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); } } - - wb.close(); } @Test public final void testUnicodeNamedRange() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - wb1.createSheet("Test"); - Name name = wb1.createName(); - name.setNameName("\u03B1"); - name.setRefersToFormula("Test!$D$3:$E$8"); + try (HSSFWorkbook wb1 = new HSSFWorkbook()) { + wb1.createSheet("Test"); + Name name = wb1.createName(); + name.setNameName("\u03B1"); + name.setRefersToFormula("Test!$D$3:$E$8"); + try (HSSFWorkbook wb2 = HSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) { + Name name2 = wb2.getName("\u03B1"); - HSSFWorkbook wb2 = HSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - Name name2 = wb2.getName("\u03B1"); + assertNotNull(name2); + assertEquals("\u03B1", name2.getNameName()); + assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula()); - assertEquals("\u03B1", name2.getNameName()); - assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula()); - - wb2.close(); - wb1.close(); + } + } } @Test public final void testAddRemove() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - assertEquals(0, wb.getNumberOfNames()); - Name name1 = wb.createName(); - name1.setNameName("name1"); - assertEquals(1, wb.getNumberOfNames()); + 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 name2 = wb.createName(); + name2.setNameName("name2"); + assertEquals(2, wb.getNumberOfNames()); - Name name3 = wb.createName(); - name3.setNameName("name3"); - assertEquals(3, wb.getNumberOfNames()); + Name name3 = wb.createName(); + name3.setNameName("name3"); + assertEquals(3, wb.getNumberOfNames()); - wb.removeName(wb.getName("name2")); - assertEquals(2, wb.getNumberOfNames()); - - wb.close(); + wb.removeName(wb.getName("name2")); + assertEquals(2, wb.getNumberOfNames()); + } } @Test public final void testScope() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet(); - wb.createSheet(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + wb.createSheet(); + wb.createSheet(); - Name name; - - name = wb.createName(); - name.setNameName("aaa"); - name = wb.createName(); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ + wb.createName().setNameName("aaa"); + Exception e = assertThrows(Exception.class, () -> wb.createName().setNameName("aaa")); assertEquals("The workbook already contains this name: aaa", e.getMessage()); - } - name = wb.createName(); - name.setSheetIndex(0); - name.setNameName("aaa"); - name = wb.createName(); - name.setSheetIndex(0); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ + 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()); - } - name = wb.createName(); - name.setSheetIndex(1); - name.setNameName("aaa"); - name = wb.createName(); - name.setSheetIndex(1); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ + 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()); - - wb.close(); + assertEquals(3, wb.getNames("aaa").size()); + } } /** @@ -247,13 +218,13 @@ public abstract class BaseTestNamedRange { // Read the Excel file and verify its content Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); Name nm1 = wb2.getName("RangeTest1"); - assertEquals("Name is " + nm1.getNameName(), "RangeTest1", nm1.getNameName()); - assertEquals("Reference is " + nm1.getRefersToFormula(), (wb2.getSheetName(0) + "!$A$1:$L$41"), nm1.getRefersToFormula()); + 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("Name is " + nm2.getNameName(), "RangeTest2", nm2.getNameName()); - assertEquals("Reference is " + nm2.getRefersToFormula(), (wb2.getSheetName(1) + "!$A$1:$O$21"), nm2.getRefersToFormula()); - + 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(); } @@ -272,9 +243,9 @@ public abstract class BaseTestNamedRange { String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - + workbook.close(); } @@ -293,9 +264,9 @@ public abstract class BaseTestNamedRange { String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea); - + workbook.close(); } @@ -315,9 +286,9 @@ public abstract class BaseTestNamedRange { Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); String retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - + assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); + assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); + wb2.close(); wb1.close(); } @@ -327,51 +298,50 @@ public abstract class BaseTestNamedRange { */ @Test public final void testMultiplePrintAreaFile() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); + 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.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); + wb1.setPrintArea(0, reference1); + wb1.setPrintArea(1, reference2); + wb1.setPrintArea(2, reference3); - //Check created print areas - String retrievedPrintArea; + //Check created print areas + String retrievedPrintArea; - retrievedPrintArea = wb1.getPrintArea(0); - assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); + retrievedPrintArea = wb1.getPrintArea(0); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); + assertEquals("Sheet1!" + reference1, retrievedPrintArea); - retrievedPrintArea = wb1.getPrintArea(1); - assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); + retrievedPrintArea = wb1.getPrintArea(1); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); + assertEquals("Sheet2!" + reference2, retrievedPrintArea); - retrievedPrintArea = wb1.getPrintArea(2); - assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); + retrievedPrintArea = wb1.getPrintArea(2); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); + assertEquals("Sheet3!" + reference3, retrievedPrintArea); - // Check print areas after re-reading workbook - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + // Check print areas after re-reading workbook + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { - retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); + retrievedPrintArea = wb2.getPrintArea(0); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); + assertEquals("Sheet1!" + reference1, retrievedPrintArea); - retrievedPrintArea = wb2.getPrintArea(1); - assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); + retrievedPrintArea = wb2.getPrintArea(1); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); + assertEquals("Sheet2!" + reference2, retrievedPrintArea); - retrievedPrintArea = wb2.getPrintArea(2); - assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); - - wb2.close(); - wb1.close(); + retrievedPrintArea = wb2.getPrintArea(2); + assertNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); + assertEquals("Sheet3!" + reference3, retrievedPrintArea); + } + } } /** @@ -388,9 +358,9 @@ public abstract class BaseTestNamedRange { String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - + workbook.close(); } @@ -407,9 +377,9 @@ public abstract class BaseTestNamedRange { String reference = "$A$1:$B$1,$D$1:$F$2"; workbook.setPrintArea(0, reference); String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + 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(); } @@ -419,19 +389,19 @@ public abstract class BaseTestNamedRange { */ @Test public final void testPrintAreaRemove() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - workbook.getSheetName(0); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + workbook.createSheet("Test Print Area"); + workbook.getSheetName(0); - workbook.setPrintArea(0, 0, 1, 0, 0); + workbook.setPrintArea(0, 0, 1, 0, 0); - String retrievedPrintArea = workbook.getPrintArea(0); + String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); + assertNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); - workbook.removePrintArea(0); - assertNull("PrintArea was not removed", workbook.getPrintArea(0)); - workbook.close(); + workbook.removePrintArea(0); + assertNull(workbook.getPrintArea(0), "PrintArea was not removed"); + } } /** @@ -461,13 +431,13 @@ public abstract class BaseTestNamedRange { Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); Name nm = wb2.getName("RangeTest"); - assertEquals("Name is " + nm.getNameName(), "RangeTest", nm.getNameName()); - assertEquals("Reference is " + nm.getRefersToFormula(), (wb2.getSheetName(0) + "!$D$4:$E$8"), nm.getRefersToFormula()); + 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("Name is " + nm.getNameName(), "AnotherTest", nm.getNameName()); - assertEquals("Reference is " + nm.getRefersToFormula(), newNamedRange2.getRefersToFormula(), nm.getRefersToFormula()); - + assertEquals("AnotherTest", nm.getNameName(), "Name is " + nm.getNameName()); + assertEquals(newNamedRange2.getRefersToFormula(), nm.getRefersToFormula(), "Reference is " + nm.getRefersToFormula()); + wb2.close(); wb1.close(); } @@ -499,7 +469,7 @@ public abstract class BaseTestNamedRange { // retrieve the cell at the named range and test its contents AreaReference aref = wb.getCreationHelper().createAreaReference(aNamedCell.getRefersToFormula()); - assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell()); + assertTrue(aref.isSingleCell(), "Should be exactly 1 cell in the named cell :'" +cellName+"'"); CellReference cref = aref.getFirstCell(); assertNotNull(cref); @@ -508,7 +478,7 @@ public abstract class BaseTestNamedRange { Row r = sheet.getRow(cref.getRow()); Cell c = r.getCell(cref.getCol()); String contents = c.getRichStringCellValue().getString(); - assertEquals("Contents of cell retrieved by its named reference", contents, cellValue); + assertEquals(contents, cellValue, "Contents of cell retrieved by its named reference"); wb.close(); } @@ -543,8 +513,8 @@ public abstract class BaseTestNamedRange { Row r = sheet.getRow(cref.getRow()); Cell c = r.getCell(cref.getCol()); String contents = c.getRichStringCellValue().getString(); - assertEquals("Contents of cell retrieved by its named reference", contents, cvalue); - + assertEquals(contents, cvalue, "Contents of cell retrieved by its named reference"); + wb.close(); } @@ -571,7 +541,7 @@ public abstract class BaseTestNamedRange { Name n = wb.createName(); n.setNameName("UPSState"); String formula = n.getRefersToFormula(); - + // bug 46973: fails here with IllegalArgumentException // ptgs must not be null @@ -589,8 +559,8 @@ public abstract class BaseTestNamedRange { // contrived example to expose bug: n.setRefersToFormula("if(A1,\"#REF!\", \"\")"); - assertFalse("Identified bug in recoginising formulas referring to deleted cells", n.isDeleted()); - + assertFalse(n.isDeleted(), "Identified bug in recoginising formulas referring to deleted cells"); + wb.close(); } @@ -608,35 +578,30 @@ public abstract class BaseTestNamedRange { n.setFunction(false); assertFalse(n.isFunctionName()); - + wb.close(); } @Test public final void testDefferedSetting() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n1 = wb.createName(); - assertNull(n1.getRefersToFormula()); - assertEquals("", n1.getNameName()); + 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()); + Name n2 = wb.createName(); + assertNull(n2.getRefersToFormula()); + assertEquals("", n2.getNameName()); - n1.setNameName("sale_1"); - n1.setRefersToFormula("10"); + n1.setNameName("sale_1"); + n1.setRefersToFormula("10"); - n2.setNameName("sale_2"); - n2.setRefersToFormula("20"); + n2.setNameName("sale_2"); + n2.setRefersToFormula("20"); - try { - n2.setNameName("sale_1"); - fail("Expected exception"); - } catch(Exception e){ + Exception e = assertThrows(Exception.class, () -> n2.setNameName("sale_1")); assertEquals("The workbook already contains this name: sale_1", e.getMessage()); } - - wb.close(); } @Test @@ -659,23 +624,23 @@ public abstract class BaseTestNamedRange { x2.setSheetIndex(wb.getSheetIndex("sheet2")); List names = wb.getNames("x"); - assertEquals("Had: " + names, 2, names.size()); + 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 @Test public void testValid() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); - + Name name = wb.createName(); for (String valid : Arrays.asList( "Hello", @@ -688,63 +653,54 @@ public abstract class BaseTestNamedRange { )) { name.setNameName(valid); } - + wb.close(); } - + @Test public void testInvalid() { Workbook wb = _testDataProvider.createWorkbook(); - + Name name = wb.createName(); - try { - name.setNameName(""); - fail("expected exception: (blank)"); - } catch (final IllegalArgumentException e) { - assertEquals("Name cannot be blank", e.getMessage()); - } - + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> name.setNameName("")); + assertEquals("Name cannot be blank", e.getMessage()); + for (String invalid : Arrays.asList( - "1number", - "Sheet1!A1", - "Exclamation!", - "Has Space", - "Colon:", - "A-Minus", - "A+Plus", - "Dollar$", - ".periodAtBeginning", - "R", //special shorthand - "C", //special shorthand - "A1", // A1-style cell reference - "R1C1", // R1C1-style cell reference - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters" - )) { - try { - name.setNameName(invalid); - fail("expected exception: " + invalid); - } catch (final IllegalArgumentException e) { - assertTrue(invalid, - e.getMessage().startsWith("Invalid name: '"+invalid+"'")); - } + "1number", + "Sheet1!A1", + "Exclamation!", + "Has Space", + "Colon:", + "A-Minus", + "A+Plus", + "Dollar$", + ".periodAtBeginning", + "R", //special shorthand + "C", //special shorthand + "A1", // A1-style cell reference + "R1C1", // R1C1-style cell reference + "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ + "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ + "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ + "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ + "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters" + )) { + 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 public void renameSheetWithNamedRangeReferringToUnicodeSheetName() { Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet\u30FB1"); - + Name name = wb.createName(); name.setNameName("test_named_range"); name.setRefersToFormula("'Sheet\u30FB201'!A1:A6"); - + wb.setSheetName(0, "Sheet 1"); IOUtils.closeQuietly(wb); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java index b7cfac9000..09c673ccc3 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +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; @@ -43,7 +43,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public abstract class BaseTestPicture { @@ -64,12 +64,12 @@ public abstract class BaseTestPicture { double emuPX = Units.EMU_PER_PIXEL; - assertEquals("the image height differs", inpDim.getHeight(), cmpDim.getHeight(), emuPX*6); - assertEquals("the image width differs", inpDim.getWidth(), cmpDim.getWidth(), emuPX*6); - assertEquals("the starting column differs", inpCA.getCol1(), cmpCA.getCol1()); - assertEquals("the column x-offset differs", inpCA.getDx1(), cmpCA.getDx1(), 1); - assertEquals("the column y-offset differs", inpCA.getDy1(), cmpCA.getDy1(), 1); - assertEquals("the ending columns differs", inpCA.getCol2(), cmpCA.getCol2()); + 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(), 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(); @@ -77,8 +77,8 @@ public abstract class BaseTestPicture { Dimension imgDim = input.getImageDimension(); - assertEquals("the image height differs", imgDim.getHeight(), inpDim.getHeight()/emuPX, 1); - assertEquals("the image width differs", imgDim.getWidth(), inpDim.getWidth()/emuPX, 1); + assertEquals(imgDim.getHeight(), inpDim.getHeight()/emuPX, 1, "the image height differs"); + assertEquals(imgDim.getWidth(), inpDim.getWidth()/emuPX, 1, "the image width differs"); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java index f044b6f0b7..f01f16a0e4 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRangeCopier.java @@ -19,17 +19,17 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Ignore +@Disabled public abstract class BaseTestRangeCopier { protected Sheet sheet1; protected Sheet sheet2; diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java index 1634330138..2579ac1e98 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java @@ -17,20 +17,21 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * A base class for testing implementations of @@ -139,76 +140,56 @@ public abstract class BaseTestRow { assertEquals(-1, row.getFirstCellNum()); assertEquals(0, row.getPhysicalNumberOfCells()); } - + wb2.close(); } protected void baseTestRowBounds(int maxRowNum) throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - //Test low row bound - sheet.createRow(0); - //Test low row bound exception - try { - sheet.createRow(-1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertTrue("Did not find expected error message, had: " + e, - e.getMessage().startsWith("Invalid row number (-1)")); - } + 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 - try { - sheet.createRow(maxRowNum + 1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage()); + //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()); } - - workbook.close(); } protected void baseTestCellBounds(int maxCellNum) throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet(); - Row row = sheet.createRow(0); - //Test low cell bound - try { - row.createCell(-1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test + 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 - try { - row.createCell(maxCellNum + 1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertTrue(e.getMessage().startsWith("Invalid column index ("+(maxCellNum+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()); + } + } } - for(int i=0; i < maxCellNum; i++){ - row.createCell(i); - } - assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - row = sheet.getRow(0); - assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); - for(int i=0; i < maxCellNum; i++){ - Cell cell = row.getCell(i); - assertEquals(i, cell.getColumnIndex()); - } - wb2.close(); } /** @@ -223,9 +204,7 @@ public abstract class BaseTestRow { // New row has last col -1 assertEquals(-1, row.getLastCellNum()); - if(row.getLastCellNum() == 0) { - fail("Identified bug 43901"); - } + assertNotEquals(0, row.getLastCellNum(), "Identified bug 43901"); // Create two cells, will return one higher // than that for the last number @@ -307,7 +286,7 @@ public abstract class BaseTestRow { assertNull(row.getCell(3)); assertNull(row.getCell(4)); assertEquals(CellType.NUMERIC, row.getCell(5).getCellType()); - + workbook.close(); } @@ -452,7 +431,7 @@ public abstract class BaseTestRow { // Save, load and re-check Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); wb1.close(); - + sheet = wb2.getSheetAt(0); row1 = sheet.getRow(0); @@ -464,10 +443,10 @@ public abstract class BaseTestRow { assertNull(row1.getRowStyle()); assertEquals(style, row2.getRowStyle()); assertEquals(4, style.getDataFormat()); - + wb2.close(); } - + @Test public void testCellShiftingRight() { Workbook wb = _testDataProvider.createWorkbook(); @@ -480,26 +459,23 @@ public abstract class BaseTestRow { row.createCell(4, CellType.NUMERIC).setCellValue(4);//E row.createCell(5, CellType.NUMERIC).setCellValue(5);//F row.createCell(6, CellType.NUMERIC).setCellValue(6);//G - try { - row.shiftCellsLeft(6, 4, 2); // range [6-4] is illegal - fail("expected shiftLeft to fail"); - } catch (IllegalArgumentException e){ - 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); - } + + 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 public void testCellShiftingLeft() { @@ -513,24 +489,21 @@ public abstract class BaseTestRow { row.createCell(4, CellType.NUMERIC).setCellValue(4);//E row.createCell(5, CellType.NUMERIC).setCellValue(5);//F row.createCell(6, CellType.NUMERIC).setCellValue(6);//G - try { - row.shiftCellsLeft(4, 6, -2); // step = -1 is illegal - fail("expected shiftLeft to fail"); - } catch (IllegalArgumentException e){ - 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); - } + + 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 @@ -538,13 +511,11 @@ public abstract class BaseTestRow { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet("sheet1"); - assertEquals("Sheet without rows should return -1 as lastRowNum", - -1, sheet.getLastRowNum()); + assertEquals(-1, sheet.getLastRowNum(), "Sheet without rows should return -1 as lastRowNum"); Row row = sheet.createRow(0); assertNotNull(row); - assertEquals("Sheet with one row should return 0 as lastRowNum", - 0, sheet.getLastRowNum()); + assertEquals(0, sheet.getLastRowNum(), "Sheet with one row should return 0 as lastRowNum"); } @Test @@ -552,12 +523,10 @@ public abstract class BaseTestRow { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet("sheet1"); - assertEquals("Sheet without rows should return -1 as firstRowNum", - -1, sheet.getFirstRowNum()); + assertEquals(-1, sheet.getFirstRowNum(), "Sheet without rows should return -1 as firstRowNum"); Row row = sheet.createRow(0); assertNotNull(row); - assertEquals("Sheet with one row should return 0 as firstRowNum", - 0, sheet.getFirstRowNum()); + 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 index 2af3022617..978c36c278 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java @@ -18,15 +18,15 @@ package org.apache.poi.ss.usermodel; import static org.apache.poi.POITestCase.assertBetween; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +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; @@ -44,7 +44,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Common superclass for testing {@link org.apache.poi.hssf.usermodel.HSSFCell}, @@ -105,24 +105,24 @@ public abstract class BaseTestSheet { } } - @Test(expected=IllegalArgumentException.class) + @Test public void createRowBeforeFirstRow() throws IOException { try (Workbook workbook = _testDataProvider.createWorkbook()) { final Sheet sh = workbook.createSheet(); sh.createRow(0); // Negative rows not allowed - sh.createRow(-1); + assertThrows(IllegalArgumentException.class, () -> sh.createRow(-1)); } } - @Test(expected=IllegalArgumentException.class) + @Test public 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 - sh.createRow(version.getLastRowIndex() + 1); + assertThrows(IllegalArgumentException.class, () -> sh.createRow(version.getLastRowIndex() + 1)); } } @@ -189,12 +189,12 @@ public abstract class BaseTestSheet { //Check that the cells are not somehow linked cell.setCellValue(factory.createRichTextString("Difference Check")); cell2.setCellFormula("cos(2)"); - if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) { - fail("string cell not properly cloned"); - } - if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) { - fail("formula cell not properly cloned"); - } + + 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)"); } @@ -281,34 +281,34 @@ public abstract class BaseTestSheet { final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 assertThrows( - "Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " + - "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")", IllegalStateException.class, - () -> sheet.addMergedRegion(duplicateRegion) + () -> 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( - "Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " + - "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")", IllegalStateException.class, - () -> sheet.addMergedRegion(partiallyOverlappingRegion) + () -> 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( - "Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " + - "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")", IllegalStateException.class, - () -> sheet.addMergedRegion(subsetRegion) + () -> 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( - "Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " + - "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")", IllegalStateException.class, - () -> sheet.addMergedRegion(supersetRegion) + () -> 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); @@ -326,9 +326,9 @@ public abstract class BaseTestSheet { final Sheet sheet = wb.createSheet(); final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1"); assertThrows( - "Should not be able to add a single-cell merged region (" + region.formatAsString() + ")", IllegalArgumentException.class, - () -> sheet.addMergedRegion(region) + () -> sheet.addMergedRegion(region), + "Should not be able to add a single-cell merged region (" + region.formatAsString() + ")" ); } } @@ -387,27 +387,27 @@ public abstract class BaseTestSheet { sheet.removeMergedRegion(0); region = sheet.getMergedRegion(0); - assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow()); + assertEquals(2, region.getFirstRow(), "Left over region should be starting at row 2"); sheet.removeMergedRegion(0); - assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions()); + 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("there should now be one merged region!", 1, sheet.getNumMergedRegions()); + assertEquals(1, sheet.getNumMergedRegions(), "there should now be one merged region!"); sheet.removeMergedRegion(0); - assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions()); + assertEquals(0, sheet.getNumMergedRegions(), "there should now be zero merged regions!"); //add it again! region.setLastRow(4); assertEquals(0, sheet.addMergedRegion(region)); - assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); + assertEquals(1, sheet.getNumMergedRegions(), "there should now be one merged region!"); //should exist now! - assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); + assertTrue(1 <= sheet.getNumMergedRegions(), "there isn't more than one merged region in there"); region = sheet.getMergedRegion(0); - assertEquals("the merged row to doesn't match the one we put in ", 4, region.getLastRow()); + assertEquals(4, region.getLastRow(), "the merged row to doesn't match the one we put in "); } } @@ -461,7 +461,7 @@ public abstract class BaseTestSheet { region = sheet.getMergedRegion(0); CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3"); - assertEquals("Merged region should shift down a row", expectedRegion, region); + assertEquals(expectedRegion, region, "Merged region should shift down a row"); } } @@ -493,9 +493,9 @@ public abstract class BaseTestSheet { // 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( - "region3 overlaps already added merged region2.", IllegalStateException.class, - () -> sh.addMergedRegion(region3) + () -> sh.addMergedRegion(region3), + "region3 overlaps already added merged region2." ); assertFalse(sh.getMergedRegions().contains(region3)); @@ -504,9 +504,9 @@ public abstract class BaseTestSheet { // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time) assertThrows( - "Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2.", IllegalStateException.class, - sh::validateMergedRegions + sh::validateMergedRegions, + "Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2." ); } } @@ -640,9 +640,10 @@ public abstract class BaseTestSheet { r.createCell(1).setCellFormula("A1*2"); Sheet s1 = wb.cloneSheet(0); r = s1.getRow(0); - assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check + // sanity check + assertEquals(r.getCell(0).getNumericCellValue(), 1, 0, "double"); assertNotNull(r.getCell(1)); - assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2"); + assertEquals(r.getCell(1).getCellFormula(), "A1*2", "formula"); } } @@ -660,7 +661,7 @@ public abstract class BaseTestSheet { Cell cell = row.createCell(0); CellStyle style2 = cell.getCellStyle(); assertNotNull(style2); - assertEquals("style should match", style.getIndex(), style2.getIndex()); + assertEquals(style.getIndex(), style2.getIndex(), "style should match"); } } @@ -1187,15 +1188,15 @@ public abstract class BaseTestSheet { Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(5).createCell(1); - assertEquals("list size before add", 0, sheet.getHyperlinkList().size()); + assertEquals(0, sheet.getHyperlinkList().size(), "list size before add"); cell.setHyperlink(hyperlink); - assertEquals("list size after add", 1, sheet.getHyperlinkList().size()); + assertEquals(1, sheet.getHyperlinkList().size(), "list size after add"); - assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0)); + assertEquals(hyperlink, sheet.getHyperlinkList().get(0), "list"); CellAddress B6 = new CellAddress(5, 1); - assertEquals("row, col", hyperlink, sheet.getHyperlink(5, 1)); - assertEquals("addr", hyperlink, sheet.getHyperlink(B6)); - assertNull("no hyperlink at A1", sheet.getHyperlink(CellAddress.A1)); + assertEquals(hyperlink, sheet.getHyperlink(5, 1), "row, col"); + assertEquals(hyperlink, sheet.getHyperlink(B6), "addr"); + assertNull(sheet.getHyperlink(CellAddress.A1), "no hyperlink at A1"); } } @@ -1302,9 +1303,8 @@ public abstract class BaseTestSheet { // active cell behavior is undefined if not set. // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null. - if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) { - fail("If not set, active cell should default to null or A1"); - } + 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); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java index abbb0d1815..c7584ef978 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Calendar; import java.util.Date; @@ -27,9 +27,9 @@ import java.util.Locale; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +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 @@ -42,13 +42,13 @@ public abstract class BaseTestSheetAutosizeColumn { private static Locale userLocale; - @BeforeClass + @BeforeAll public static void initLocale() { userLocale = LocaleUtil.getUserLocale(); LocaleUtil.setUserLocale(Locale.ROOT); } - @AfterClass + @AfterAll public static void resetLocale() { LocaleUtil.setUserLocale(userLocale); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java index 1611f95a8e..78642d21b8 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java @@ -17,17 +17,17 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class BaseTestSheetHiding { @@ -47,61 +47,50 @@ public abstract class BaseTestSheetHiding { _file2 = file2; } - @Before + @BeforeEach public void setUp() { wbH = _testDataProvider.openSampleWorkbook(_file1); wbU = _testDataProvider.openSampleWorkbook(_file2); } - @After + @AfterEach public void teadDown() throws IOException { wbH.close(); wbU.close(); } - + @Test public final void testSheetVisibility() throws IOException { - 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)); + try (Workbook wb = _testDataProvider.createWorkbook()) { + wb.createSheet("MySheet"); - // verify limits-check + assertFalse(wb.isSheetHidden(0)); + assertFalse(wb.isSheetVeryHidden(0)); + assertEquals(SheetVisibility.VISIBLE, wb.getSheetVisibility(0)); - // check sheet-index with one more => throws exception - try { - wb.setSheetVisibility(1, SheetVisibility.HIDDEN); - fail("Should catch exception here"); - } catch (IllegalArgumentException e) { - // expected here + 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)); } - - // check sheet-index with index out of bounds => throws exception - try { - wb.setSheetVisibility(10, SheetVisibility.HIDDEN); - fail("Should catch exception here"); - } catch (IllegalArgumentException e) { - // expected here - } - - wb.close(); } /** diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java index 407cba71c8..86f56daf61 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftColumns.java @@ -18,11 +18,12 @@ */ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; @@ -31,8 +32,8 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class BaseTestSheetShiftColumns { protected Sheet sheet1; @@ -41,7 +42,7 @@ public abstract class BaseTestSheetShiftColumns { protected ITestDataProvider _testDataProvider; - @Before + @BeforeEach public void init() { int rowIndex = 0; sheet1 = workbook.createSheet("sheet1"); @@ -157,9 +158,9 @@ public abstract class BaseTestSheetShiftColumns { assertNull(newb6Null); } - @Test(expected = IllegalStateException.class) + @Test public void testShiftTwoColumnsLeft() { - sheet1.shiftColumns(1, 2, -2); + assertThrows(IllegalStateException.class, () -> sheet1.shiftColumns(1, 2, -2)); } @Test @@ -229,8 +230,8 @@ public abstract class BaseTestSheetShiftColumns { verifyHyperlink(shiftedRow.getCell(4), HyperlinkType.URL, "https://poi.apache.org/"); // Make sure hyperlinks were moved and not copied - assertNull("Document hyperlink should be moved, not copied", sh.getHyperlink(0, 0)); - assertNull("URL hyperlink should be moved, not copied", sh.getHyperlink(1, 0)); + 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(); @@ -245,11 +246,10 @@ public abstract class BaseTestSheetShiftColumns { private void verifyHyperlink(Cell cell, HyperlinkType linkType, String ref) { assertTrue(cellHasHyperlink(cell)); - if (cell != null) { - Hyperlink link = cell.getHyperlink(); - assertEquals(linkType, link.getType()); - assertEquals(ref, link.getAddress()); - } + assertNotNull(cell); + Hyperlink link = cell.getHyperlink(); + assertEquals(linkType, link.getType()); + assertEquals(ref, link.getAddress()); } private boolean cellHasHyperlink(Cell cell) { diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java index 25a564c917..8b4ecf8eb9 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java @@ -19,12 +19,12 @@ package org.apache.poi.ss.usermodel; import static org.apache.poi.POITestCase.skipTest; import static org.apache.poi.POITestCase.testPassesNow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +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; @@ -36,7 +36,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests row shifting capabilities. @@ -136,16 +136,17 @@ public abstract class BaseTestSheetShiftRows { * When shifting rows, the page breaks should go with it */ @Test - public void testShiftRowBreaks() throws IOException { // TODO - enable XSSF test - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row row = s.createRow(4); - row.createCell(0).setCellValue("test"); - s.setRowBreak(4); + public 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("Row number 6 should have a pagebreak", s.isRowBroken(6)); - wb.close(); + s.shiftRows(4, 4, 2); + assertTrue(s.isRowBroken(6), "Row number 6 should have a pagebreak"); + } } @Test @@ -219,8 +220,8 @@ public abstract class BaseTestSheetShiftRows { assertEquals(2, sheet.getLastRowNum()); // Verify comments are in the position expected - assertNull("Had: " + (sheet.getCellComment(new CellAddress(0,0)) == null ? "null" : sheet.getCellComment(new CellAddress(0,0)).getString()), - sheet.getCellComment(new CellAddress(0,0))); + 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))); } @@ -570,18 +571,17 @@ public abstract class BaseTestSheetShiftRows { verifyHyperlink(shiftedRow.getCell(1), HyperlinkType.URL, "https://poi.apache.org/"); // Make sure hyperlinks were moved and not copied - assertNull("Document hyperlink should be moved, not copied", sh.getHyperlink(0, 0)); - assertNull("URL hyperlink should be moved, not copied", sh.getHyperlink(0, 1)); + 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()); - if (linkAddress.equals(unexpectedLinkAddress)) { - fail("Row 4, including the hyperlink at C4, should have " + - "been deleted when Row 1 was shifted on top of it."); - } + 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 diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java index 0c81191b1a..34d5038544 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java @@ -17,15 +17,15 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +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; @@ -34,8 +34,8 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Common superclass for testing usermodel API for array formulas.
@@ -77,12 +77,8 @@ public abstract class BaseTestSheetUpdateArrayFormulas { Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(0).createCell(0); assertFalse(cell.isPartOfArrayFormulaGroup()); - try { - cell.getArrayFormulaRange(); - fail("expected exception"); - } catch (IllegalStateException e) { - assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - } + 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)); @@ -139,12 +135,12 @@ public abstract class BaseTestSheetUpdateArrayFormulas { * Passing an incorrect formula to sheet.setArrayFormula * should throw FormulaParseException */ - @Test(expected = FormulaParseException.class) + @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); - sheet.setArrayFormula("incorrect-formula(C11_C12*D11_D12)", cra); + assertThrows(FormulaParseException.class, () -> sheet.setArrayFormula("incorrect-formula(C11_C12*D11_D12)", cra)); } } @@ -159,19 +155,11 @@ public abstract class BaseTestSheetUpdateArrayFormulas { Cell cell = sheet.createRow(0).createCell(0); assertFalse(cell.isPartOfArrayFormulaGroup()); - try { - cell.getArrayFormulaRange(); - fail("expected exception"); - } catch (IllegalStateException e) { - assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - } + IllegalStateException e = assertThrows(IllegalStateException.class, cell::getArrayFormulaRange); + assertEquals("Cell Sheet0!A1 is not part of an array formula.", e.getMessage()); - try { - sheet.removeArrayFormula(cell); - fail("expected exception"); - } catch (IllegalArgumentException e) { - 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()); } } @@ -201,13 +189,9 @@ public abstract class BaseTestSheetUpdateArrayFormulas { // cells C4:C6 are not included in array formula, // invocation of sheet.removeArrayFormula on any of them throws IllegalArgumentException for (Cell acell : cr) { - try { - sheet.removeArrayFormula(acell); - fail("expected exception"); - } catch (IllegalArgumentException e) { - String ref = new CellReference(acell).formatAsString(); - assertEquals("Cell " + ref + " is not part of an array formula.", e.getMessage()); - } + 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()); } } } @@ -299,15 +283,12 @@ public abstract class BaseTestSheetUpdateArrayFormulas { CellRange mrange = sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); for (Cell mcell : mrange) { - try { - assertEquals(CellType.FORMULA, mcell.getCellType()); - mcell.setCellType(CellType.NUMERIC); - fail("expected exception"); - } catch (IllegalStateException e) { - 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()); - } + 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()); @@ -342,15 +323,12 @@ public abstract class BaseTestSheetUpdateArrayFormulas { 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 - try { - assertEquals("A1:A3*B1:B3", mcell.getCellFormula()); - mcell.setCellFormula("A1+A2"); - fail("expected exception"); - } catch (IllegalStateException e) { - 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()); - } + 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()); @@ -386,14 +364,11 @@ public abstract class BaseTestSheetUpdateArrayFormulas { for (Cell mcell : mrange) { int columnIndex = mcell.getColumnIndex(); Row mrow = mcell.getRow(); - try { - mrow.removeCell(mcell); - fail("expected exception"); - } catch (IllegalStateException e) { - 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()); - } + 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)); @@ -432,13 +407,10 @@ public abstract class BaseTestSheetUpdateArrayFormulas { for (Cell mcell : mrange) { int columnIndex = mcell.getColumnIndex(); Row mrow = mcell.getRow(); - try { - sheet.removeRow(mrow); - fail("expected exception"); - } catch (IllegalStateException e) { - // 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()); - } + 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())); @@ -485,13 +457,9 @@ public abstract class BaseTestSheetUpdateArrayFormulas { "B1:D6", "B1:G3", "E1:G6", "B4:G6" // 2-row/2-column intersection )) { CellRangeAddress cra = CellRangeAddress.valueOf(ref); - try { - sheet.addMergedRegion(cra); - fail("expected exception with ref " + ref); - } catch (IllegalStateException e) { - String msg = "The range " + cra.formatAsString() + " intersects with a multi-cell array formula. You cannot merge cells of an array."; - assertEquals(msg, e.getMessage()); - } + 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()); @@ -503,13 +471,9 @@ public abstract class BaseTestSheetUpdateArrayFormulas { "C6:F6", //bottom "B2:B5", "H7:J9")) { CellRangeAddress cra = CellRangeAddress.valueOf(ref); - try { - sheet.addMergedRegion(cra); - expectedNumMergedRegions++; - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - } catch (IllegalStateException e) { - fail("did not expect exception with ref: " + ref + "\n" + e.getMessage()); - } + sheet.addMergedRegion(cra); + expectedNumMergedRegions++; + assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); } } @@ -522,7 +486,7 @@ public abstract class BaseTestSheetUpdateArrayFormulas { //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")); + 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); @@ -530,14 +494,9 @@ public abstract class BaseTestSheetUpdateArrayFormulas { //we cannot set individual formulas for cells included in an array formula sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - - try { - sheet.shiftRows(0, 0, 1); - fail("expected exception"); - } catch (IllegalStateException e) { - 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()); - } + 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 @@ -556,8 +515,8 @@ public abstract class BaseTestSheetUpdateArrayFormulas { } } - @Ignore("See bug 59728") - @Test(expected = IllegalStateException.class) + @Disabled("See bug 59728") + @Test public void shouldNotBeAbleToCreateArrayFormulaOnPreexistingMergedRegion() throws IOException { /* * m = merged region @@ -578,7 +537,7 @@ public abstract class BaseTestSheetUpdateArrayFormulas { 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 - sheet.setArrayFormula("SUM(A1:A3)", arrayFormula); + 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 index b36078d310..08835946ba 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java @@ -17,15 +17,14 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 java.io.IOException; import java.io.OutputStream; @@ -38,7 +37,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public abstract class BaseTestWorkbook { @@ -67,7 +66,7 @@ public abstract class BaseTestWorkbook { * should not be able to advance an iterator when the * underlying data has been reordered */ - @Test(expected=ConcurrentModificationException.class) + @Test public void sheetIterator_sheetsReordered() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { wb.createSheet("Sheet0"); @@ -79,7 +78,7 @@ public abstract class BaseTestWorkbook { wb.setSheetOrder("Sheet2", 1); // Iterator order should be fixed when iterator is created - assertEquals("Sheet1", it.next().getSheetName()); + assertThrows(ConcurrentModificationException.class, it::next); } } @@ -88,7 +87,7 @@ public abstract class BaseTestWorkbook { * should not be able to advance an iterator when the * underlying data has been reordered */ - @Test(expected=ConcurrentModificationException.class) + @Test public void sheetIterator_sheetRemoved() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { wb.createSheet("Sheet0"); @@ -99,7 +98,7 @@ public abstract class BaseTestWorkbook { wb.removeSheetAt(1); // Iterator order should be fixed when iterator is created - it.next(); + assertThrows(ConcurrentModificationException.class, it::next); } } @@ -107,14 +106,14 @@ public abstract class BaseTestWorkbook { * Expected UnsupportedOperationException: * should not be able to remove sheets from the sheet iterator */ - @Test(expected=UnsupportedOperationException.class) + @Test public void sheetIterator_remove() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { wb.createSheet("Sheet0"); Iterator it = wb.sheetIterator(); it.next(); //Sheet0 - it.remove(); + assertThrows(UnsupportedOperationException.class, it::remove); } } @@ -127,9 +126,9 @@ public abstract class BaseTestWorkbook { //getting a sheet by invalid index or non-existing name assertNull(wb.getSheet("Sheet1")); IllegalArgumentException ex = assertThrows( - "should have thrown exception due to invalid sheet index", IllegalArgumentException.class, - () -> wb.getSheetAt(0) + () -> 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")); @@ -145,16 +144,15 @@ public abstract class BaseTestWorkbook { //fetching sheets by name is case-insensitive Sheet originalSheet = wb.createSheet("Sheet3"); Sheet fetchedSheet = wb.getSheet("sheet3"); - if (fetchedSheet == null) { - fail("Identified bug 44892"); - } + assertNotNull(fetchedSheet, "Identified bug 44892"); + assertEquals("Sheet3", fetchedSheet.getSheetName()); assertEquals(3, wb.getNumberOfSheets()); assertSame(originalSheet, fetchedSheet); ex = assertThrows( - "should have thrown exception due to duplicate sheet name", IllegalArgumentException.class, - () -> wb.createSheet("sHeeT3") + () -> 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()); @@ -165,9 +163,9 @@ public abstract class BaseTestWorkbook { "My:Sheet"}; for (String sheetName : invalidNames) { assertThrows( - "should have thrown exception due to invalid sheet name: " + sheetName, IllegalArgumentException.class, - () -> wb.createSheet(sheetName) + () -> wb.createSheet(sheetName), + "should have thrown exception due to invalid sheet name: " + sheetName ); } //still have 3 sheets @@ -177,28 +175,12 @@ public abstract class BaseTestWorkbook { wb.setSheetName(2, "I changed!"); //try to assign an invalid name to the 2nd sheet - try { - wb.setSheetName(1, "[I'm invalid]"); - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> wb.setSheetName(1, "[I'm invalid]")); //try to assign an invalid name to the 2nd sheet - try { - wb.createSheet(null); - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> wb.createSheet(null)); - try { - wb.setSheetName(2, null); - - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } + assertThrows(IllegalArgumentException.class, () -> wb.setSheetName(2, null)); //check assertEquals(0, wb.getSheetIndex("sheet0")); @@ -244,14 +226,9 @@ public abstract class BaseTestWorkbook { String sheetName2 = "My very long sheet name which is longer than 31 chars " + "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; - try { - /*Sheet sh2 =*/ - wb1.createSheet(sheetName2); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - 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()); - } + + 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); @@ -777,11 +754,9 @@ public abstract class BaseTestWorkbook { for(int i = 0;i < wb.getNumberOfSheets();i++) { sheetNames.append(wb.getSheetAt(i).getSheetName()).append(","); } - assertEquals("Had: " + sheetNames, - sheets.length, wb.getNumberOfSheets()); + assertEquals(sheets.length, wb.getNumberOfSheets(), "Had: " + sheetNames); for(int i = 0;i < wb.getNumberOfSheets();i++) { - assertEquals("Had: " + sheetNames, - sheets[i], wb.getSheetAt(i).getSheetName()); + assertEquals(sheets[i], wb.getSheetAt(i).getSheetName(), "Had: " + sheetNames); } } @@ -823,8 +798,7 @@ public abstract class BaseTestWorkbook { final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename); wb.close(); final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename); - assertArrayEquals(filename + " sample file was modified as a result of closing the workbook", - before, after); + assertArrayEquals(before, after, filename + " sample file was modified as a result of closing the workbook"); } @Test diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java index f21842b4ec..5a5c8ec04f 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestXEvaluationSheet.java @@ -17,12 +17,12 @@ package org.apache.poi.ss.usermodel; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Map; -import static org.junit.Assert.assertEquals; +import org.apache.poi.ss.formula.EvaluationSheet; +import org.junit.jupiter.api.Test; public abstract class BaseTestXEvaluationSheet { /** diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java index 77f1ca3d3b..57887aee8e 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java @@ -16,19 +16,22 @@ 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 + 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.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.*; +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; @@ -41,9 +44,9 @@ 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.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests of {@link DataFormatter} @@ -54,7 +57,7 @@ import org.junit.Test; public class TestDataFormatter { private static final double _15_MINUTES = 0.041666667; - @BeforeClass + @BeforeAll @SuppressForbidden public static void setUpClass() { // some pre-checks to hunt for a problem in the Maven build @@ -74,8 +77,8 @@ public class TestDataFormatter { CellFormat cfmt = CellFormat.getInstance("_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-"); CellFormatResult result = cfmt.apply(cellValueO); - assertEquals("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", - " 1,234.56 ", result.text); + 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"); } /** @@ -109,7 +112,7 @@ public class TestDataFormatter { // Regular numeric style formats assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]##")); - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]00")); + assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]00")); } @@ -148,14 +151,14 @@ public class TestDataFormatter { }; for (String format : formats) { assertEquals( - "Wrong format for: " + format, "12.34", - dfUS.formatRawCellContents(12.343, -1, format) + dfUS.formatRawCellContents(12.343, -1, format), + "Wrong format for: " + format ); assertEquals( - "Wrong format for: " + format, "-12.34", - dfUS.formatRawCellContents(-12.343, -1, format) + dfUS.formatRawCellContents(-12.343, -1, format), + "Wrong format for: " + format ); } @@ -172,14 +175,14 @@ public class TestDataFormatter { String[] formats = { "#,##0.00;[Blue](#,##0.00)" }; for (String format : formats) { assertEquals( - "Wrong format for: " + format, "12.34", - dfUS.formatRawCellContents(12.343, -1, format) + dfUS.formatRawCellContents(12.343, -1, format), + "Wrong format for: " + format ); assertEquals( - "Wrong format for: " + format, "(12.34)", - dfUS.formatRawCellContents(-12.343, -1, format) + dfUS.formatRawCellContents(-12.343, -1, format), + "Wrong format for: " + format ); } @@ -187,14 +190,14 @@ public class TestDataFormatter { formats = new String[] { "$#,##0.00;[Red]($#,##0.00)" }; for (String format : formats) { assertEquals( - "Wrong format for: " + format, "$12.34", - dfUS.formatRawCellContents(12.343, -1, format) + dfUS.formatRawCellContents(12.343, -1, format), + "Wrong format for: " + format ); assertEquals( - "Wrong format for: " + format, "($12.34)", - dfUS.formatRawCellContents(-12.343, -1, format) + dfUS.formatRawCellContents(-12.343, -1, format), + "Wrong format for: " + format ); } } @@ -204,8 +207,8 @@ public class TestDataFormatter { DataFormatter dfUS = new DataFormatter(Locale.US); String format = "[>=10]#,##0;[<10]0.0"; - assertEquals("Wrong format for " + format, "17,876", dfUS.formatRawCellContents(17876.000, -1, format)); - assertEquals("Wrong format for " + format, "9.7", dfUS.formatRawCellContents(9.71, -1, format)); + 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); } /** @@ -646,7 +649,7 @@ public class TestDataFormatter { * TODO Fix these so that they work */ @Test - @Ignore + @Disabled public void testCustomFormats() { DataFormatter dfUS = new DataFormatter(Locale.US, true); String fmt; @@ -700,7 +703,7 @@ public class TestDataFormatter { 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)); @@ -710,15 +713,13 @@ public class TestDataFormatter { 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)); - - try { - assertEquals("1h 0m\"", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\" m\"\"m\"\"\"\"", false)); - fail("Catches exception because of invalid format, i.e. trailing quoting"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("Cannot format given Object as a Number")); - } + + 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 public void testIsADateFormat() { // first check some cases that should not be a date, also call multiple times to ensure the cache is used @@ -926,7 +927,7 @@ public class TestDataFormatter { String value = df.formatCellValue(cell, wb.getCreationHelper().createFormulaEvaluator()); assertEquals("-130", value); } - + /** * Bug #63292 */ @@ -965,7 +966,7 @@ public class TestDataFormatter { doFormatTestSequential(formatter1); doFormatTestConcurrent(formatter1, formatter2); } - + /** * Bug #64319 * @@ -976,24 +977,24 @@ public class TestDataFormatter { @Test public 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, + assertEquals("TRUE", formatter.formatRawCellContents(1.0, 170, "\"TRUE\";\"FALSE\";\"ZERO\"")); - assertEquals("ZERO", formatter.formatRawCellContents(0.0, 170, + assertEquals("ZERO", formatter.formatRawCellContents(0.0, 170, "\"TRUE\";\"FALSE\";\"ZERO\"")); - assertEquals("FALSE", formatter.formatRawCellContents(-1.0, 170, + assertEquals("FALSE", formatter.formatRawCellContents(-1.0, 170, "\"TRUE\";\"FALSE\";\"ZERO\"")); // Explicit Scientific format does need E+ - assertEquals("1E+05", formatter.formatRawCellContents(1e05, 170, + assertEquals("1E+05", formatter.formatRawCellContents(1e05, 170, "0E+00")); - assertEquals("1E+10", formatter.formatRawCellContents(1e10, 170, + assertEquals("1E+10", formatter.formatRawCellContents(1e10, 170, "0E+00")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, + 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")); @@ -1001,20 +1002,20 @@ public class TestDataFormatter { // 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, + assertEquals("1E5", formatter.formatRawCellContents(1e05, 170, "0E0")); - assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, + assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, "0E0")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, + assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, "0E0")); - assertEquals("1E5", formatter.formatRawCellContents(1e05, 170, + assertEquals("1E5", formatter.formatRawCellContents(1e05, 170, "0E-0")); - assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, + assertEquals("1E10", formatter.formatRawCellContents(1e10, 170, "0E-0")); - assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, + assertEquals("1E-10", formatter.formatRawCellContents(1e-10, 170, "0E-0")); - + } private void doFormatTestSequential(DataFormatter formatter) { @@ -1052,7 +1053,7 @@ public class TestDataFormatter { 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("Failed on iteration " + iteration, expected, actual); + 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 index dc5c3f5b24..550815d089 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java @@ -24,12 +24,12 @@ 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.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -45,21 +45,21 @@ 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.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestDateUtil { static TimeZone userTimeZone; - @BeforeClass + @BeforeAll public static void setCEST() { userTimeZone = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST")); } - @AfterClass + @AfterAll public static void resetTimeZone() { LocaleUtil.setUserTimeZone(userTimeZone); } @@ -194,12 +194,12 @@ public class TestDateUtil { for (int hour = 0; hour < 24; hour++) { double excelDate = DateUtil.getExcelDate(cal.getTime(), false); - assertEquals("getJavaDate: Checking hour = " + hour, cal.getTime().getTime(), - DateUtil.getJavaDate(excelDate, false).getTime()); + assertEquals(cal.getTime().getTime(), DateUtil.getJavaDate(excelDate, false).getTime(), + "getJavaDate: Checking hour = " + hour); LocalDateTime ldt = LocalDateTime.ofInstant(cal.toInstant(), cal.getTimeZone().toZoneId()); - assertEquals("getLocalDateTime: Checking hour = " + hour, ldt, - DateUtil.getLocalDateTime(excelDate, false)); + assertEquals(ldt, DateUtil.getLocalDateTime(excelDate, false), + "getLocalDateTime: Checking hour = " + hour); cal.add(Calendar.HOUR_OF_DAY, 1); } @@ -214,21 +214,17 @@ public class TestDateUtil { cal.add(Calendar.DATE,1); // now Jan. 2, 2004 Date dateIf1904 = cal.getTime(); // 1900 windowing - assertEquals("Checking 1900 Date Windowing", - dateIf1900.getTime(), - DateUtil.getJavaDate(excelDate,false).getTime()); + assertEquals(dateIf1900.getTime(), DateUtil.getJavaDate(excelDate,false).getTime(), + "Checking 1900 Date Windowing"); // 1904 windowing - assertEquals("Checking 1904 Date Windowing", - dateIf1904.getTime(), - DateUtil.getJavaDate(excelDate,true).getTime()); + assertEquals(dateIf1904.getTime(), DateUtil.getJavaDate(excelDate,true).getTime(), + "Checking 1904 Date Windowing"); // 1900 windowing (LocalDateTime) - assertEquals("Checking 1900 Date Windowing", - LocalDateTime.of(2000,1,1,0,0), - DateUtil.getLocalDateTime(excelDate,false)); + assertEquals(LocalDateTime.of(2000,1,1,0,0), DateUtil.getLocalDateTime(excelDate,false), + "Checking 1900 Date Windowing"); // 1904 windowing (LocalDateTime) - assertEquals("Checking 1904 Date Windowing", - LocalDateTime.of(2004,1,2,0,0), - DateUtil.getLocalDateTime(excelDate,true)); + assertEquals(LocalDateTime.of(2004,1,2,0,0), DateUtil.getLocalDateTime(excelDate,true), + "Checking 1904 Date Windowing"); } /** @@ -252,12 +248,9 @@ public class TestDateUtil { double difference = excelDate - Math.floor(excelDate); int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - hour, - differenceInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - javaDate.getTime(), - DateUtil.getJavaDate(excelDate, false).getTime()); + 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); @@ -265,12 +258,10 @@ public class TestDateUtil { double differenceLocalDate = excelLocalDate - Math.floor(excelLocalDate); int differenceLocalDateInHours = (int) (differenceLocalDate * 24 * 60 + 0.5) / 60; - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)", - hour, - differenceLocalDateInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)", - localDate, - DateUtil.getLocalDateTime(excelLocalDate, false)); + 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)"); } } @@ -295,15 +286,15 @@ public class TestDateUtil { cal.set(Calendar.HOUR_OF_DAY, hour); Date javaDate = DateUtil.getJavaDate(excelDate, false); double actDate = DateUtil.getExcelDate(javaDate, false); - assertEquals("Checking " + hour + " hours on Daylight Saving Time start date", - excelDate, actDate, oneMinute); + 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("Checking " + hour + " hours on Daylight Saving Time start date (LocalDateTime)", - excelDate, actLocalDate, oneMinute); + assertEquals(excelDate, actLocalDate, oneMinute, + "Checking " + hour + " hours on Daylight Saving Time start date (LocalDateTime)"); } } @@ -320,23 +311,19 @@ public class TestDateUtil { double excelDate = DateUtil.getExcelDate(javaDate, false); double difference = excelDate - Math.floor(excelDate); int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals("Checking " + hour + " hour on Daylight Saving Time end date", - hour, - differenceInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - javaDate.getTime(), - DateUtil.getJavaDate(excelDate, false).getTime()); + 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("Checking " + hour + " hour on Daylight Saving Time end date (LocalDateTime)", - hour, - differenceLocalDateInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date (LocalDateTime)", - localDate, - DateUtil.getLocalDateTime(excelLocalDate, false)); + 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)"); } } @@ -353,15 +340,13 @@ public class TestDateUtil { for (int hour = 0; hour < 24; hour++, excelDate += oneHour) { cal.set(Calendar.HOUR_OF_DAY, hour); Date javaDate = DateUtil.getJavaDate(excelDate, false); - assertEquals("Checking " + hour + " hours on Daylight Saving Time start date", - excelDate, - DateUtil.getExcelDate(javaDate, false), oneMinute); + 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("Checking " + hour + " hours on Daylight Saving Time start date", - excelDate, - DateUtil.getExcelDate(localDate, false), oneMinute); + assertEquals(excelDate, DateUtil.getExcelDate(localDate, false), oneMinute, + "Checking " + hour + " hours on Daylight Saving Time start date"); } } @@ -386,7 +371,7 @@ public class TestDateUtil { Date javaDate = DateUtil.getJavaDate(excelDate); // Should match despite time-zone - assertEquals("Checking timezone " + id, expected.getTime(), javaDate.getTime()); + assertEquals(expected.getTime(), javaDate.getTime(), "Checking timezone " + id); } // Check that the timezone aware getter works correctly @@ -398,8 +383,8 @@ public class TestDateUtil { // Same, no change assertEquals( - DateUtil.getJavaDate(excelDate, false).getTime(), - DateUtil.getJavaDate(excelDate, false, cet).getTime() + DateUtil.getJavaDate(excelDate, false).getTime(), + DateUtil.getJavaDate(excelDate, false, cet).getTime() ); // London vs Copenhagen, should differ by an hour @@ -464,10 +449,7 @@ public class TestDateUtil { "[yeLLow]yyyy-mm-dd" }; for (String format : formats) { - assertTrue( - format + " is a date format", - DateUtil.isADateFormat(formatId, format) - ); + assertTrue(DateUtil.isADateFormat(formatId, format), format + " is a date format"); } // Then time based ones too @@ -482,10 +464,7 @@ public class TestDateUtil { "[hh]", "[mm]", "[ss]", "[SS]", "[red][hh]" }; for (String format : formats) { - assertTrue( - format + " is a datetime format", - DateUtil.isADateFormat(formatId, format) - ); + assertTrue(DateUtil.isADateFormat(formatId, format), format + " is a datetime format"); } // Then invalid ones @@ -498,10 +477,7 @@ public class TestDateUtil { "", null }; for (String format : formats) { - assertFalse( - format + " is not a date or datetime format", - DateUtil.isADateFormat(formatId, format) - ); + assertFalse(DateUtil.isADateFormat(formatId, format), format + " is not a date or datetime format"); } // And these are ones we probably shouldn't allow, @@ -624,47 +600,26 @@ public class TestDateUtil { public void absoluteDay() { // 1 Jan 1900 is 1 day after 31 Dec 1899 Calendar cal = LocaleUtil.getLocaleCalendar(1900,JANUARY,1,0,0,0); - assertEquals("Checking absolute day (1 Jan 1900)", 1, DateUtil.absoluteDay(cal, false)); + assertEquals(1, DateUtil.absoluteDay(cal, false), "Checking absolute day (1 Jan 1900)"); LocalDateTime ldt = LocalDateTime.of(1900,1,1,0,0,0); - assertEquals("Checking absolute day (1 Jan 1900) (LocalDateTime)", 1, DateUtil.absoluteDay(ldt, false)); + 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("Checking absolute day (1 Jan 1901) (LocalDateTime)", 366, DateUtil.absoluteDay(ldt, false)); + assertEquals(366, DateUtil.absoluteDay(ldt, false), "Checking absolute day (1 Jan 1901) (LocalDateTime)"); } @Test public void absoluteDayYearTooLow() { Calendar cal = LocaleUtil.getLocaleCalendar(1899,JANUARY,1,0,0,0); - try { - DateUtil.absoluteDay(cal, false); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(cal, false)); - try { - cal.set(1903,JANUARY,1,0,0,0); - DateUtil.absoluteDay(cal, true); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } + cal.set(1903,JANUARY,1,0,0,0); + assertThrows(IllegalArgumentException.class, () -> DateUtil.absoluteDay(cal, true)); // same for LocalDateTime - try { - DateUtil.absoluteDay(LocalDateTime.of(1899,1,1,0,0,0), false); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } - - try { - DateUtil.absoluteDay(LocalDateTime.of(1903,1,1,0,0,0), true); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } + 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 diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java index 742fb2228f..47f47d3245 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; @@ -34,7 +34,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.poi.util.LocaleUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestExcelStyleDateFormatter { private static final String EXCEL_DATE_FORMAT = "MMMMM"; @@ -77,9 +77,9 @@ public class TestExcelStyleDateFormatter { int actIdx = localeIndex(locale); - assertNotNull(msg, result); - assertTrue(msg, result.length() > actIdx); - assertEquals(msg, expected.charAt(month), result.charAt(actIdx)); + assertNotNull(result, msg); + assertTrue(result.length() > actIdx, msg); + assertEquals(expected.charAt(month), result.charAt(actIdx), msg); month++; } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java b/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java index ec8359a46d..0ae728d52c 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java @@ -17,7 +17,8 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.BufferedReader; import java.io.File; @@ -27,8 +28,8 @@ 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.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests for the Fraction Formatting part of DataFormatter. @@ -43,15 +44,12 @@ public final class TestFractionFormat { assertEquals("26027/81", ret); } - @Test(expected = IllegalStateException.class) + @Test public void testInvalid() { - FractionFormat f = new FractionFormat("", "9999999999999999999999999999"); - double val = 321.321; - String ret = f.format(val); - assertEquals("26027/81", ret); + assertThrows(IllegalStateException.class, () -> new FractionFormat("", "9999999999999999999999999999")); } - @Ignore("Runs for some longer time") + @Disabled("Runs for some longer time") @Test public void microBenchmark() { FractionFormat f = new FractionFormat("", "##"); @@ -105,7 +103,7 @@ public final class TestFractionFormat { String truth = clean(truths[j]); String testKey = truths[0] + ":" + truths[1] + ":" + headers[j]; - assertEquals(testKey, truth, formatted); + assertEquals(truth, formatted, testKey); } truthLine = reader.readLine(); } diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java b/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java index 093410b746..e6209f3352 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java +++ b/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java @@ -17,10 +17,10 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Yegor Kozlov @@ -31,24 +31,18 @@ public final class TestIndexedColors { public void fromInt() { int[] illegalIndices = { -1, 65 }; for (int index : illegalIndices) { - try { - IndexedColors.fromInt(index); - fail("Expected IllegalArgumentException: " + index); - } - catch (final IllegalArgumentException e) { - // expected - } + 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 public void getIndex() { assertEquals(51, IndexedColors.GOLD.getIndex()); } - + @Test public void index() { assertEquals(51, IndexedColors.GOLD.index); diff --git a/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java b/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java deleted file mode 100644 index 569fadce71..0000000000 --- a/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.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.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Test suite for org.apache.poi.ss.util - * - * @author Josh Micich - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaReference.class, - //TestCellRangeAddress.class, //converted to junit4 - //TestCellReference.class, //converted to junit4 - TestDateFormatConverter.class, - TestExpandedDouble.class, - TestNumberComparer.class, - TestNumberToTextConverter.class, - TestSheetBuilder.class, - TestSheetUtil.class, - TestWorkbookUtil.class -}) -public class AllSSUtilTests { -} diff --git a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java b/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java index d06bea9b3e..ce3fbeef15 100644 --- a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java +++ b/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java @@ -5,9 +5,9 @@ The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,12 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +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; @@ -39,7 +40,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests Spreadsheet CellUtil @@ -52,30 +53,29 @@ public abstract class BaseTestCellUtil { protected BaseTestCellUtil(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } - + @Test public void setCellStyleProperty() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); + 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 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); - - wb.close(); + // 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(expected=RuntimeException.class) + + @Test public void setCellStylePropertyWithInvalidValue() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet s = wb.createSheet(); @@ -83,127 +83,120 @@ public abstract class BaseTestCellUtil { Cell c = r.createCell(0); // An invalid BorderStyle constant - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, 42); + assertThrows(RuntimeException.class, () -> CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, 42)); } } - + @Test() public void setCellStylePropertyBorderWithShortAndEnum() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); + 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()); - - wb.close(); + // 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 public void setCellStyleProperties() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); + 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("Only one additional style should have been created", styCnt1 + 1, styCnt2); + // 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("No additional styles should have been created", styCnt2, styCnt3); - - wb.close(); - + // 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 public void getRow() throws IOException { - 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("An existing row should not be recreated", row1, r1); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sh = wb.createSheet(); + Row row1 = sh.createRow(0); - // Get row that does not exist yet - assertNotNull(CellUtil.getRow(1, sh)); + // Get row that already exists + Row r1 = CellUtil.getRow(0, sh); + assertNotNull(r1); + assertSame(row1, r1, "An existing row should not be recreated"); - wb.close(); + // Get row that does not exist yet + assertNotNull(CellUtil.getRow(1, sh)); + } } @Test public void getCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); + 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("An existing cell should not be recreated", A1, a1); + // 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)); - - wb.close(); + // Get cell that does not exist yet + assertNotNull(CellUtil.getCell(row, 1)); + } } @Test public void createCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sh = wb.createSheet(); + Row row = sh.createRow(0); - CellStyle style = wb.createCellStyle(); - style.setWrapText(true); + 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); + // 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. + 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("cell style should be unchanged with createCell(..., null)", style, f1.getCellStyle()); - assertEquals("cell style should be unchanged with createCell(..., null)", style, F1.getCellStyle()); - - // test createCell(row, column, value) (no CellStyle) - f1 = CellUtil.createCell(row, 5, "Overwritten cell with default style"); - assertSame(F1, f1); - - wb.close(); + // 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); + } } /** @@ -221,7 +214,7 @@ public abstract class BaseTestCellUtil { // Assumptions assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. + // 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()); @@ -238,7 +231,7 @@ public abstract class BaseTestCellUtil { wb.close(); } - + @Test public void setAlignmentEnum() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); @@ -249,7 +242,7 @@ public abstract class BaseTestCellUtil { // Assumptions assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. + // 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()); @@ -266,94 +259,83 @@ public abstract class BaseTestCellUtil { wb.close(); } - + @Test public void setVerticalAlignmentEnum() 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); + 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()); + // 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 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()); - - wb.close(); + // 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 public void setFont() 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); - final int defaultFontIndex = 0; - Font font = wb.createFont(); - font.setItalic(true); - final int customFontIndex = font.getIndex(); + 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()); + // 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 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()); - - wb.close(); + // 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 public void setFontFromDifferentWorkbook() throws IOException { - 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); + 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); - // font belongs to different workbook - try { - CellUtil.setFont(A1, font2); - fail("setFont not allowed if font belongs to a different workbook"); - } catch (final IllegalArgumentException e) { - // one specific message is expected - if (!e.getMessage().startsWith("Font does not belong to this workbook")) { - throw e; - } - } finally { - wb1.close(); - wb2.close(); + // 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")); } } @@ -363,20 +345,19 @@ public abstract class BaseTestCellUtil { */ @Test public void setFillForegroundColorBeforeFillBackgroundColorEnum() throws IOException { - 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("fill pattern", FillPatternType.BRICKS, style.getFillPattern()); - assertEquals("fill foreground color", IndexedColors.BLUE, IndexedColors.fromInt(style.getFillForegroundColor())); - assertEquals("fill background color", IndexedColors.RED, IndexedColors.fromInt(style.getFillBackgroundColor())); + 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); - wb1.close(); + 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"); + } } /** diff --git a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java b/src/testcases/org/apache/poi/ss/util/TestAreaReference.java index d15dd5f7dd..3d7f99839b 100644 --- a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java +++ b/src/testcases/org/apache/poi/ss/util/TestAreaReference.java @@ -16,20 +16,19 @@ ==================================================================== */ 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.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; /** * Test for {@link AreaReference} handling of max rows. - * + * * @author David North */ public class TestAreaReference { @@ -63,7 +62,7 @@ public class TestAreaReference { 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()); diff --git a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellAddress.java index 96c783f6a7..dffeff5ea8 100644 --- a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java +++ b/src/testcases/org/apache/poi/ss/util/TestCellAddress.java @@ -17,14 +17,15 @@ package org.apache.poi.ss.util; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assume.assumeTrue; +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. */ @@ -57,7 +58,7 @@ public final class TestCellAddress { assertEquals(new CellReference(6, 4), new CellReference(6, 4)); assertNotEquals(new CellReference(4, 6), new CellReference(6, 4)); } - + @SuppressWarnings("EqualsWithItself") @Test public void testCompareTo() { @@ -65,27 +66,27 @@ public final class TestCellAddress { 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)); @@ -98,7 +99,7 @@ public final class TestCellAddress { final CellAddress addr = new CellAddress(6, 4); assertEquals(6, addr.getRow()); } - + @Test public void testGetColumn() { final CellAddress addr = new CellAddress(6, 4); diff --git a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java index 3bc1e59980..bdf715d4cb 100644 --- a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java +++ b/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java @@ -17,12 +17,13 @@ limitations under the License. package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -31,7 +32,7 @@ import java.util.NoSuchElementException; import org.apache.poi.hssf.record.TestcaseRecordInputStream; import org.apache.poi.util.LittleEndianOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestCellRangeAddress { static final byte[] data = new byte[] { @@ -53,13 +54,9 @@ public final class TestCellRangeAddress { @Test public void testLoadInvalid() { - try { - new CellRangeAddress( - TestcaseRecordInputStream.create(0x000, new byte[] { (byte)0x02 })); - fail(); - } catch (RuntimeException e) { - assertTrue("Had: " + e, e.getMessage().contains("Ran out of data")); - } + RuntimeException e = assertThrows(RuntimeException.class, () -> + new CellRangeAddress(TestcaseRecordInputStream.create(0x000, new byte[]{(byte) 0x02}))); + assertTrue(e.getMessage().contains("Ran out of data")); } @Test @@ -74,7 +71,7 @@ public final class TestCellRangeAddress { recordBytes = baos.toByteArray(); assertEquals(recordBytes.length, data.length); for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, 0, recordBytes[i]); + assertEquals(0, recordBytes[i], "At offset " + i); } // Now set the flags @@ -90,26 +87,16 @@ public final class TestCellRangeAddress { assertEquals(recordBytes.length, data.length); for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, data[i], recordBytes[i]); + assertEquals(data[i], recordBytes[i], "At offset " + i); } } } - + @Test - public void testCreateIllegal() throws IOException { + public void testCreateIllegal() { // for some combinations we expected exceptions - try { - new CellRangeAddress(1, 0, 0, 0); - fail("Expect to catch an exception"); - } catch (IllegalArgumentException e) { - // expected here - } - try { - new CellRangeAddress(0, 0, 1, 0); - fail("Expect to catch an exception"); - } catch (IllegalArgumentException e) { - // expected here - } + assertThrows(IllegalArgumentException.class, () -> new CellRangeAddress(1, 0, 0, 0)); + assertThrows(IllegalArgumentException.class, () -> new CellRangeAddress(0, 0, 1, 0)); } @Test @@ -120,14 +107,14 @@ public final class TestCellRangeAddress { } @Test - public void testGetEncodedSize() throws IOException { + public void testGetEncodedSize() { assertEquals(2*CellRangeAddress.ENCODED_SIZE, CellRangeAddress.getEncodedSize(2)); } @Test - public void testFormatAsString() throws IOException { + public void testFormatAsString() { CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - + assertEquals("D2:E3", ref.formatAsString()); assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString()); @@ -142,11 +129,11 @@ public final class TestCellRangeAddress { 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)); @@ -178,117 +165,107 @@ public final class TestCellRangeAddress { ref = new CellRangeAddress(-1, -1, -1, -1); assertEquals(":", ref.formatAsString()); } - + @Test public 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 public 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 public 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 public 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 public 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 public 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 public 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("A1", new CellAddress(0, 0), iter.next()); - assertEquals("B1", new CellAddress(0, 1), iter.next()); - assertEquals("A2", new CellAddress(1, 0), iter.next()); - assertEquals("B2", new CellAddress(1, 1), iter.next()); + 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()); - try { - iter.next(); - fail("Expected NoSuchElementException"); - } catch (final NoSuchElementException e) { - //expected - } - try { - iter.remove(); - fail("Expected UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - //expected - } - + assertThrows(NoSuchElementException.class, iter::next); + assertThrows(UnsupportedOperationException.class, iter::remove); + // for each interface int count = 0; for (final CellAddress addr : A1_B2) { @@ -297,7 +274,7 @@ public final class TestCellRangeAddress { } assertEquals(4, count); } - + private static void assertIntersects(CellRangeAddress regionA, CellRangeAddress regionB) { if (!(regionA.intersects(regionB) && regionB.intersects(regionA))) { final String A = regionA.formatAsString(); diff --git a/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java b/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java index 377f78d82a..0de86405da 100644 --- a/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java +++ b/src/testcases/org/apache/poi/ss/util/TestCellRangeUtil.java @@ -17,13 +17,14 @@ package org.apache.poi.ss.util; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertArrayEquals; +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 java.util.HashSet; + +import org.junit.jupiter.api.Test; /** * Tests CellRangeUtil. @@ -31,7 +32,7 @@ import java.util.HashSet; * @see org.apache.poi.ss.util.CellRangeUtil */ public 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); @@ -39,7 +40,7 @@ public final class TestCellRangeUtil { 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 public void testMergeCellRanges() { // Note that the order of the output array elements does not matter @@ -56,7 +57,7 @@ public final class TestCellRangeUtil { // Partially mergeable: multiple possible merges // A B // 1 x x A1,A2,B1 --> A1:B1,A2 or A1:A2,B1 - // 2 x + // 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)); diff --git a/src/testcases/org/apache/poi/ss/util/TestCellReference.java b/src/testcases/org/apache/poi/ss/util/TestCellReference.java index 095eb701d2..b2222986d0 100644 --- a/src/testcases/org/apache/poi/ss/util/TestCellReference.java +++ b/src/testcases/org/apache/poi/ss/util/TestCellReference.java @@ -17,24 +17,24 @@ 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.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import org.junit.jupiter.api.Test; /** * Tests that the common CellReference works as we need it to. @@ -288,7 +288,7 @@ public final class TestCellReference { confirmCrInRange(false, "XFD", "1048577", v2007); confirmCrInRange(false, "XFE", "1048576", v2007); - assertFalse("Identified bug 47312a", CellReference.cellReferenceIsWithinRange("B", "0", v97)); + assertFalse(CellReference.cellReferenceIsWithinRange("B", "0", v97), "Identified bug 47312a"); confirmCrInRange(false, "A", "0", v97); confirmCrInRange(false, "A", "0", v2007); @@ -296,35 +296,17 @@ public final class TestCellReference { @Test public void testInvalidReference() { - try { - new CellReference("Sheet1!#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) { - // expected here - } - - try { - new CellReference("'MySheetName'!#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) { - // expected here - } - - try { - new CellReference("#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) { - // expected here + 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) { - if (expResult == CellReference.cellReferenceIsWithinRange(colStr, rowStr, sv)) { - return; - } - fail("expected (c='" + colStr + "', r='" + rowStr + "' to be " - + (expResult ? "within" : "out of") + " bounds for version " + sv.name()); + 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 @@ -338,12 +320,9 @@ public final class TestCellReference { assertEquals(0, CellReference.convertColStringToIndex("$A")); assertEquals(1, CellReference.convertColStringToIndex("$B")); - try { - CellReference.convertColStringToIndex("A$"); - fail("Should throw exception here"); - } catch (IllegalArgumentException expected) { - assertTrue(expected.getMessage().contains("A$")); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> CellReference.convertColStringToIndex("A$")); + assertTrue(e.getMessage().contains("A$")); } @Test @@ -368,10 +347,10 @@ public final class TestCellReference { assertEquals("HOME", ref.getSheetName()); assertEquals(168, ref.getRow()); assertEquals(-1, ref.getCol()); - assertTrue("row absolute", ref.isRowAbsolute()); + assertTrue(ref.isRowAbsolute(), "row absolute"); //assertFalse("column absolute/relative is undefined", ref.isColAbsolute()); } - + @Test public void getSheetName() { assertNull(new CellReference("A5").getSheetName()); @@ -381,39 +360,38 @@ public final class TestCellReference { assertEquals("Sheet1", new CellReference("Sheet1!A5").getSheetName()); assertEquals("Sheet 1", new CellReference("'Sheet 1'!A5").getSheetName()); } - + @Test public void testToString() { CellReference ref = new CellReference("'Sheet 1'!A5"); assertEquals("org.apache.poi.ss.util.CellReference ['Sheet 1'!A5]", ref.toString()); } - + @Test public void testEqualsAndHashCode() { CellReference ref1 = new CellReference("'Sheet 1'!A5"); CellReference ref2 = new CellReference("Sheet 1", 4, 0, false, false); - assertEquals("equals", ref1, ref2); - assertEquals("hash code", ref1.hashCode(), ref2.hashCode()); + assertEquals(ref1, ref2); + assertEquals(ref1.hashCode(), ref2.hashCode()); //noinspection ObjectEqualsNull - assertNotEquals("null", null, ref1); - assertNotEquals("3D vs 2D", ref1, new CellReference("A5")); - assertNotEquals("type", ref1, 0L); + assertNotEquals(null, ref1); + assertNotEquals(ref1, new CellReference("A5")); } @Test public void isRowWithinRange() { SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertFalse("1 before first row", CellReference.isRowWithinRange("0", ss)); - assertTrue("first row", CellReference.isRowWithinRange("1", ss)); - assertTrue("last row", CellReference.isRowWithinRange("1048576", ss)); - assertFalse("1 beyond last row", CellReference.isRowWithinRange("1048577", ss)); + 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("1 before first row", CellReference.isRowWithinRange(-1, ss)); - assertTrue("first row", CellReference.isRowWithinRange(0, ss)); - assertTrue("last row", CellReference.isRowWithinRange(1048575, ss)); - assertFalse("1 beyond last row", CellReference.isRowWithinRange(1048576, ss)); + 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 @@ -421,63 +399,59 @@ public final class TestCellReference { String rowNum = "4000000000"; assertFalse(CellReference.isRowWithinRange(rowNum, SpreadsheetVersion.EXCEL2007)); } - - @Test(expected=NumberFormatException.class) + + @Test public void isRowWithinRangeNonInteger_Alpha() { String rowNum = "NotANumber"; - CellReference.isRowWithinRange(rowNum, SpreadsheetVersion.EXCEL2007); + assertThrows(NumberFormatException.class, () -> CellReference.isRowWithinRange(rowNum, SpreadsheetVersion.EXCEL2007)); } @Test public void isColWithinRange() { SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertTrue("(empty)", CellReference.isColumnWithinRange("", ss)); - assertTrue("first column (A)", CellReference.isColumnWithinRange("A", ss)); - assertTrue("last column (XFD)", CellReference.isColumnWithinRange("XFD", ss)); - assertFalse("1 beyond last column (XFE)", CellReference.isColumnWithinRange("XFE", ss)); - } - - @Test(expected=IllegalArgumentException.class) - public void unquotedSheetName() { - new CellReference("'Sheet 1!A5"); + 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(expected=IllegalArgumentException.class) - public void mismatchedQuotesSheetName() { - new CellReference("Sheet 1!A5"); + @Test + public void unquotedSheetName() { + assertThrows(IllegalArgumentException.class, () -> new CellReference("'Sheet 1!A5")); } - + + @Test + public void mismatchedQuotesSheetName() { + assertThrows(IllegalArgumentException.class, () -> new CellReference("Sheet 1!A5")); + } + @Test public void escapedSheetName() { String escapedName = "'Don''t Touch'!A5"; String unescapedName = "'Don't Touch'!A5"; new CellReference(escapedName); - try { - new CellReference(unescapedName); - fail("Sheet names containing apostrophe's must be escaped via a repeated apostrophe"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Bad sheet name quote escaping: ")); - } + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new CellReference(unescapedName)); + assertTrue(e.getMessage().startsWith("Bad sheet name quote escaping: ")); } - - @Test(expected=IllegalArgumentException.class) + + @Test public void negativeRow() { - new CellReference("sheet", -2, 0, false, false); + assertThrows(IllegalArgumentException.class, () -> new CellReference("sheet", -2, 0, false, false)); } - @Test(expected=IllegalArgumentException.class) + @Test public void negativeColumn() { - new CellReference("sheet", 0, -2, false, false); - } - - @Test(expected=IllegalArgumentException.class) - public void classifyEmptyStringCellReference() { - CellReference.classifyCellReference("", SpreadsheetVersion.EXCEL2007); + assertThrows(IllegalArgumentException.class, () -> new CellReference("sheet", 0, -2, false, false)); } - @Test(expected=IllegalArgumentException.class) + @Test + public void classifyEmptyStringCellReference() { + assertThrows(IllegalArgumentException.class, () -> CellReference.classifyCellReference("", SpreadsheetVersion.EXCEL2007)); + } + + @Test public void classifyInvalidFirstCharCellReference() { - CellReference.classifyCellReference("!A5", SpreadsheetVersion.EXCEL2007); + assertThrows(IllegalArgumentException.class, () -> CellReference.classifyCellReference("!A5", SpreadsheetVersion.EXCEL2007)); } @Test diff --git a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java index 4a0115605a..5a6bb29ad0 100644 --- a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java +++ b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java @@ -19,10 +19,10 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.File; import java.io.FileOutputStream; @@ -46,7 +46,7 @@ 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.TempFile; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestDateFormatConverter { private void outputLocaleDataFormats( Date date, boolean dates, boolean times, int style, String styleName ) throws Exception { @@ -181,20 +181,20 @@ public final class TestDateFormatConverter { final String partTag = langTag.substring(0, idx); Locale loc = Locale.forLanguageTag(partTag); - assertNotNull("Invalid language tag: "+partTag, loc); + assertNotNull(loc, "Invalid language tag: "+partTag); if (excludeList.contains(partTag)) { continue; } String prefix = DateFormatConverter.getPrefixForLocale(loc); - assertNotNull("Prefix not found - language tag: "+partTag, prefix); - assertNotEquals("Prefix not found - language tag: "+partTag,"", prefix); + assertNotNull(prefix, "Prefix not found - language tag: "+partTag); + assertNotEquals("", prefix, "Prefix not found - language tag: "+partTag); Matcher m = p.matcher(prefix); - assertTrue("Invalid prefix: "+prefix, m.matches()); + assertTrue(m.matches(), "Invalid prefix: "+prefix); LocaleID partLid = LocaleID.lookupByLanguageTag(partTag); - assertNotNull("LocaleID not found for part: "+partTag, partLid); + 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 index d20d234ef7..7b86ff1102 100644 --- a/src/testcases/org/apache/poi/ss/util/TestDateParser.java +++ b/src/testcases/org/apache/poi/ss/util/TestDateParser.java @@ -17,63 +17,50 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; public class TestDateParser { - @Test - public void testFailWhenNoDate() { - try { - DateParser.parseDate("potato"); - fail("Shouldn't parse potato!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenLooksLikeDateButItIsnt() { - try { - DateParser.parseDate("potato/cucumber/banana"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenIsInvalidDate() { - try { - DateParser.parseDate("13/13/13"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } + @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" + }) + public void testFailWhenInvalidDate(String invalidDate) { + EvaluationException e = assertThrows(EvaluationException.class, + () -> DateParser.parseDate(invalidDate), "Shouldn't parse " + invalidDate); + assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); } @Test public void testShouldParseValidDate() throws EvaluationException { Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); Calendar actDate = DateParser.parseDate("1984/10/20"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); + assertEquals(expDate, actDate, + "Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + + expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms"); } @Test public void testShouldIgnoreTimestamp() throws EvaluationException { Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); Calendar actDate = DateParser.parseDate("1984/10/20 12:34:56"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); + 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 index c02f58dd2f..7b285a60b4 100644 --- a/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java +++ b/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java @@ -17,13 +17,13 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link ExpandedDouble} @@ -34,7 +34,7 @@ public final class TestExpandedDouble { @Test public void testNegative() { ExpandedDouble hd = new ExpandedDouble(0xC010000000000000L); - assertNotEquals("identified bug - sign bit not masked out of exponent", -2046, hd.getBinaryExponent()); + 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()); @@ -44,7 +44,7 @@ public final class TestExpandedDouble { @Test public void testSubnormal() { ExpandedDouble hd = new ExpandedDouble(0x0000000000000001L); - assertNotEquals("identified bug - subnormal numbers not decoded properly", -1023, hd.getBinaryExponent()); + assertNotEquals(-1023, hd.getBinaryExponent(), "identified bug - subnormal numbers not decoded properly"); assertEquals(-1086, hd.getBinaryExponent()); BigInteger frac = hd.getSignificand(); assertEquals(64, frac.bitLength()); @@ -91,7 +91,7 @@ public final class TestExpandedDouble { checkNormaliseBaseTenResult(ed1, nd2); ExpandedDouble ed3 = nd2.normaliseBaseTwo(); - assertEquals("bin exp mismatch", ed3.getBinaryExponent(), ed1.getBinaryExponent()); + assertEquals(ed3.getBinaryExponent(), ed1.getBinaryExponent(), "bin exp mismatch"); BigInteger diff = ed3.getSignificand().subtract(ed1.getSignificand()).abs(); if (diff.signum() == 0) { @@ -127,6 +127,6 @@ public final class TestExpandedDouble { } BigInteger diff = subDigsB.subtract(subDigsO).abs(); // 100/32768 ~= 0.003 - assertTrue("minor mistake", diff.intValue() <= 100); + assertTrue(diff.intValue() <= 100, "minor mistake"); } } diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java b/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java index 66e357b753..abd9a01177 100644 --- a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java +++ b/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java @@ -17,13 +17,14 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; + /** * Tests for {@link NumberComparer} */ @@ -42,7 +43,7 @@ public final class TestNumberComparer { success &= confirm(i, ce.getNegB(), ce.getNegA(), +ce.getExpectedResult()); } - assertTrue("One or more cases failed. See stderr", success); + assertTrue(success, "One or more cases failed. See stderr"); } @Test @@ -68,7 +69,6 @@ public final class TestNumberComparer { public void testSpecificExampleA() { double a = 0.06-0.01; double b = 0.05; - //noinspection ConstantConditions assertNotEquals(a, b, 0.0); assertEquals(0, NumberComparer.compare(a, b)); } @@ -80,7 +80,6 @@ public final class TestNumberComparer { public void testSpecificExampleB() { double a = 1+1.0028-0.9973; double b = 1.0055; - //noinspection ConstantConditions assertNotEquals(a, b, 0.0); assertEquals(0, NumberComparer.compare(a, b)); } diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java b/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java index a471923b2d..feb8fa8b0f 100644 --- a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java +++ b/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java @@ -17,14 +17,14 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +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.Test; +import org.junit.jupiter.api.Test; /** * Tests for {@link NumberToTextConverter} diff --git a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java b/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java index 927f764280..b53e92dd9c 100644 --- a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java +++ b/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java @@ -17,8 +17,8 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; import java.io.IOException; @@ -31,7 +31,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests Spreadsheet PropertyTemplate @@ -799,12 +799,12 @@ public final class TestPropertyTemplate { } } } - + @Test public 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++) { @@ -855,10 +855,10 @@ public final class TestPropertyTemplate { 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(); @@ -872,10 +872,10 @@ public final class TestPropertyTemplate { 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(); @@ -905,10 +905,10 @@ public final class TestPropertyTemplate { } } } - + wb.close(); } - + @Test public void clonePropertyTemplate() throws IOException { CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); @@ -922,14 +922,14 @@ public final class TestPropertyTemplate { 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(); @@ -943,7 +943,7 @@ public final class TestPropertyTemplate { 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 index 6e3842b7a9..67f1e1310f 100644 --- a/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java +++ b/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java @@ -17,7 +17,7 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.BorderStyle; @@ -27,9 +27,9 @@ 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.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -44,18 +44,18 @@ public final class TestRegionUtil { private static final int DEFAULT_COLOR = 0; private Workbook wb; private Sheet sheet; - - @Before + + @BeforeEach public void setUp() { wb = new HSSFWorkbook(); sheet = wb.createSheet(); } - - @After + + @AfterEach public 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); @@ -63,7 +63,7 @@ public final class TestRegionUtil { if (cell == null) cell = row.createCell(columnIndex); return cell.getCellStyle(); } - + @Test public void setBorderTop() { assertEquals(NONE, getCellStyle(0, 0).getBorderTop()); @@ -104,7 +104,7 @@ public final class TestRegionUtil { assertEquals(THIN, getCellStyle(1, 0).getBorderLeft()); assertEquals(THIN, getCellStyle(2, 0).getBorderLeft()); } - + @Test public void setTopBorderColor() { assertEquals(DEFAULT_COLOR, getCellStyle(0, 0).getTopBorderColor()); @@ -145,7 +145,7 @@ public final class TestRegionUtil { assertEquals(RED, getCellStyle(1, 0).getLeftBorderColor()); assertEquals(RED, getCellStyle(2, 0).getLeftBorderColor()); } - + @Test public void bordersCanBeAddedToNonExistantCells() { RegionUtil.setBorderTop(THIN, A1C3, sheet); diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java b/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java index cae0407ab7..0951e72afa 100644 --- a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java +++ b/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +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; @@ -30,7 +30,7 @@ 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.Test; +import org.junit.jupiter.api.Test; /** * Tests SheetBuilder. diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java b/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java index 44b75f5be5..ebf84dc424 100644 --- a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java +++ b/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java @@ -5,9 +5,9 @@ The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +22,14 @@ 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.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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; /** * Tests SheetUtil. @@ -38,122 +39,128 @@ import static org.junit.Assert.assertTrue; public final class TestSheetUtil { @Test public void testCellWithMerges() throws Exception { - 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); + try (Workbook wb = new HSSFWorkbook()) { + Sheet s = wb.createSheet(); - 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 - assertEquals(10.0, SheetUtil.getCellWithMerges(s, 1, 0).getNumericCellValue(), 0.01); - assertEquals(11.0, SheetUtil.getCellWithMerges(s, 1, 1).getNumericCellValue(), 0.01); - - // With a cell that's the primary one of a merged region, we get that cell - assertEquals(20.0, SheetUtil.getCellWithMerges(s, 2, 0).getNumericCellValue(), 0.01); - assertEquals(21., SheetUtil.getCellWithMerges(s, 2, 1).getNumericCellValue(), 0.01); - - // With a cell elsewhere in the merged region, get top-left - assertEquals(20.0, SheetUtil.getCellWithMerges(s, 3, 0).getNumericCellValue(), 0.01); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 2).getNumericCellValue(), 0.01); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 3).getNumericCellValue(), 0.01); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 4).getNumericCellValue(), 0.01); - - wb.close(); + // 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 public void testCanComputeWidthHSSF() throws IOException { - Workbook wb = new HSSFWorkbook(); - - // cannot check on result because on some machines we get back false here! - SheetUtil.canComputeColumnWidth(wb.getFontAt(0)); - - wb.close(); + try (Workbook wb = new HSSFWorkbook()) { + // cannot check on result because on some machines we get back false here! + SheetUtil.canComputeColumnWidth(wb.getFontAt(0)); + } } @Test public void testGetCellWidthEmpty() throws IOException { - 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); - - wb.close(); + 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 public void testGetCellWidthString() throws IOException { - 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); - - wb.close(); + 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 public void testGetCellWidthNumber() throws IOException { - 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); - - wb.close(); + 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 public void testGetCellWidthBoolean() throws IOException { - 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); - - wb.close(); + 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 public void testGetColumnWidthString() throws IOException { - 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("Having some width for rows with actual cells", - SheetUtil.getColumnWidth(sheet, 0, true) > 0); - assertEquals("Not having any widht for rows with all empty cells", - -1.0, SheetUtil.getColumnWidth(sheet, 0, true, 1, 2), 0.01); - - wb.close(); + 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 index 30c080e40b..aa9b37ecac 100644 --- a/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java +++ b/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java @@ -17,9 +17,9 @@ package org.apache.poi.ss.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests WorkbookUtil. diff --git a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java b/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java index c553d0cc60..1a84d13e0f 100644 --- a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java +++ b/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java @@ -16,7 +16,7 @@ ==================================================================== */ package org.apache.poi.ss.util.cellwalk; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Date; @@ -25,7 +25,7 @@ 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.Test; +import org.junit.jupiter.api.Test; public class TestCellWalk { diff --git a/src/testcases/org/apache/poi/util/AllPOIUtilTests.java b/src/testcases/org/apache/poi/util/AllPOIUtilTests.java deleted file mode 100644 index 58155e6dca..0000000000 --- a/src/testcases/org/apache/poi/util/AllPOIUtilTests.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.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for all sub-packages of org.apache.poi.util
- */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestArrayUtil.class - , TestBitField.class - , TestByteField.class - , TestHexDump.class - , TestIntegerField.class - , TestIntList.class - , TestLittleEndian.class - , TestLongField.class - , TestPOILogFactory.class - , TestPOILogger.class - , TestShortField.class - , TestStringUtil.class - , TestTempFile.class -}) -public final class AllPOIUtilTests { -} diff --git a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java b/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java index c69baa7900..138f2baccd 100644 --- a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java +++ b/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java @@ -17,12 +17,12 @@ 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; -import static org.junit.Assert.assertNull; - /** * A simple utility class that can verify that objects have been successfully garbage collected. * @@ -100,7 +100,6 @@ public class MemoryLeakVerifier { Thread.sleep(GC_SLEEP_TIME); } - assertNull("Object should not exist after " + MAX_GC_ITERATIONS + " collections, but still had: " + ref.get(), - ref.get()); + 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/TestArrayUtil.java b/src/testcases/org/apache/poi/util/TestArrayUtil.java index 2718f7094d..001d5c0595 100644 --- a/src/testcases/org/apache/poi/util/TestArrayUtil.java +++ b/src/testcases/org/apache/poi/util/TestArrayUtil.java @@ -18,12 +18,12 @@ package org.apache.poi.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit test for ArrayUtil @@ -83,19 +83,11 @@ public class TestArrayUtil { } // Check can't shift more than we have - try { - ArrayUtil.arrayMoveWithin(getIntsList(), 7, 3, 5); - fail(); - } catch(IllegalArgumentException e) { - // Good, we don't have 5 from 7 onwards - } + 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 - try { - ArrayUtil.arrayMoveWithin(getIntsList(), 2, 7, 5); - fail(); - } catch(IllegalArgumentException e) { - // Good, we can't fit 5 in starting at 7 - } + 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 index c8c57ecaa2..d075c98fb0 100644 --- a/src/testcases/org/apache/poi/util/TestBitField.java +++ b/src/testcases/org/apache/poi/util/TestBitField.java @@ -17,11 +17,11 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test BitField functionality diff --git a/src/testcases/org/apache/poi/util/TestByteField.java b/src/testcases/org/apache/poi/util/TestByteField.java index 3c6bea78bf..53e9b95738 100644 --- a/src/testcases/org/apache/poi/util/TestByteField.java +++ b/src/testcases/org/apache/poi/util/TestByteField.java @@ -18,13 +18,13 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Unit test for ByteField class @@ -86,11 +86,11 @@ public final class TestByteField { for (int j = 0; j < _test_array.length; j++) { field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); field = new ByteField(0); field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3 ", _test_array[ j ], array[ 0 ]); + assertEquals(_test_array[ j ], field.get(), "testing _2 "); + assertEquals(_test_array[ j ], array[ 0 ], "testing _3 "); } } @@ -109,7 +109,7 @@ public final class TestByteField { for (int j = 0; j < _test_array.length; j++) { array[ 0 ] = _test_array[ j ]; field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing " + j); } } @@ -120,7 +120,7 @@ public final class TestByteField { for (int j = 0; j < _test_array.length; j++) { field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "Testing " + j); } } @@ -132,7 +132,7 @@ public final class TestByteField { for (byte b : _test_array) { field.set(b); field.writeToBytes(array); - assertEquals("testing ", b, array[ 0 ]); + 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 index cf575c770b..d6a7d5d0e4 100644 --- a/src/testcases/org/apache/poi/util/TestHexDump.java +++ b/src/testcases/org/apache/poi/util/TestHexDump.java @@ -17,10 +17,10 @@ package org.apache.poi.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -28,21 +28,21 @@ import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TestHexDump { private static PrintStream SYSTEM_OUT; - @BeforeClass + @BeforeAll public static void setUp() throws UnsupportedEncodingException { SYSTEM_OUT = System.out; System.setOut(new PrintStream(new OutputStream() {public void write(int b) {}}, false, "UTF-8")); } - @AfterClass + @AfterAll public static void tearDown() { System.setOut(SYSTEM_OUT); } @@ -55,8 +55,8 @@ public class TestHexDump { byte[] bytesAct = streamAct.toByteArray(); byte[] bytesExp = toHexDump(0, 0); - assertEquals("array size mismatch", bytesExp.length, bytesAct.length); - assertArrayEquals("array mismatch", bytesExp, bytesAct); + assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); + assertArrayEquals(bytesExp, bytesAct, "array mismatch"); // verify proper behavior with non-zero offset streamAct.reset(); @@ -64,8 +64,8 @@ public class TestHexDump { bytesAct = streamAct.toByteArray(); bytesExp = toHexDump(0x10000000L,0); - assertEquals("array size mismatch", bytesExp.length, bytesAct.length); - assertArrayEquals("array mismatch", bytesExp, bytesAct); + assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); + assertArrayEquals(bytesExp, bytesAct, "array mismatch"); // verify proper behavior with negative offset streamAct.reset(); @@ -73,8 +73,8 @@ public class TestHexDump { bytesAct = streamAct.toByteArray(); bytesExp = toHexDump(0xFF000000L,0); - assertEquals("array size mismatch", bytesExp.length, bytesAct.length); - assertArrayEquals("array mismatch", bytesExp, bytesAct); + assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); + assertArrayEquals(bytesExp, bytesAct, "array mismatch"); // verify proper behavior with non-zero index streamAct.reset(); @@ -82,36 +82,20 @@ public class TestHexDump { bytesAct = streamAct.toByteArray(); bytesExp = toHexDump(0xFF000000L,0x81); - assertEquals("array size mismatch", bytesExp.length, bytesAct.length); - assertArrayEquals("array mismatch", bytesExp, bytesAct); + assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); + assertArrayEquals(bytesExp, bytesAct, "array mismatch"); // verify proper behavior with negative index - try { - streamAct.reset(); - HexDump.dump(testArray, 0x10000000L, streamAct, -1); - fail("should have caught ArrayIndexOutOfBoundsException on negative index"); - } catch (ArrayIndexOutOfBoundsException ignored_exception) { - // as expected - } + streamAct.reset(); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, -1)); // verify proper behavior with index that is too large - try { - streamAct.reset(); - HexDump.dump(testArray, 0x10000000L, streamAct, testArray.length); - fail("should have caught ArrayIndexOutOfBoundsException on large index"); - } catch (ArrayIndexOutOfBoundsException ignored_exception) { - // as expected - } + streamAct.reset(); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, testArray.length)); // verify proper behavior with null stream - try { - HexDump.dump(testArray, 0x10000000L, null, 0); - fail("should have caught IllegalArgumentException on negative index"); - } catch (IllegalArgumentException ignored_exception) { - - // as expected - } + assertThrows(IllegalArgumentException.class, () -> HexDump.dump(testArray, 0x10000000L, null, 0)); // verify proper behaviour with empty byte array streamAct.reset(); @@ -178,28 +162,18 @@ public class TestHexDump { byte[] testArray = testArray(); String dump = HexDump.dump(testArray, 0, 0); //System.out.println("Hex: \n" + dump); - assertTrue("Had: \n" + dump, - dump.contains("0123456789:;<=>?")); + assertTrue(dump.contains("0123456789:;<=>?"), "Had: \n" + dump); dump = HexDump.dump(testArray, 2, 1); //System.out.println("Hex: \n" + dump); - assertTrue("Had: \n" + dump, - dump.contains("123456789:;<=>?@")); + assertTrue(dump.contains("123456789:;<=>?@"), "Had: \n" + dump); } - @Test(expected=ArrayIndexOutOfBoundsException.class) + @Test public void testDumpToStringOutOfIndex1() { - HexDump.dump(new byte[1], 0, -1); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testDumpToStringOutOfIndex2() { - HexDump.dump(new byte[1], 0, 2); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testDumpToStringOutOfIndex3() { - HexDump.dump(new byte[1], 0, 1); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(new byte[1], 0, -1)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(new byte[1], 0, 2)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(new byte[1], 0, 1)); } @Test diff --git a/src/testcases/org/apache/poi/util/TestIOUtils.java b/src/testcases/org/apache/poi/util/TestIOUtils.java index fbef102f17..6a7710484c 100644 --- a/src/testcases/org/apache/poi/util/TestIOUtils.java +++ b/src/testcases/org/apache/poi/util/TestIOUtils.java @@ -17,12 +17,12 @@ package org.apache.poi.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; @@ -38,19 +38,19 @@ import java.nio.charset.StandardCharsets; import java.util.Random; import org.apache.poi.EmptyFileException; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Class to test IOUtils */ public final class TestIOUtils { - static File TMP; - static final long LENGTH = 300+new Random().nextInt(9000); + private static File TMP; + private static final long LENGTH = 300+new Random().nextInt(9000); - @BeforeClass + @BeforeAll public static void setUp() throws IOException { TMP = File.createTempFile("poi-ioutils-", ""); OutputStream os = new FileOutputStream(TMP); @@ -62,11 +62,15 @@ public final class TestIOUtils { } - @AfterClass + @AfterAll public static void tearDown() { if (TMP != null) assertTrue(TMP.delete()); } + private static InputStream data123() { + return new ByteArrayInputStream(new byte[]{1,2,3}); + } + @Test public void testPeekFirst8Bytes() throws Exception { assertArrayEquals("01234567".getBytes(StandardCharsets.UTF_8), @@ -81,43 +85,38 @@ public final class TestIOUtils { @Test public void testPeekFirst8BytesTooLessAvailable() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3, 0, 0, 0, 0, 0}, - IOUtils.peekFirst8Bytes(new ByteArrayInputStream(new byte[] { 1, 2, 3}))); + assertArrayEquals(new byte[] { 1, 2, 3, 0, 0, 0, 0, 0}, IOUtils.peekFirst8Bytes(data123())); } - @Test(expected = EmptyFileException.class) - public void testPeekFirst8BytesEmpty() throws Exception { - IOUtils.peekFirst8Bytes(new ByteArrayInputStream(new byte[] {})); + @Test + public void testPeekFirst8BytesEmpty() { + assertThrows(EmptyFileException.class, () -> + IOUtils.peekFirst8Bytes(new ByteArrayInputStream(new byte[0]))); } @Test public void testToByteArray() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(new ByteArrayInputStream(new byte[] { 1, 2, 3}))); + assertArrayEquals(new byte[] { 1, 2, 3}, IOUtils.toByteArray(data123())); } - @Test(expected = IOException.class) - public void testToByteArrayToSmall() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(new ByteArrayInputStream(new byte[] { 1, 2, 3}), 10)); + @Test + public void testToByteArrayToSmall() { + assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10)); } - @Test(expected = IOException.class) - public void testToByteArrayMaxLengthToSmall() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(new ByteArrayInputStream(new byte[] { 1, 2, 3}), 10, 10)); + @Test + public void testToByteArrayMaxLengthToSmall() { + assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10, 10)); } - @Test(expected = RecordFormatException.class) - public void testToByteArrayNegativeLength() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(new ByteArrayInputStream(new byte[] { 1, 2, 3}), -1)); + @Test + public void testToByteArrayNegativeLength() { + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), -1)); } - @Test(expected = RecordFormatException.class) - public void testToByteArrayNegativeMaxLength() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(new ByteArrayInputStream(new byte[] { 1, 2, 3}), 10, -1)); + @Test + public void testToByteArrayNegativeMaxLength() { + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), 10, -1)); } @Test @@ -148,7 +147,7 @@ public final class TestIOUtils { public void testSkipFully() throws IOException { try (InputStream is = new FileInputStream(TMP)) { long skipped = IOUtils.skipFully(is, 20000L); - assertEquals("length: " + LENGTH, LENGTH, skipped); + assertEquals(LENGTH, skipped); } } @@ -156,7 +155,7 @@ public final class TestIOUtils { public void testSkipFullyGtIntMax() throws IOException { try (InputStream is = new FileInputStream(TMP)) { long skipped = IOUtils.skipFully(is, Integer.MAX_VALUE + 20000L); - assertEquals("length: " + LENGTH, LENGTH, skipped); + assertEquals(LENGTH, skipped); } } @@ -166,7 +165,7 @@ public final class TestIOUtils { try (InputStream is = new FileInputStream(TMP)) { IOUtils.copy(is, bos); long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), 20000L); - assertEquals("length: " + LENGTH, LENGTH, skipped); + assertEquals(LENGTH, skipped); } } @@ -176,7 +175,7 @@ public final class TestIOUtils { try (InputStream is = new FileInputStream(TMP)) { IOUtils.copy(is, bos); long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), Integer.MAX_VALUE + 20000L); - assertEquals("length: " + LENGTH, LENGTH, skipped); + assertEquals(LENGTH, skipped); } } @@ -188,28 +187,28 @@ public final class TestIOUtils { @Test public void testZeroByte() throws IOException { long skipped = IOUtils.skipFully((new ByteArrayInputStream(new byte[0])), 100); - assertEquals("zero byte", -1L, skipped); + assertEquals(-1L, skipped); } @Test public void testSkipZero() throws IOException { try (InputStream is = new FileInputStream(TMP)) { long skipped = IOUtils.skipFully(is, 0); - assertEquals("zero length", 0, skipped); + assertEquals(0, skipped); } } - @Test(expected = IllegalArgumentException.class) + @Test public void testSkipNegative() throws IOException { try (InputStream is = new FileInputStream(TMP)) { - IOUtils.skipFully(is, -1); + assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(is, -1)); } } - @Test(expected = RecordFormatException.class) + @Test public void testMaxLengthTooLong() throws IOException { try (InputStream is = new FileInputStream(TMP)) { - IOUtils.toByteArray(is, Integer.MAX_VALUE, 100); + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, Integer.MAX_VALUE, 100)); } } @@ -222,17 +221,17 @@ public final class TestIOUtils { } } - @Test(expected = RecordFormatException.class) + @Test public void testMaxLengthInvalid() throws IOException { try (InputStream is = new FileInputStream(TMP)) { - IOUtils.toByteArray(is, 90, 80); + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, 90, 80)); } } @Test public void testWonkyInputStream() throws IOException { long skipped = IOUtils.skipFully(new WonkyInputStream(), 10000); - assertEquals("length: "+LENGTH, 10000, skipped); + assertEquals(10000, skipped); } @Test @@ -257,16 +256,11 @@ public final class TestIOUtils { } @Test - public void testSetMaxOverrideOverLimit() throws IOException { + public void testSetMaxOverrideOverLimit() { IOUtils.setByteArrayMaxOverride(2); try { ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - try { - IOUtils.toByteArray(stream); - fail("Should have caught an Exception here"); - } catch (RecordFormatException e) { - // expected - } + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream)); } finally { IOUtils.setByteArrayMaxOverride(-1); } @@ -298,12 +292,7 @@ public final class TestIOUtils { IOUtils.setByteArrayMaxOverride(2); try { ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - try { - IOUtils.toByteArray(stream, 3, 100); - fail("Should have caught an Exception here"); - } catch (RecordFormatException e) { - // expected - } + assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream, 3, 100)); } finally { IOUtils.setByteArrayMaxOverride(-1); } diff --git a/src/testcases/org/apache/poi/util/TestIntList.java b/src/testcases/org/apache/poi/util/TestIntList.java index 25d427d361..1efadc0c91 100644 --- a/src/testcases/org/apache/poi/util/TestIntList.java +++ b/src/testcases/org/apache/poi/util/TestIntList.java @@ -17,15 +17,15 @@ package org.apache.poi.util; -import org.junit.Test; +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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; /** * Class to test IntList @@ -50,18 +50,17 @@ public final class TestIntList { @Test public void testAdd() { - IntList list = new IntList(); - int[] testArray = - { - 0, 1, 2, 3, 5 - }; + 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)); + for (int j = 0; j < testArray.length; j++) { + assertEquals(testArray[j], list.get(j)); } assertEquals(testArray.length, list.size()); @@ -69,59 +68,44 @@ public final class TestIntList { 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)); + 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++) - { + 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++) - { + for (int j = 0; j < list.size(); j++) { assertEquals(j - 1, list.get(j)); } // add past end - try - { - list.add(list.size() + 1, 8); - fail("should have thrown exception"); - } - catch (IndexOutOfBoundsException e) - { - - // as expected - } + 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++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { assertEquals(j, list.get(j)); } list = new IntList(0); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(0, j); } assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { assertEquals(j, list.get(999 - j)); } } @@ -130,8 +114,7 @@ public final class TestIntList { public void testAddAll() { IntList list = new IntList(); - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { list.add(j); } IntList list2 = new IntList(0); @@ -139,29 +122,19 @@ public final class TestIntList { list2.addAll(list); list2.addAll(list); assertEquals(2 * list.size(), list2.size()); - for (int j = 0; j < 5; j++) - { + 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(); + int limit = list.size(); - for (int j = 0; j < limit; j++) - { + for (int j = 0; j < limit; j++) { assertTrue(list.addAll(j, empty)); assertEquals(limit, list.size()); } - try - { - list.addAll(limit + 1, empty); - fail("should have thrown an exception"); - } - catch (IndexOutOfBoundsException e) - { - // as expected - } + assertThrows(IndexOutOfBoundsException.class, () -> list.addAll(limit + 1, empty)); // try add at beginning empty.addAll(0, list); @@ -215,20 +188,17 @@ public final class TestIntList { public void testClear() { IntList list = new IntList(); - for (int j = 0; j < 500; j++) - { + 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++) - { + for (int j = 0; j < 500; j++) { list.add(j + 1); } assertEquals(500, list.size()); - for (int j = 0; j < 500; j++) - { + for (int j = 0; j < 500; j++) { assertEquals(j + 1, list.get(j)); } } @@ -237,18 +207,13 @@ public final class TestIntList { public void testContains() { IntList list = new IntList(); - for (int j = 0; j < 1000; j += 2) - { + for (int j = 0; j < 1000; j += 2) { list.add(j); } - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { + for (int j = 0; j < 1000; j++) { + if (j % 2 == 0) { assertTrue(list.contains(j)); - } - else - { + } else { assertFalse(list.contains(j)); } } @@ -259,8 +224,7 @@ public final class TestIntList { IntList list = new IntList(); assertTrue(list.containsAll(list)); - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { list.add(j); } IntList list2 = new IntList(list); @@ -306,46 +270,27 @@ public final class TestIntList { public void testGet() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } - for (int j = 0; j < 1001; j++) - { - try - { - assertEquals(j, list.get(j)); - if (j == 1000) - { - fail("should have gotten exception"); - } - } - catch (IndexOutOfBoundsException e) - { - if (j != 1000) - { - fail("unexpected IndexOutOfBoundsException"); - } - } + for (int j = 0; j < 1000; j++) { + assertEquals(j, list.get(j)); } + + assertThrows(IndexOutOfBoundsException.class, () -> list.get(1000)); } @Test public void testIndexOf() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j / 2); } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { + for (int j = 0; j < 1000; j++) { + if (j < 500) { assertEquals(j * 2, list.indexOf(j)); - } - else - { + } else { assertEquals(-1, list.indexOf(j)); } } @@ -378,18 +323,13 @@ public final class TestIntList { public void testLastIndexOf() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j / 2); } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { + for (int j = 0; j < 1000; j++) { + if (j < 500) { assertEquals(1 + j * 2, list.lastIndexOf(j)); - } - else - { + } else { assertEquals(-1, list.indexOf(j)); } } @@ -399,48 +339,33 @@ public final class TestIntList { public void testRemove() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } - for (int j = 0; j < 1000; 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++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { assertEquals(999 - j, list.remove(999 - j)); assertEquals(999 - j, list.size()); } - try - { - list.remove(0); - fail("should have caught IndexOutOfBoundsException"); - } - catch (IndexOutOfBoundsException e) - { - // as expected - } + assertThrows(IndexOutOfBoundsException.class, () -> list.remove(0)); } @Test public void testRemoveValue() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j / 2); } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { + for (int j = 0; j < 1000; j++) { + if (j < 500) { assertTrue(list.removeValue(j)); assertTrue(list.removeValue(j)); } @@ -452,22 +377,17 @@ public final class TestIntList { public void testRemoveAll() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); + IntList listOdd = new IntList(); IntList listEven = new IntList(); - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { + for (int j = 0; j < 1000; j++) { + if (j % 2 == 0) { listEven.add(j); - } - else - { + } else { listOdd.add(j); } } @@ -494,22 +414,17 @@ public final class TestIntList { public void testRetainAll() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); + IntList listOdd = new IntList(); IntList listEven = new IntList(); - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { + for (int j = 0; j < 1000; j++) { + if (j % 2 == 0) { listEven.add(j); - } - else - { + } else { listOdd.add(j); } } @@ -535,43 +450,26 @@ public final class TestIntList { public void testSet() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + for (int j = 0; j < 1000; j++) { list.add(j); } - for (int j = 0; j < 1001; j++) - { - try - { - list.set(j, j + 1); - if (j == 1000) - { - fail("Should have gotten exception"); - } - assertEquals(j + 1, list.get(j)); - } - catch (IndexOutOfBoundsException e) - { - if (j != 1000) - { - fail("premature exception"); - } - } + 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 public void testSize() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + 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++) - { + for (int j = 0; j < 1000; j++) { assertEquals(1000 - j, list.size()); list.removeValue(j); assertEquals(999 - j, list.size()); @@ -582,41 +480,36 @@ public final class TestIntList { public void testToArray() { IntList list = new IntList(); - for (int j = 0; j < 1000; j++) - { + 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)); + for (int j = 0; j < 1000; j++) { + assertEquals(a1[j], list.get(j)); } - int[] a2 = new int[ list.size() ]; + 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)); + 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); + 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)); + 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)); + 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 index e9ca052944..517216dbf3 100644 --- a/src/testcases/org/apache/poi/util/TestIntegerField.java +++ b/src/testcases/org/apache/poi/util/TestIntegerField.java @@ -17,13 +17,13 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Test IntegerField code @@ -34,48 +34,26 @@ public final class TestIntegerField { @Test public void testConstructors() { - try - { - new IntegerField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1)); IntegerField field = new IntegerField(2); assertEquals(0, field.get()); - try - { - new IntegerField(-1, 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1, 1)); field = new IntegerField(2, 0x12345678); assertEquals(0x12345678, field.get()); - byte[] array = new byte[ 6 ]; - try - { - new IntegerField(-1, 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + 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 ]); - array = new byte[ 5 ]; - try - { - new IntegerField(2, 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(2, 5, new byte[ 5 ])); + for (int element : _test_array) { array = new byte[ 4 ]; new IntegerField(0, element, array); @@ -90,43 +68,31 @@ public final class TestIntegerField { for (int j = 0; j < _test_array.length; j++) { field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); field = new IntegerField(0); field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); - assertEquals("testing _3.2 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 16) % 256), - array[ 2 ]); - assertEquals("testing _3.3 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 24) % 256), - array[ 3 ]); + 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 public void testReadFromBytes() { - IntegerField field = new IntegerField(1); + IntegerField field1 = new IntegerField(1); byte[] array = new byte[ 4 ]; - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new IntegerField(0); + 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); - field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); + field2.readFromBytes(array); + assertEquals(_test_array[ j ], field2.get(), "testing " + j); } } @@ -145,7 +111,7 @@ public final class TestIntegerField { for (int j = 0; j < buffer.length / 4; j++) { field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "Testing " + j); } } @@ -163,7 +129,7 @@ public final class TestIntegerField { val += (array[ 2 ] << 16) & 0x00FF0000; val += (array[ 1 ] << 8) & 0x0000FF00; val += (array[ 0 ] & 0x000000FF); - assertEquals("testing ", b, val); + assertEquals(b, val, "testing "); } } } diff --git a/src/testcases/org/apache/poi/util/TestLittleEndian.java b/src/testcases/org/apache/poi/util/TestLittleEndian.java index 24072fa656..30d3a8e96e 100644 --- a/src/testcases/org/apache/poi/util/TestLittleEndian.java +++ b/src/testcases/org/apache/poi/util/TestLittleEndian.java @@ -17,16 +17,16 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test LittleEndian functionality @@ -81,7 +81,7 @@ public final class TestLittleEndian { assertEquals(testdata3[2], (byte)0xFF); assertEquals(expected2, LittleEndian.getUShort(testdata3)); assertEquals(expected3, LittleEndian.getUShort(testdata3, 1)); - + } private static final byte[] _double_array = @@ -239,13 +239,13 @@ public final class TestLittleEndian { assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.LONG_SIZE)); } - private static byte[] _good_array = { - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, + private static final byte[] _good_array = { + 0x01, 0x02, 0x01, 0x02, + 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, }; - private static byte[] _bad_array = { + private static final byte[] _bad_array = { 0x01 }; @@ -269,13 +269,8 @@ public final class TestLittleEndian { } assertEquals(count, _good_array.length / LittleEndianConsts.SHORT_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readShort(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - // as expected - } + ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); + assertThrows(BufferUnderrunException.class, () -> LittleEndian.readShort(stream2)); } /** @@ -297,14 +292,8 @@ public final class TestLittleEndian { } } assertEquals(count, _good_array.length / LittleEndianConsts.INT_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readInt(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - - // as expected - } + ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); + assertThrows(BufferUnderrunException.class, () -> LittleEndian.readInt(stream2)); } /** @@ -325,18 +314,12 @@ public final class TestLittleEndian { break; } } - assertEquals(count, - _good_array.length / LittleEndianConsts.LONG_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readLong(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - // as expected - } + assertEquals(count, _good_array.length / LittleEndianConsts.LONG_SIZE); + ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); + assertThrows(BufferUnderrunException.class, () -> LittleEndian.readLong(stream2)); } - @Test(expected = BufferUnderrunException.class) + @Test public void testReadFromStream() throws IOException { int actual; actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 5, -128, })); @@ -345,7 +328,8 @@ public final class TestLittleEndian { actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, })); assertEquals(513, actual); - LittleEndian.readInt(new ByteArrayInputStream(new byte[] { 1, 2, 3, })); + assertThrows(BufferUnderrunException.class, () -> + LittleEndian.readInt(new ByteArrayInputStream(new byte[] { 1, 2, 3, }))); } @Test diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java index 7e048dbc3a..36af4524e9 100644 --- a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java +++ b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java @@ -17,17 +17,17 @@ package org.apache.poi.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; /** * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} @@ -74,8 +74,8 @@ public final class TestLittleEndianStreams { byte[] actBuf = new byte[4]; lei.readFully(actBuf); - assertFalse("Identified bug in readFully() - source buffer was modified", - actBuf[0] == 0x00 && srcBuf[0] == 0x77 && srcBuf[3] == 0x44); + 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); diff --git a/src/testcases/org/apache/poi/util/TestLocaleUtil.java b/src/testcases/org/apache/poi/util/TestLocaleUtil.java index aeb79b973c..0b6b8d6642 100644 --- a/src/testcases/org/apache/poi/util/TestLocaleUtil.java +++ b/src/testcases/org/apache/poi/util/TestLocaleUtil.java @@ -17,17 +17,17 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assume.assumeFalse; +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.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestLocaleUtil { @@ -41,7 +41,7 @@ public class TestLocaleUtil { * 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. */ - @Before + @BeforeEach @SuppressForbidden("implementation around default locales in POI") public void setUp() { // reset the user locale and time zone so that tests do not interfere with each other @@ -60,7 +60,7 @@ public class TestLocaleUtil { * Reset the Locale to the user default after the test so that it doesn't influence * other tests. */ - @After + @AfterEach public void tearDown() { LocaleUtil.resetUserLocale(); LocaleUtil.resetUserTimeZone(); @@ -118,10 +118,10 @@ public class TestLocaleUtil { private static void assertCalendarNotEquals(Calendar expected, Calendar actual) { // FIXME: add more tests to compare calendars, ignoring whether the dates are equal - assertNotEquals("time zone", expected.getTimeZone(), actual.getTimeZone()); + 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("time zone", expected.getTimeZone(), actual.getTimeZone()); + 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 index 7f50bd97cd..952af51bb3 100644 --- a/src/testcases/org/apache/poi/util/TestLongField.java +++ b/src/testcases/org/apache/poi/util/TestLongField.java @@ -17,13 +17,14 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Test LongField code @@ -37,33 +38,21 @@ public final class TestLongField { @Test public void testConstructors() { - try { - new LongField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - LongField field = new LongField(2); + 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 ])); + - assertEquals(0L, field.get()); - try { - new LongField(-1, 1L); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new LongField(2, 0x123456789ABCDEF0L); - assertEquals(0x123456789ABCDEF0L, field.get()); byte[] array = new byte[ 10 ]; - - try { - new LongField(-1, 1L, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new LongField(2, 0x123456789ABCDEF0L, array); + LongField field = new LongField(2, 0x123456789ABCDEF0L, array); assertEquals(0x123456789ABCDEF0L, field.get()); assertEquals(( byte ) 0xF0, array[ 2 ]); assertEquals(( byte ) 0xDE, array[ 3 ]); @@ -73,13 +62,9 @@ public final class TestLongField { assertEquals(( byte ) 0x56, array[ 7 ]); assertEquals(( byte ) 0x34, array[ 8 ]); assertEquals(( byte ) 0x12, array[ 9 ]); - array = new byte[ 9 ]; - try { - new LongField(2, 5L, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(2, 5L, new byte[ 9 ])); + for (long element : _test_array) { array = new byte[ 8 ]; new LongField(0, element, array); @@ -94,33 +79,18 @@ public final class TestLongField { for (int j = 0; j < _test_array.length; j++) { field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); field = new LongField(0); field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); - assertEquals("testing _3.2 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 16) % 256), - array[ 2 ]); - assertEquals("testing _3.3 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 24) % 256), - array[ 3 ]); - assertEquals("testing _3.4 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 32) % 256), - array[ 4 ]); - assertEquals("testing _3.5 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 40) % 256), - array[ 5 ]); - assertEquals("testing _3.6 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 48) % 256), - array[ 6 ]); - assertEquals("testing _3.7 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 56) % 256), - array[ 7 ]); + 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 ]); } } @@ -146,7 +116,7 @@ public final class TestLongField { array[ 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); array[ 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing " + j); } } @@ -169,7 +139,7 @@ public final class TestLongField { for (int j = 0; j < buffer.length / 8; j++) { field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "Testing " + j); } } @@ -191,7 +161,7 @@ public final class TestLongField { val += ((( long ) array[ 2 ]) << 16) & 0x0000000000FF0000L; val += ((( long ) array[ 1 ]) << 8) & 0x000000000000FF00L; val += (array[ 0 ] & 0x00000000000000FFL); - assertEquals("testing ", element, val); + assertEquals(element, val, "testing "); } } } diff --git a/src/testcases/org/apache/poi/util/TestPOILogFactory.java b/src/testcases/org/apache/poi/util/TestPOILogFactory.java index 666d1d9b2f..a4580bb04a 100644 --- a/src/testcases/org/apache/poi/util/TestPOILogFactory.java +++ b/src/testcases/org/apache/poi/util/TestPOILogFactory.java @@ -17,7 +17,7 @@ package org.apache.poi.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class TestPOILogFactory { diff --git a/src/testcases/org/apache/poi/util/TestPOILogger.java b/src/testcases/org/apache/poi/util/TestPOILogger.java index 0c6765cf14..d40d475ac7 100644 --- a/src/testcases/org/apache/poi/util/TestPOILogger.java +++ b/src/testcases/org/apache/poi/util/TestPOILogger.java @@ -18,11 +18,11 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the log class. @@ -30,7 +30,7 @@ import org.junit.Test; public final class TestPOILogger implements POILogger { private String lastLog = ""; private Throwable lastEx; - + /** * Test different types of log output. */ @@ -41,23 +41,23 @@ public final class TestPOILogger implements POILogger { POILogFactory._loggerClassName = TestPOILogger.class.getName(); POILogger log = POILogFactory.getLogger( "foo" ); assertTrue(log instanceof TestPOILogger); - + TestPOILogger tLog = (TestPOILogger)log; - + log.log(POILogger.WARN, "Test = ", 1); assertEquals("Test = 1", tLog.lastLog); - + log.log(POILogger.ERROR, "Test ", 1,2,new Exception("bla")); assertEquals("Test 12", tLog.lastLog); assertNotNull(tLog.lastEx); - + log.log(POILogger.ERROR, "log\nforging", "\nevil","\nlog"); assertEquals("log forging evil log", tLog.lastLog); } finally { POILogFactory._loggerClassName = oldLCN; } } - + // ---------- POI Logger methods implemented for testing ---------- @Override diff --git a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java b/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java index b403fc53a0..ee43e08df1 100644 --- a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java +++ b/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java @@ -17,8 +17,8 @@ package org.apache.poi.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -26,33 +26,33 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public 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 public void noCompressionExample() { @@ -66,23 +66,23 @@ public class TestRLEDecompressingInputStream { /** * 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: * @@ -102,23 +102,23 @@ public class TestRLEDecompressingInputStream { 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: * @@ -136,7 +136,7 @@ public class TestRLEDecompressingInputStream { final String expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; checkRLEDecompression(expected, compressed); } - + @Test public void decompress() throws IOException { final byte[] compressed = { @@ -146,7 +146,7 @@ public class TestRLEDecompressingInputStream { 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(); diff --git a/src/testcases/org/apache/poi/util/TestShortField.java b/src/testcases/org/apache/poi/util/TestShortField.java index c31202f2cc..2ae0cb6ef0 100644 --- a/src/testcases/org/apache/poi/util/TestShortField.java +++ b/src/testcases/org/apache/poi/util/TestShortField.java @@ -17,13 +17,14 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Test ShortField code @@ -34,42 +35,24 @@ public final class TestShortField { @Test public void testConstructors() { - try { - new ShortField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1)); ShortField field = new ShortField(2); assertEquals(0, field.get()); - try { - new ShortField(-1, ( short ) 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1, ( short ) 1)); field = new ShortField(2, ( short ) 0x1234); assertEquals(0x1234, field.get()); - byte[] array = new byte[ 4 ]; - try { - new ShortField(-1, ( short ) 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + 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 ]); - array = new byte[ 3 ]; - try { - new ShortField(2, ( short ) 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } + + 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); @@ -84,36 +67,29 @@ public final class TestShortField { for (int j = 0; j < _test_array.length; j++) { field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); field = new ShortField(0); field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); + 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 public void testReadFromBytes() { - ShortField field = new ShortField(1); + ShortField field1 = new ShortField(1); byte[] array = new byte[ 2 ]; - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ShortField(0); + 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); - field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); + field2.readFromBytes(array); + assertEquals(_test_array[ j ], field2.get(), "testing " + j); } } @@ -132,7 +108,7 @@ public final class TestShortField { for (int j = 0; j < buffer.length / 2; j++) { field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); + assertEquals(_test_array[ j ], field.get(), "Testing " + j); } } @@ -148,7 +124,7 @@ public final class TestShortField { val &= ( short ) 0xFF00; val += ( short ) (array[ 0 ] & 0x00FF); - assertEquals("testing ", element, val); + assertEquals(element, val, "testing "); } } } diff --git a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java b/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java index e61aea653f..7152ec6cef 100644 --- a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java +++ b/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java @@ -17,11 +17,12 @@ package org.apache.poi.util; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit test for StringCodepointsIterable @@ -37,8 +38,8 @@ public class TestStringCodepointsIterable { List codePoints2 = new ArrayList<>(); sci.iterator().forEachRemaining(codePoints::add); sci.iterator().forEachRemaining(codePoints2::add); - Assert.assertEquals(17, codePoints.size()); - Assert.assertEquals(codePoints, codePoints2); + 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 index b70a7dbda1..a03ab6a127 100644 --- a/src/testcases/org/apache/poi/util/TestStringUtil.java +++ b/src/testcases/org/apache/poi/util/TestStringUtil.java @@ -17,14 +17,15 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Test; +import org.junit.jupiter.api.Test; /** * Unit test for StringUtil @@ -66,82 +67,60 @@ public class TestStringUtil { StringUtil.putCompressedUnicode( input, output, 0 ); for ( int j = 0; j < expected_output.length; j++ ) { - assertEquals( "testing offset " + j, expected_output[j], - output[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( "testing offset " + j, expected_output[j], - output[100 + j - expected_output.length] ); - } - try - { - StringUtil.putCompressedUnicode( input, output, - 101 - expected_output.length ); - fail( "Should have caught ArrayIndexOutOfBoundsException" ); - } - catch ( ArrayIndexOutOfBoundsException ignored ) - { - // as expected + 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 public 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 - }; + 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( "testing offset " + j, expected_output[j], - output[j] ); + 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( "testing offset " + j, expected_output[j], - output[100 + j - expected_output.length] ); - } - try - { - StringUtil.putUnicodeLE( input, output, - 101 - expected_output.length ); - fail( "Should have caught ArrayIndexOutOfBoundsException" ); - } - catch ( ArrayIndexOutOfBoundsException ignored ) - { - // as expected + 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 public void startsWithIgnoreCase() { - assertTrue("same string", StringUtil.startsWithIgnoreCase("Apache POI", "Apache POI")); - assertTrue("longer string", StringUtil.startsWithIgnoreCase("Apache POI project", "Apache POI")); - assertTrue("different case", StringUtil.startsWithIgnoreCase("APACHE POI", "Apache POI")); - assertFalse("leading whitespace should not be ignored", StringUtil.startsWithIgnoreCase(" Apache POI project", "Apache POI")); - assertFalse("shorter string", StringUtil.startsWithIgnoreCase("Apache", "Apache POI")); + 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 public void endsWithIgnoreCase() { - assertTrue("same string", StringUtil.endsWithIgnoreCase("Apache POI", "Apache POI")); - assertTrue("longer string", StringUtil.endsWithIgnoreCase("Project Apache POI", "Apache POI")); - assertTrue("different case", StringUtil.endsWithIgnoreCase("APACHE POI", "Apache POI")); - assertFalse("trailing whitespace should not be ignored", StringUtil.endsWithIgnoreCase("Apache POI project ", "Apache POI")); - assertFalse("shorter string", StringUtil.endsWithIgnoreCase("Apache", "Apache POI")); + 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 @@ -152,27 +131,27 @@ public class TestStringUtil { 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("no separator", "ApachePOIproject", StringUtil.join(arr)); - assertEquals("separator", "Apache POI project", StringUtil.join(arr, " ")); + assertEquals("ApachePOIproject", StringUtil.join(arr), "no separator"); + assertEquals("Apache POI project", StringUtil.join(arr, " "), "separator"); } @Test public void count() { String test = "Apache POI project\n\u00a9 Copyright 2016"; // supports search in null or empty string - assertEquals("null", 0, StringUtil.countMatches(null, 'A')); - assertEquals("empty string", 0, StringUtil.countMatches("", 'A')); + assertEquals(0, StringUtil.countMatches(null, 'A'), "null"); + assertEquals(0, StringUtil.countMatches("", 'A'), "empty string"); - assertEquals("normal", 2, StringUtil.countMatches(test, 'e')); - assertEquals("normal, should not find a in escaped copyright", 1, StringUtil.countMatches(test, 'a')); + 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("null character", 0, StringUtil.countMatches(test, '\0')); - assertEquals("CR", 0, StringUtil.countMatches(test, '\r')); - assertEquals("LF", 1, StringUtil.countMatches(test, '\n')); + 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("Unicode", 1, StringUtil.countMatches(test, '\u00a9')); + 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 index ac1904dabc..8ed0e837c1 100644 --- a/src/testcases/org/apache/poi/util/TestTempFile.java +++ b/src/testcases/org/apache/poi/util/TestTempFile.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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; @@ -28,20 +28,20 @@ import java.io.IOException; import java.util.Arrays; import org.apache.poi.poifs.dev.TestPOIFSDump; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestTempFile { private String previousTempDir; private File tempDir; - @Before + @BeforeEach public void setUp() throws IOException { previousTempDir = System.getProperty(TempFile.JAVA_IO_TMPDIR); if(previousTempDir != null) { - assertTrue("Failed to create directory " + previousTempDir, - new File(previousTempDir).exists() || new File(previousTempDir).mkdirs()); + 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 @@ -51,19 +51,19 @@ public class TestTempFile { System.setProperty(TempFile.JAVA_IO_TMPDIR, tempDir.getAbsolutePath()); } - @After + @AfterEach public void tearDown() throws IOException { if(tempDir != null) { String[] files = tempDir.list(); assertNotNull(files); // can have the "poifiles" subdir if (files.length == 1) { - assertEquals("Had: " + Arrays.toString(files), DefaultTempFileCreationStrategy.POIFILES, files[0]); + assertEquals(DefaultTempFileCreationStrategy.POIFILES, files[0], "Had: " + Arrays.toString(files)); files = new File(tempDir, files[0]).list(); assertNotNull(files); - assertEquals("Had: " + Arrays.toString(files), 0, files.length); + assertEquals(0, files.length, "Had: " + Arrays.toString(files)); } else { - assertEquals("Had: " + Arrays.toString(files), 0, files.length); + assertEquals(0, files.length, "Had: " + Arrays.toString(files)); } // remove the directory after the tests @@ -92,41 +92,35 @@ public class TestTempFile { FileOutputStream fos = new FileOutputStream(tempFile); fos.write(1); //file can be written to fos.close(); - assertTrue("temp file exists", tempFile.exists()); - assertTrue("temp file is a file", tempFile.isFile()); - assertTrue("temp file's name should start with test", - tempFile.getName().startsWith("test")); - assertTrue("temp file's name should end with .txt", - tempFile.getName().endsWith(".txt")); - assertEquals("temp file is saved in poifiles directory", - DefaultTempFileCreationStrategy.POIFILES, tempFile.getParentFile().getName()); + 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("Unable to delete temp file", tempFile.delete()); + assertTrue(tempFile.delete()); } @Test public void createTempFileWithDefaultSuffix() throws IOException { File tempFile = TempFile.createTempFile("test", null); - assertTrue("temp file's name should end with .tmp", - tempFile.getName().endsWith(".tmp")); + assertTrue(tempFile.getName().endsWith(".tmp")); } @Test public void testCreateTempDirectory() throws IOException { File tempDir = TempFile.createTempDirectory("testDir"); - assertTrue("testDir exists", tempDir.exists()); - assertTrue("testDir is a directory", tempDir.isDirectory()); - assertTrue("testDir's name starts with testDir", - tempDir.getName().startsWith("testDir")); - assertEquals("tempDir is saved in poifiles directory", - DefaultTempFileCreationStrategy.POIFILES, tempDir.getParentFile().getName()); + 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("Unable to delete tempDir", tempDir.delete()); + assertTrue(tempDir.delete()); } @Test diff --git a/src/testcases/org/apache/poi/util/TestXMLHelper.java b/src/testcases/org/apache/poi/util/TestXMLHelper.java index 5536168545..478ba0dbe0 100644 --- a/src/testcases/org/apache/poi/util/TestXMLHelper.java +++ b/src/testcases/org/apache/poi/util/TestXMLHelper.java @@ -17,11 +17,11 @@ package org.apache.poi.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +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; @@ -36,7 +36,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.XMLReader; @@ -121,9 +121,9 @@ public class TestXMLHelper { 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("Had Exception about not-recognized SAX feature: " + e + " which is only expected" + - " for Xerces XML Parser, but had parser: " + reader, - reader.getClass().getName().contains("org.apache.xerces")); + 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); }