From: Andreas Beeker Date: Tue, 18 Aug 2020 13:50:31 +0000 (+0000) Subject: Update library versions X-Git-Tag: before_ooxml_3rd_edition~134 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=a73348fe8bac35ead3d72c76179d3bcacbd2a01a;p=poi.git Update library versions Replace deprecated junit @Rules with assertThrows Adapt to XMLSec refactoring in version 2.2.0 git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1880965 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/build.xml b/build.xml index 54537d17fd..b95d541ddb 100644 --- a/build.xml +++ b/build.xml @@ -208,10 +208,20 @@ under the License. @{artifact} - + + + + @{artifact} + + + + + + + @@ -225,13 +235,23 @@ under the License. + + + + + + + + + + - + - + @@ -250,50 +270,50 @@ under the License. - - - - - - - - + + + + + + + + - + + + - - + + - - - + - + - - - + + + - + @@ -332,23 +352,30 @@ under the License. - - - + + + + - - - - + + + + + + + + - + @@ -560,29 +587,9 @@ under the License. - - - - - - - - - - - - - - - - - - - - - - - + + + @@ -694,12 +701,15 @@ under the License. + - + + + @@ -712,7 +722,9 @@ under the License. - + + + @@ -2475,15 +2487,14 @@ under the License. - - + - - + + @@ -2592,7 +2603,9 @@ under the License. - + + + diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java index 7f9692ecdc..9fd9b96bd6 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java @@ -119,6 +119,7 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianByteArrayOutputStream; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; +import org.apache.poi.util.Removal; /** * High level representation of a workbook. This is the first object most users @@ -1151,7 +1152,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss public HSSFFont createFont() { /*FontRecord font =*/ workbook.createNewFont(); - int fontindex = getNumberOfFontsAsInt() - 1; + int fontindex = getNumberOfFonts() - 1; if (fontindex > 3) { fontindex++; // THERE IS NO FOUR!! @@ -1172,7 +1173,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss public HSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { - int numberOfFonts = getNumberOfFontsAsInt(); + int numberOfFonts = getNumberOfFonts(); for (int i = 0; i <= numberOfFonts; i++) { // Remember - there is no 4! if (i == 4) { @@ -1202,6 +1203,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss @Override @Deprecated + @Removal(version="6.0.0") public int getNumberOfFontsAsInt() { return getNumberOfFonts(); } diff --git a/src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java b/src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java index 5f31274439..076eafd03c 100644 --- a/src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java +++ b/src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java @@ -260,7 +260,7 @@ public final class AnalysisToolPak implements UDFFinder { } FreeRefFunction f = inst.findFunction(name); if(f != null && !(f instanceof NotImplemented)) { - throw new IllegalArgumentException("POI already implememts " + name + + throw new IllegalArgumentException("POI already implements " + name + ". You cannot override POI's implementations of Excel functions"); } diff --git a/src/java/org/apache/poi/ss/formula/eval/FunctionEval.java b/src/java/org/apache/poi/ss/formula/eval/FunctionEval.java index ad034e1a67..da670439a9 100644 --- a/src/java/org/apache/poi/ss/formula/eval/FunctionEval.java +++ b/src/java/org/apache/poi/ss/formula/eval/FunctionEval.java @@ -189,7 +189,7 @@ public final class FunctionEval { retval[FunctionID.INDIRECT] = null; // Indirect.evaluate has different signature retval[162] = TextFunction.CLEAN; - + retval[163] = MatrixFunction.MDETERM; retval[164] = MatrixFunction.MINVERSE; retval[165] = MatrixFunction.MMULT; @@ -394,7 +394,7 @@ public final class FunctionEval { if(functions[idx] instanceof NotImplementedFunction) { functions[idx] = func; } else { - throw new IllegalArgumentException("POI already implememts " + name + + throw new IllegalArgumentException("POI already implements " + name + ". You cannot override POI's implementations of Excel functions"); } } diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java index 60b9e26e67..5e1ee2fbe4 100644 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java +++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java @@ -299,7 +299,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet { * and will be missing from the c14n resulting nodes. */ Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId); - c14nValue.write(c14n.canonicalizeSubtree(node)); + c14n.canonicalizeSubtree(node, c14nValue); } } catch (RuntimeException e) { throw e; 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 3e570e2b51..1a4940c051 100644 --- a/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java +++ b/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java @@ -21,6 +21,7 @@ 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; @@ -42,14 +43,11 @@ import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.poifs.filesystem.FileMagic; -import org.apache.poi.poifs.filesystem.NotOLE2FileException; 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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Test that the extractor factory plays nicely @@ -129,9 +127,6 @@ public class TestExtractorFactory { R apply(T t) throws IOException, OpenXML4JException, XmlException; } - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testFile() throws Exception { for (int i = 0; i < TEST_SET.length; i += 4) { @@ -142,11 +137,12 @@ public class TestExtractorFactory { } @Test - public void testFileInvalid() throws Exception { - thrown.expectMessage("Can't create extractor - unsupported file type: UNKNOWN"); - thrown.expect(IOException.class); - // Text - ExtractorFactory.createExtractor(txt); + public void testFileInvalid() { + IOException ex = assertThrows( + IOException.class, + () -> ExtractorFactory.createExtractor(txt) + ); + assertEquals("Can't create extractor - unsupported file type: UNKNOWN", ex.getMessage()); } @Test @@ -155,10 +151,11 @@ public class TestExtractorFactory { } @Test - public void testInputStreamInvalid() throws Exception { - thrown.expectMessage("Can't create extractor - unsupported file type: UNKNOWN"); - thrown.expect(IOException.class); - testInvalid(ExtractorFactory::createExtractor); + public void testInputStreamInvalid() throws IOException { + try (FileInputStream fis = new FileInputStream(txt)) { + IOException ex = assertThrows(IOException.class, () -> ExtractorFactory.createExtractor(fis)); + assertTrue(ex.getMessage().contains(FileMagic.UNKNOWN.name())); + } } @Test @@ -167,10 +164,12 @@ public class TestExtractorFactory { } @Test - public void testPOIFSInvalid() throws Exception { - thrown.expectMessage("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0"); - thrown.expect(NotOLE2FileException.class); - testInvalid((f) -> ExtractorFactory.createExtractor(new POIFSFileSystem(f))); + public void testPOIFSInvalid() { + IOException ex = assertThrows( + IOException.class, + () -> ExtractorFactory.createExtractor(new POIFSFileSystem(txt)) + ); + assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0")); } private void testStream(final FunctionEx poifsIS, final boolean loadOOXML) @@ -199,17 +198,6 @@ public class TestExtractorFactory { } } - private void testInvalid(FunctionEx poifs) throws IOException, OpenXML4JException, XmlException { - // Text - try (FileInputStream fis = new FileInputStream(txt); - POITextExtractor ignored = poifs.apply(fis)) { - fail("extracting from invalid package"); - } catch (IllegalArgumentException e) { - assertTrue("Had: " + e, e.getMessage().contains(FileMagic.UNKNOWN.name())); - throw e; - } - } - @Test public void testPackage() throws Exception { for (int i = 0; i < TEST_SET.length; i += 4) { @@ -273,6 +261,7 @@ public class TestExtractorFactory { } try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) { + assertNotNull(extractor); assertTrue(extractor.getText().length() > 200); } } finally { @@ -296,6 +285,7 @@ public class TestExtractorFactory { assertTrue(extractor instanceof XSSFExcelExtractor); } try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString()))) { + assertNotNull(extractor); assertTrue(extractor.getText().length() > 200); } } 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 3858bc688d..4995fcb2ef 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java @@ -19,6 +19,7 @@ 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; @@ -29,9 +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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Tests for content type (ContentType class). @@ -40,9 +39,6 @@ public final class TestContentType { private static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; - @Rule - public ExpectedException exception = ExpectedException.none(); - /** * Check rule M1.13: Package implementers shall only create and only * recognize parts with a content type; format designers shall specify a @@ -158,12 +154,13 @@ public final class TestContentType { */ @Test public void testFileWithContentTypeEntities() throws Exception { - if (!isOldXercesActive()) { - exception.expect(InvalidFormatException.class); + try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml")) { + if (isOldXercesActive()) { + OPCPackage.open(is); + } else { + assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); + } } - - InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml"); - OPCPackage.open(is); } /** 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 d8fc1b7b84..5f95abd1ca 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java @@ -22,11 +22,11 @@ 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.hamcrest.core.StringContains.containsString; 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; @@ -50,6 +50,7 @@ import java.util.List; import java.util.TreeMap; import java.util.function.BiConsumer; import java.util.regex.Pattern; +import java.util.stream.Stream; import com.google.common.hash.Hashing; import com.google.common.io.Files; @@ -88,13 +89,9 @@ 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.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; -import org.hamcrest.core.AllOf; import org.junit.Ignore; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.function.ThrowingRunnable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -107,9 +104,6 @@ public final class TestPackage { private static final String CONTENT_EXT_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; private static final POIDataSamples xlsSamples = POIDataSamples.getSpreadSheetInstance(); - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - /** * Test that just opening and closing the file doesn't alter the document. */ @@ -645,115 +639,46 @@ public final class TestPackage { } } - - @Test - public void NonOOXML_OLE2Stream() throws Exception { - expectedEx.expect(OLE2NotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be in the OLE2 Format"), - containsString("You are calling the part of POI that deals with OOXML") - )); - try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.xls"); - OPCPackage p = OPCPackage.open(stream)) { - assertNotNull(p); - fail("Shouldn't be able to open OLE2"); - } - } - @Test - public void NonOOXML_OLE2File() throws Exception { - expectedEx.expect(OLE2NotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be in the OLE2 Format"), - containsString("You are calling the part of POI that deals with OOXML") - )); - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.xls"))) { - assertNotNull(p); - fail("Shouldn't be able to open OLE2"); - } - } - - @Test - public void NonOOXML_RawXmlStream() throws Exception { - expectedEx.expect(NotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be a raw XML file"), - containsString("Formats such as Office 2003 XML") - )); - try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.xml"); - OPCPackage p = OPCPackage.open(stream)) { - assertNotNull(p); - fail("Shouldn't be able to open XML"); - } - } - - @Test - public void NonOOXML_RawXmlFile() throws Exception { - expectedEx.expect(NotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be a raw XML file"), - containsString("Formats such as Office 2003 XML") - )); - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.xml"))) { - assertNotNull(p); - fail("Shouldn't be able to open XML"); - } - } - - @Test - public void NonOOXML_ODFStream() throws Exception { - expectedEx.expect(ODFNotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be in ODF"), - containsString("Formats like these (eg ODS") - )); - try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.ods"); - OPCPackage p = OPCPackage.open(stream)) { - assertNotNull(p); - fail("Shouldn't be able to open ODS"); - } - } - - @Test - public void NonOOXML_ODFFile() throws Exception { - expectedEx.expect(ODFNotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("The supplied data appears to be in ODF"), - containsString("Formats like these (eg ODS") - )); - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.ods"))) { - assertNotNull(p); - fail("Shouldn't be able to open ODS"); - } + public void NonOOXML_File() throws Exception { + handleNonOOXML( + "SampleSS.xls", OLE2NotOfficeXmlFileException.class, + "The supplied data appears to be in the OLE2 Format", + "You are calling the part of POI that deals with OOXML" + ); + + handleNonOOXML( + "SampleSS.xml", NotOfficeXmlFileException.class, + "The supplied data appears to be a raw XML file", + "Formats such as Office 2003 XML" + ); + + handleNonOOXML( + "SampleSS.ods", ODFNotOfficeXmlFileException.class, + "The supplied data appears to be in ODF", + "Formats like these (eg ODS" + ); + + handleNonOOXML( + "SampleSS.txt", NotOfficeXmlFileException.class, + "No valid entries or contents found", + "not a valid OOXML" + ); } - @Test - public void NonOOXML_TextStream() throws Exception { - expectedEx.expect(NotOfficeXmlFileException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("No valid entries or contents found"), - containsString("not a valid OOXML") - )); - try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.txt"); - OPCPackage p = OPCPackage.open(stream)) { - assertNotNull(p); - fail("Shouldn't be able to open Plain Text"); + private void handleNonOOXML(String file, Class exception, String... messageParts) throws IOException { + try (InputStream stream = xlsSamples.openResourceAsStream(file)) { + ThrowingRunnable[] 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); + Stream.of(messageParts).forEach(mp -> assertTrue(ex.getMessage().contains(mp))); + } } } - @Test - public void NonOOXML_TextFile() throws Exception { - // Unhelpful low-level error, sorry - expectedEx.expect(UnsupportedFileFormatException.class); - expectedEx.expectMessage(AllOf.allOf( - containsString("No valid entries or contents found"), - containsString("not a valid OOXML") - )); - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.txt"))) { - assertNotNull(p); - fail("Shouldn't be able to open Plain Text"); - } - } /** * Zip bomb handling test @@ -805,29 +730,32 @@ public final class TestPackage { } } - expectedEx.expect(IOException.class); - expectedEx.expectMessage("Zip bomb detected!"); - - try (Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))) { - wb.getSheetAt(0); - } + IOException ex = assertThrows( + IOException.class, + () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray())) + ); + assertTrue(ex.getMessage().contains("Zip bomb detected!")); } @Test - public void testZipEntityExpansionTerminates() throws IOException, OpenXML4JException, XmlException { - expectedEx.expect(IllegalStateException.class); - expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text."); - openXmlBombFile("poc-shared-strings.xlsx"); + public void testZipEntityExpansionTerminates() { + IllegalStateException ex = assertThrows( + IllegalStateException.class, + () -> openXmlBombFile("poc-shared-strings.xlsx") + ); + assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); } @Test - public void testZipEntityExpansionSharedStringTableEvents() throws IOException, OpenXML4JException, XmlException { + public void testZipEntityExpansionSharedStringTableEvents() { boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); ExtractorFactory.setThreadPrefersEventExtractors(true); try { - expectedEx.expect(IllegalStateException.class); - expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text."); - openXmlBombFile("poc-shared-strings.xlsx"); + IllegalStateException ex = assertThrows( + IllegalStateException.class, + () -> openXmlBombFile("poc-shared-strings.xlsx") + ); + assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); } finally { ExtractorFactory.setThreadPrefersEventExtractors(before); } @@ -835,19 +763,33 @@ public final class TestPackage { @Test - public void testZipEntityExpansionExceedsMemory() throws IOException, OpenXML4JException, XmlException { - expectedEx.expect(IOException.class); - expectedEx.expectMessage("unable to parse shared strings table"); - expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than")); - openXmlBombFile("poc-xmlbomb.xlsx"); + public void testZipEntityExpansionExceedsMemory() { + IOException ex = assertThrows( + IOException.class, + () -> openXmlBombFile("poc-xmlbomb.xlsx") + ); + assertTrue(ex.getMessage().contains("unable to parse shared strings table")); + assertTrue(matchSAXEx(ex)); } @Test - public void testZipEntityExpansionExceedsMemory2() throws IOException, OpenXML4JException, XmlException { - expectedEx.expect(IOException.class); - expectedEx.expectMessage("unable to parse shared strings table"); - expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than")); - openXmlBombFile("poc-xmlbomb-empty.xlsx"); + public void testZipEntityExpansionExceedsMemory2() { + IOException ex = assertThrows( + IOException.class, + () -> openXmlBombFile("poc-xmlbomb-empty.xlsx") + ); + assertTrue(ex.getMessage().contains("unable to parse shared strings table")); + assertTrue(matchSAXEx(ex)); + } + + private static boolean matchSAXEx(Exception root) { + for (Throwable t = root; t != null; t = t.getCause()) { + if (t.getClass().isAssignableFrom(SAXParseException.class) && + t.getMessage().contains("The parser has encountered more than")) { + return true; + } + } + return false; } private void openXmlBombFile(String file) throws IOException, OpenXML4JException, XmlException { @@ -873,24 +815,28 @@ public final class TestPackage { } @Test - public void zipBombCheckSizesRatioTooSmall() throws IOException, EncryptedDocumentException { - expectedEx.expect(POIXMLException.class); - expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMinInflateRatio()"); - getZipStatsAndConsume((max_size, min_ratio) -> { - // check ratio out of bounds - ZipSecureFile.setMinInflateRatio(min_ratio+0.002); - }); + public void zipBombCheckSizesRatioTooSmall() { + POIXMLException ex = assertThrows( + POIXMLException.class, + () -> getZipStatsAndConsume((max_size, min_ratio) -> { + // check ratio out of bounds + ZipSecureFile.setMinInflateRatio(min_ratio+0.002); + }) + ); + assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMinInflateRatio()")); } @Test public void zipBombCheckSizesSizeTooBig() throws IOException, EncryptedDocumentException { - expectedEx.expect(POIXMLException.class); - expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMaxEntrySize()"); - getZipStatsAndConsume((max_size, min_ratio) -> { - // check max entry size ouf of bounds - ZipSecureFile.setMinInflateRatio(min_ratio-0.002); - ZipSecureFile.setMaxEntrySize(max_size-200); - }); + POIXMLException ex = assertThrows( + POIXMLException.class, + () -> getZipStatsAndConsume((max_size, min_ratio) -> { + // check max entry size ouf of bounds + ZipSecureFile.setMinInflateRatio(min_ratio-0.002); + ZipSecureFile.setMaxEntrySize(max_size-200); + }) + ); + assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMaxEntrySize()")); } private void getZipStatsAndConsume(BiConsumer ratioCon) throws IOException { @@ -1121,42 +1067,6 @@ public final class TestPackage { } } - @SuppressWarnings("SameParameterValue") - private static AnyCauseMatcher getCauseMatcher(Class cause, String message) { - // junit is only using hamcrest-core, so instead of adding hamcrest-beans, we provide the throwable - // search with the basics... - // see https://stackoverflow.com/a/47703937/2066598 - return new AnyCauseMatcher<>(cause, message); - } - - private static class AnyCauseMatcher extends TypeSafeMatcher { - private final Class expectedType; - private final String expectedMessage; - - AnyCauseMatcher(Class expectedType, String expectedMessage) { - this.expectedType = expectedType; - this.expectedMessage = expectedMessage; - } - - @Override - protected boolean matchesSafely(final Throwable root) { - for (Throwable t = root; t != null; t = t.getCause()) { - if (t.getClass().isAssignableFrom(expectedType) && t.getMessage().contains(expectedMessage)) { - return true; - } - } - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("expects type ") - .appendValue(expectedType) - .appendText(" and a message ") - .appendValue(expectedMessage); - } - } - @SuppressWarnings("UnstableApiUsage") @Test public void testBug63029() throws Exception { 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 a4e977c148..988024907a 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 @@ -145,9 +145,7 @@ import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Ignore; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.w3.x2000.x09.xmldsig.ReferenceType; import org.w3.x2000.x09.xmldsig.SignatureDocument; import org.w3c.dom.Document; @@ -160,9 +158,6 @@ public class TestSignatureInfo { private KeyPair keyPair; private X509Certificate x509; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @AfterClass public static void removeUserLocale() { LocaleUtil.resetUserLocale(); 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 b02995fcdd..b4fb08fef0 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java @@ -17,6 +17,10 @@ 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 java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -33,30 +37,25 @@ 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.Rule; -import org.junit.rules.ExpectedException; public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); private static final String filename = "SampleShow.pptx"; private static final String password = "opensesame"; private static final String removeExpectedExceptionMsg = "This functionality this unit test is trying to test is now passing. " + "The unit test needs to be updated by deleting the expected exception code. Status and close any related bugs."; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test - public void testFactoryFromFile() throws Exception { + public void testFactoryFromFile() { // Remove thrown.* when bug 58779 is resolved // In the mean time, this function will modify SampleShow.pptx on disk. - thrown.expect(AssertionError.class); - // thrown.expectCause(Matcher); - thrown.expectMessage("SampleShow.pptx sample file was modified as a result of closing the slideshow"); - thrown.reportMissingExceptionWithMessage("Bug 58779: " + removeExpectedExceptionMsg); - - testFactoryFromFile(filename); + AssertionError ex = assertThrows( + "Bug 58779: " + removeExpectedExceptionMsg, + AssertionError.class, + () -> testFactoryFromFile(filename) + ); + assertTrue(ex.getMessage().contains("SampleShow.pptx sample file was modified as a result of closing the slideshow")); } @Test @@ -65,13 +64,14 @@ public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { } @Test - public void testFactoryFromNative() throws Exception { + public void testFactoryFromNative() { // Remove thrown.* when unit test for XSLF SlideShowFactory.create(OPCPackage) is implemented - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("Test not implemented"); - thrown.reportMissingExceptionWithMessage(removeExpectedExceptionMsg); - - testFactoryFromNative(filename); + UnsupportedOperationException ex = assertThrows( + removeExpectedExceptionMsg, + UnsupportedOperationException.class, + () -> testFactoryFromNative(filename) + ); + assertEquals("Test not implemented", ex.getMessage()); } @Test 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 15dcf326a0..8a3ffe433f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java @@ -20,6 +20,7 @@ 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 java.io.IOException; @@ -57,18 +58,16 @@ public final class TestSXSSFSheet extends BaseTestXSheet { */ @Override @Test - public void cloneSheet() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("Not Implemented"); - super.cloneSheet(); + public void cloneSheet() { + RuntimeException ex = assertThrows(RuntimeException.class, super::cloneSheet); + assertEquals("Not Implemented", ex.getMessage()); } @Override @Test - public void cloneSheetMultipleTimes() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("Not Implemented"); - super.cloneSheetMultipleTimes(); + public void cloneSheetMultipleTimes() { + RuntimeException ex = assertThrows(RuntimeException.class, super::cloneSheetMultipleTimes); + assertEquals("Not Implemented", ex.getMessage()); } /** @@ -76,10 +75,9 @@ public final class TestSXSSFSheet extends BaseTestXSheet { */ @Override @Test - public void shiftMerged() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("Not Implemented"); - super.shiftMerged(); + public void shiftMerged() { + RuntimeException ex = assertThrows(RuntimeException.class, super::shiftMerged); + assertEquals("Not Implemented", ex.getMessage()); } /** @@ -89,15 +87,14 @@ public final class TestSXSSFSheet extends BaseTestXSheet { */ @Override @Test - public void bug35084() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("Not Implemented"); - super.bug35084(); + public void bug35084() { + RuntimeException ex = assertThrows(RuntimeException.class, super::bug35084); + assertEquals("Not Implemented", ex.getMessage()); } @Override @Test - public void getCellComment() throws IOException { + public void getCellComment() { // TODO: reading cell comments via Sheet does not work currently as it tries // to access the underlying sheet for this, but comments are stored as // properties on Cells... @@ -119,9 +116,8 @@ public final class TestSXSSFSheet extends BaseTestXSheet { sheet.createRow(3); sheet.createRow(4); - thrown.expect(Throwable.class); - thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk."); - sheet.createRow(1); + Throwable ex = assertThrows(Throwable.class, () -> sheet.createRow(1)); + assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", ex.getMessage()); } } diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java index 91ee3a38a3..5c60d2d69b 100644 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java +++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java @@ -21,6 +21,7 @@ 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 java.io.ByteArrayInputStream; @@ -39,16 +40,11 @@ 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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public final class TestHMEFMessage { private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testCounts() throws Exception { HMEFMessage msg = openSample("quick-winmail.dat"); @@ -161,12 +157,13 @@ public final class TestHMEFMessage { } @Test - public void testInvalidMessage() throws Exception { + public void testInvalidMessage() { InputStream str = new ByteArrayInputStream(new byte[4]); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("TNEF signature not detected in file, expected 574529400 but got 0"); - new HMEFMessage(str); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> new HMEFMessage(str) + ); + assertEquals("TNEF signature not detected in file, expected 574529400 but got 0", ex.getMessage()); } @Test @@ -200,10 +197,11 @@ public final class TestHMEFMessage { LittleEndian.putUShort(90, out); InputStream str = new ByteArrayInputStream(out.toByteArray()); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unhandled level 90"); - new HMEFMessage(str); + IllegalStateException ex = assertThrows( + IllegalStateException.class, + () -> new HMEFMessage(str) + ); + assertEquals("Unhandled level 90", ex.getMessage()); } @Test 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 681cd46708..bdb5bba463 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java @@ -17,6 +17,7 @@ package org.apache.poi.hslf.dev; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import java.io.File; import java.io.PrintStream; @@ -36,9 +37,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.NullPrintStream; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -58,9 +57,6 @@ public abstract class BasePPTIteratingTest { ENCRYPTED_FILES.add("Password_Protected-hello.ppt"); } - @Rule - public ExpectedException thrown = ExpectedException.none(); - protected static final Map> EXCLUDED = new HashMap<>(); @@ -112,24 +108,29 @@ public abstract class BasePPTIteratingTest { @Test public void testAllFiles() throws Exception { String fileName = file.getName(); + Class t = null; if (EXCLUDED.containsKey(fileName)) { - thrown.expect(EXCLUDED.get(fileName)); + t = EXCLUDED.get(fileName); + } else if (getFailedOldFiles().contains(fileName)) { + t = OldPowerPointFormatException.class; + } else if (getFailedEncryptedFiles().contains(fileName)) { + t = EncryptedPowerPointFileException.class; } - try { + if (t == null) { runOneFile(file); - } catch (OldPowerPointFormatException e) { - // expected for some files - if(!OLD_FILES.contains(file.getName())) { - throw e; - } - } catch (EncryptedPowerPointFileException e) { - // expected for some files - if(!ENCRYPTED_FILES.contains(file.getName())) { - throw e; - } + } else { + assertThrows(t, () -> runOneFile(file)); } } abstract void runOneFile(File pFile) throws Exception; + + protected Set getFailedEncryptedFiles() { + return ENCRYPTED_FILES; + } + + protected Set getFailedOldFiles() { + return OLD_FILES; + } } 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 de2f7721c2..7ff2349fbd 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java @@ -16,13 +16,15 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import org.apache.poi.EmptyFileException; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import static org.junit.Assert.assertThrows; import java.io.File; +import java.util.Collections; +import java.util.Set; -import static org.junit.Assert.fail; +import org.apache.poi.EmptyFileException; +import org.apache.poi.hslf.HSLFTestDataSamples; +import org.junit.Test; public class TestPPTXMLDump extends BasePPTIteratingTest { @Test @@ -34,16 +36,21 @@ public class TestPPTXMLDump extends BasePPTIteratingTest { HSLFTestDataSamples.getSampleFile("pictures.ppt").getAbsolutePath() }); - try { - PPTXMLDump.main(new String[]{"invalidfile"}); - fail("Should catch exception here"); - } catch (EmptyFileException e) { - // expected here - } + assertThrows(EmptyFileException.class, () -> PPTXMLDump.main(new String[]{"invalidfile"})); } @Override void runOneFile(File pFile) throws Exception { PPTXMLDump.main(new String[]{pFile.getAbsolutePath()}); } + + @Override + protected Set getFailedEncryptedFiles() { + return Collections.emptySet(); + } + + @Override + protected Set getFailedOldFiles() { + return Collections.emptySet(); + } } 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 e749d7586d..9a6445e1e2 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java @@ -16,18 +16,19 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import org.apache.poi.EmptyFileException; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.util.IOUtils; -import org.junit.Test; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; +import java.util.Collections; import java.util.HashSet; import java.util.Set; -import static org.junit.Assert.fail; +import org.apache.poi.EmptyFileException; +import org.apache.poi.hslf.HSLFTestDataSamples; +import org.apache.poi.util.IOUtils; +import org.junit.Test; public class TestSlideShowDumper extends BasePPTIteratingTest { private static final Set FAILING = new HashSet<>(); @@ -39,8 +40,6 @@ public class TestSlideShowDumper extends BasePPTIteratingTest { @Test public void testMain() throws IOException { - SlideShowDumper.main(new String[0]); - // SlideShowDumper calls IOUtils.toByteArray(is), which would fail if a different size is defined IOUtils.setByteArrayMaxOverride(-1); @@ -76,4 +75,14 @@ public class TestSlideShowDumper extends BasePPTIteratingTest { } } } + + @Override + protected Set getFailedEncryptedFiles() { + return Collections.emptySet(); + } + + @Override + protected Set getFailedOldFiles() { + return Collections.emptySet(); + } } \ No newline at end of file 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 8158b5c547..dbab32a041 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java @@ -16,20 +16,18 @@ ==================================================================== */ package org.apache.poi.hslf.dev; -import org.apache.poi.EmptyFileException; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; +import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; -import static org.junit.Assert.fail; +import org.apache.poi.EmptyFileException; +import org.apache.poi.hslf.HSLFTestDataSamples; +import org.junit.Test; public class TestSlideShowRecordDumper extends BasePPTIteratingTest { @Test public void testMain() throws IOException { - SlideShowRecordDumper.main(new String[0]); - SlideShowRecordDumper.main(new String[] { HSLFTestDataSamples.getSampleFile("slide_master.ppt").getAbsolutePath(), }); diff --git a/src/testcases/org/apache/poi/POITestCase.java b/src/testcases/org/apache/poi/POITestCase.java index bda78bcf6d..7907012cfb 100644 --- a/src/testcases/org/apache/poi/POITestCase.java +++ b/src/testcases/org/apache/poi/POITestCase.java @@ -22,8 +22,8 @@ import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeNoException; diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java index a609ef7a26..688ea0088d 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java @@ -17,12 +17,12 @@ 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.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java index 262aafdb3b..823dc4418e 100644 --- a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java +++ b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java @@ -17,9 +17,9 @@ package org.apache.poi.hssf.dev; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import java.io.File; -import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -27,10 +27,7 @@ import java.util.Locale; import java.util.Map; import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; @@ -44,11 +41,7 @@ import org.junit.runners.Parameterized.Parameters; */ @RunWith(Parameterized.class) public abstract class BaseTestIteratingXLS { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - protected static final Map> EXCLUDED = - new HashMap<>(); + protected static final Map> EXCLUDED = new HashMap<>(); @Parameters(name="{index}: {0}") public static Iterable files() { @@ -80,20 +73,15 @@ public abstract class BaseTestIteratingXLS { @Test public void testMain() throws Exception { String fileName = file.getName(); - if (EXCLUDED.containsKey(fileName)) { - thrown.expect(EXCLUDED.get(fileName)); - } - - try { - runOneFile(file); - } catch (Exception e) { - // try to read it in HSSFWorkbook to quickly fail if we cannot read the file there at all and thus probably should use EXCLUDED instead - try (FileInputStream stream = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(stream)) { - assertNotNull(wb); - } - throw e; - } + Class t = EXCLUDED.get(fileName); + + if (t == null) { + runOneFile(file); + } else { + assertThrows(t, () -> runOneFile(file)); + } + } abstract void runOneFile(File pFile) throws Exception; diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java index 75adb444a4..f5cce1b268 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java @@ -22,26 +22,21 @@ import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.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.Ignore; -import org.junit.Test; public class TestBiffViewer extends BaseTestIteratingXLS { @BeforeClass public static void setup() { EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); + EXCLUDED.put("35897-type4.xls", IllegalArgumentException.class); // unsupported crypto api header + EXCLUDED.put("51832.xls", IllegalArgumentException.class); + EXCLUDED.put("xor-encryption-abc.xls", RecordFormatException.class); + EXCLUDED.put("password.xls", IllegalArgumentException.class); EXCLUDED.put("46904.xls", OldExcelFormatException.class); EXCLUDED.put("59074.xls", OldExcelFormatException.class); EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 @@ -50,11 +45,11 @@ public class TestBiffViewer extends BaseTestIteratingXLS { EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well + EXCLUDED.put("43493.xls", RecordFormatException.class); // HSSFWorkbook cannot open it as well // EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); EXCLUDED.put("50833.xls", IllegalArgumentException.class); // "Name is too long" when setting username EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - EXCLUDED.put("61300.xls", RecordFormatException.class); + EXCLUDED.put("61300.xls", IndexOutOfBoundsException.class); EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 } @@ -68,11 +63,11 @@ public class TestBiffViewer extends BaseTestIteratingXLS { } } - @Test - @Ignore("only used for manual tests") - @SuppressWarnings("java:S2699") - public void testOneFile() throws Exception { - POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - runOneFile(samples.getFile("43493.xls")); - } +// @Test +// @Ignore("only used for manual tests") +// @SuppressWarnings("java:S2699") +// public void testOneFile() throws Exception { +// POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); +// runOneFile(samples.getFile("43493.xls")); +// } } diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java index d92239bbfe..c0ef0fd7dc 100644 --- a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java +++ b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java @@ -18,16 +18,12 @@ package org.apache.poi.hssf.model; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import org.apache.poi.hssf.record.ColumnInfoRecord; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public final class TestSheetAdditional { - @Rule - public ExpectedException thrown= ExpectedException.none(); - @Test public void testGetCellWidth() { InternalSheet sheet = InternalSheet.createSheet(); @@ -65,8 +61,10 @@ public final class TestSheetAdditional { sheet.setColumnWidth(0, 255*256); // over the limit - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("The maximum column width for an individual cell is 255 characters."); - sheet.setColumnWidth(0, 256*256); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.setColumnWidth(0, 256*256) + ); + assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage()); } } diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java index a716717ad9..757da3c9ca 100644 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java +++ b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java @@ -19,16 +19,15 @@ 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 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.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Tests for {@link RecordFactoryInputStream} @@ -57,10 +56,7 @@ public final class TestRecordFactoryInputStream { private static final String SAMPLE_WINDOW1 = "3D 00 12 00" + "00 00 00 00 40 38 55 23 38 00 00 00 00 00 01 00 58 02"; - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - /** * Makes sure that a default password mismatch condition is represented with {@link EncryptedDocumentException} */ @@ -76,11 +72,13 @@ public final class TestRecordFactoryInputStream { + SAMPLE_WINDOW1_ENCR1 ); - expectedEx.expect(EncryptedDocumentException.class); - expectedEx.expectMessage("Default password is invalid for salt/verifier/verifierHash"); - createRFIS(dataWrongDefault); + EncryptedDocumentException ex = assertThrows( + EncryptedDocumentException.class, + () -> createRFIS(dataWrongDefault) + ); + assertTrue(ex.getMessage().contains("Default password is invalid for salt/verifier/verifierHash")); } - + @Test public void defaultPasswordOK() { // This encodng depends on docId, password and stream position @@ -96,7 +94,7 @@ public final class TestRecordFactoryInputStream { RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault); confirmReadInitialRecords(rfis); } - + /** * Makes sure that an incorrect user supplied password condition is represented with {@link EncryptedDocumentException} @@ -113,12 +111,13 @@ public final class TestRecordFactoryInputStream { + SAMPLE_WINDOW1_ENCR2 ); - expectedEx.expect(EncryptedDocumentException.class); - expectedEx.expectMessage("Supplied password is invalid for salt/verifier/verifierHash"); - Biff8EncryptionKey.setCurrentUserPassword("passw0rd"); try { - createRFIS(dataWrongDefault); + EncryptedDocumentException ex = assertThrows( + EncryptedDocumentException.class, + () -> createRFIS(dataWrongDefault) + ); + assertEquals("Supplied password is invalid for salt/verifier/verifierHash", ex.getMessage()); } finally { Biff8EncryptionKey.setCurrentUserPassword(null); } @@ -144,8 +143,8 @@ public final class TestRecordFactoryInputStream { Biff8EncryptionKey.setCurrentUserPassword(null); } } - - + + /** * makes sure the record stream starts with {@link BOFRecord}, {@link FilePassRecord} and then {@link WindowOneRecord} * The third record is decrypted so this method also checks its content. 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 1862efeb6a..2f4217400b 100644 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java +++ b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java @@ -21,6 +21,7 @@ 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 java.util.ArrayList; @@ -54,20 +55,14 @@ 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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Tess for {@link PageSettingsBlock} */ public final class TestPageSettingsBlock { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testPrintSetup_bug46548() { - // PageSettingBlock in this file contains PLS (sid=x004D) record // followed by ContinueRecord (sid=x003C) HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex46548-23133.xls"); @@ -202,14 +197,16 @@ public final class TestPageSettingsBlock { public void testDuplicatePSBRecord_bug47199() { // Hypothetical setup of PSB records which should cause POI to crash org.apache.poi.hssf.record.Record[] recs = { - new HeaderRecord("&LSales Figures"), - new HeaderRecord("&LInventory"), + new HeaderRecord("&LSales Figures"), + new HeaderRecord("&LInventory"), }; RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - thrown.expectMessage("Duplicate PageSettingsBlock record (sid=0x14)"); - thrown.expect(RecordFormatException.class); - new PageSettingsBlock(rs); + RecordFormatException ex = assertThrows( + RecordFormatException.class, + () -> new PageSettingsBlock(rs) + ); + assertEquals("Duplicate PageSettingsBlock record (sid=0x14)", ex.getMessage()); } /** diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java index 7d7650de25..446d9b1d0e 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java @@ -92,9 +92,7 @@ import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Ignore; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Testcases for bugs entered in bugzilla @@ -105,9 +103,6 @@ import org.junit.rules.ExpectedException; */ public final class TestBugs extends BaseTestBugzillaIssues { - @Rule - public ExpectedException thrown = ExpectedException.none(); - public TestBugs() { super(HSSFITestDataProvider.instance); } @@ -923,7 +918,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { @Test public void bug45338() throws IOException { try (HSSFWorkbook wb = new HSSFWorkbook()) { - assertEquals(4, wb.getNumberOfFontsAsInt()); + assertEquals(4, wb.getNumberOfFonts()); HSSFSheet s = wb.createSheet(); s.createRow(0); @@ -931,7 +926,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { s.getRow(0).createCell(0); s.getRow(1).createCell(0); - assertEquals(4, wb.getNumberOfFontsAsInt()); + assertEquals(4, wb.getNumberOfFonts()); HSSFFont f1 = wb.getFontAt(0); assertFalse(f1.getBold()); @@ -947,7 +942,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { assertNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2)); HSSFFont nf = wb.createFont(); - assertEquals(5, wb.getNumberOfFontsAsInt()); + assertEquals(5, wb.getNumberOfFonts()); assertEquals(5, nf.getIndex()); assertEquals(nf, wb.getFontAt(5)); @@ -961,7 +956,7 @@ public final class TestBugs extends BaseTestBugzillaIssues { nf.setTypeOffset((short) 2); nf.setUnderline((byte) 2); - assertEquals(5, wb.getNumberOfFontsAsInt()); + assertEquals(5, wb.getNumberOfFonts()); assertEquals(nf, wb.getFontAt(5)); // Find it now @@ -1480,10 +1475,12 @@ public final class TestBugs extends BaseTestBugzillaIssues { * (is an excel 95 file though) */ @Test - public void bug46904a() throws Exception { - thrown.expect(OldExcelFormatException.class); - thrown.expectMessage("The supplied spreadsheet seems to be Excel"); - simpleTest("46904.xls"); + public void bug46904a() { + OldExcelFormatException ex = assertThrows( + OldExcelFormatException.class, + () -> simpleTest("46904.xls") + ); + assertTrue(ex.getMessage().contains("The supplied spreadsheet seems to be Excel")); } /** @@ -2735,8 +2732,8 @@ public final class TestBugs extends BaseTestBugzillaIssues { assertEquals(CellType.BLANK, cell.getCellType()); assertEquals("", cell.getStringCellValue()); - thrown.expect(IllegalStateException.class); - assertNull(cell.getCellFormula()); + + assertThrows(IllegalStateException.class, cell::getCellFormula); } } @@ -2835,9 +2832,11 @@ public final class TestBugs extends BaseTestBugzillaIssues { DocumentEntry entry = (DocumentEntry) poifs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - thrown.expect(RuntimeException.class); - thrown.expectMessage("Can't read negative number of bytes"); - new PropertySet(new DocumentInputStream(entry)); + RuntimeException ex = assertThrows( + RuntimeException.class, + () -> new PropertySet(new DocumentInputStream(entry)) + ); + assertEquals("Can't read negative number of bytes", ex.getMessage()); } } diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java index 821a14b9ef..09906b8e27 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java @@ -18,15 +18,7 @@ package org.apache.poi.hssf.usermodel; import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; -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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; @@ -1042,9 +1034,11 @@ public final class TestHSSFSheet extends BaseTestSheet { Sheet sheet = wb.createSheet(); sheet.showInPane(2, 3); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Maximum row number is 65535"); - sheet.showInPane(Integer.MAX_VALUE, 3); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.showInPane(Integer.MAX_VALUE, 3) + ); + assertEquals("Maximum row number is 65535", ex.getMessage()); } } diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java index 583ef24f50..91894113bd 100644 --- a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java +++ b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java @@ -17,9 +17,9 @@ 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.Assert.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -37,9 +37,9 @@ import org.junit.Ignore; import org.junit.Test; public class TestXorEncryption { - + private static final HSSFTestDataSamples samples = new HSSFTestDataSamples(); - + @Test public void testXorEncryption() { // Xor-Password: abc diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java index 4e235b66c7..1b154bd89d 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java @@ -20,6 +20,8 @@ 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 java.io.ByteArrayInputStream; import java.io.File; @@ -27,9 +29,7 @@ import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Class to test that POIFS complains when given an Office 2003 XML @@ -37,32 +37,23 @@ import org.junit.rules.ExpectedException; */ public class TestOfficeXMLException { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static InputStream openSampleStream(String sampleFileName) { return HSSFTestDataSamples.openSampleFileStream(sampleFileName); } @Test public void testOOXMLException() throws IOException { - thrown.expect(OfficeXmlFileException.class); - thrown.expectMessage("You are calling the part of POI that deals with OLE2 Office Documents"); - - try (InputStream in = openSampleStream("sample.xlsx"); - POIFSFileSystem fs = new POIFSFileSystem(in)) { - + try (InputStream in = openSampleStream("sample.xlsx")) { + OfficeXmlFileException ex = assertThrows(OfficeXmlFileException.class, () -> new POIFSFileSystem(in)); + assertTrue(ex.getMessage().contains("You are calling the part of POI that deals with OLE2 Office Documents")); } } @Test public void test2003XMLException() throws IOException { - thrown.expect(NotOLE2FileException.class); - thrown.expectMessage("The supplied data appears to be a raw XML file"); - - try (InputStream in = openSampleStream("SampleSS.xml"); - POIFSFileSystem fs = new POIFSFileSystem(in)) { + try (InputStream in = openSampleStream("SampleSS.xml")) { + NotOLE2FileException ex = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in)); + assertTrue(ex.getMessage().contains("The supplied data appears to be a raw XML file")); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java index 4de08c4c5c..2a235d3940 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java @@ -17,9 +17,11 @@ 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.assertThat; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.File; @@ -32,16 +34,11 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class TestOle10Native { private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testOleNative() throws IOException, Ole10NativeException { POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("oleObject1.bin")); @@ -101,11 +98,14 @@ public class TestOle10Native { } @Test - public void testOleNativeOOM() throws IOException, Ole10NativeException { - POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin")); - thrown.expect(RecordFormatException.class); - thrown.expectMessage("Tried to allocate"); - Ole10Native.createFromEmbeddedOleObject(fs); + public void testOleNativeOOM() throws IOException { + try (POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin"))) { + RecordFormatException ex = assertThrows( + RecordFormatException.class, + () -> Ole10Native.createFromEmbeddedOleObject(fs) + ); + assertTrue(ex.getMessage().contains("Tried to allocate")); + } } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java index 5153cb37e1..9860935c12 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java @@ -19,12 +19,12 @@ 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 java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; @@ -42,9 +42,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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Tests for the older OPOIFS-based POIFSFileSystem @@ -166,9 +164,6 @@ public final class TestPOIFSFileSystem { } } - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - /** * Check that we do the right thing when the list of which * sectors are BAT blocks points off the list of @@ -176,12 +171,13 @@ public final class TestPOIFSFileSystem { */ @Test public void testFATandDIFATsectors() throws Exception { - // Open the file up - expectedEx.expect(IndexOutOfBoundsException.class); - expectedEx.expectMessage("Block 1148 not found"); try (InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")) { - new POIFSFileSystem(stream); - fail("File is corrupt and shouldn't have been opened"); + IndexOutOfBoundsException ex = assertThrows( + "File is corrupt and shouldn't have been opened", + IndexOutOfBoundsException.class, + () -> new POIFSFileSystem(stream) + ); + assertTrue(ex.getMessage().contains("Block 1148 not found")); } } diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java index c6a0a6a77b..af313172a7 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java @@ -17,13 +17,13 @@ package org.apache.poi.poifs.filesystem; -import static org.hamcrest.core.IsCollectionContaining.hasItem; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; 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.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java b/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java index 9f7a21a0df..7faedd8c03 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java +++ b/src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java @@ -20,6 +20,8 @@ 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 java.io.IOException; @@ -37,9 +39,7 @@ import org.apache.poi.ss.usermodel.CellValue; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -67,14 +67,10 @@ public class TestFunctionRegistry { fe = null; } - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test + @Test(expected = NotImplementedException.class) public void testRegisterInRuntimeA() { HSSFCell cellA = row.createCell(0); cellA.setCellFormula("FISHER(A5)"); - thrown.expect(NotImplementedException.class); fe.evaluate(cellA); } @@ -87,11 +83,10 @@ public class TestFunctionRegistry { assertEquals(ErrorEval.NA.getErrorCode(), cv.getErrorValue()); } - @Test + @Test(expected = NotImplementedException.class) public void testRegisterInRuntimeC() { HSSFCell cellB = row.createCell(1); cellB.setCellFormula("CUBEMEMBERPROPERTY(A5)"); - thrown.expect(NotImplementedException.class); fe.evaluate(cellB); } @@ -112,24 +107,31 @@ public class TestFunctionRegistry { @Test public void testExceptionsA() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("POI already implememts SUM. You cannot override POI's implementations of Excel functions"); - FunctionEval.registerFunction("SUM", TestFunctionRegistry::na); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> FunctionEval.registerFunction("SUM", TestFunctionRegistry::na) + ); + assertEquals("POI already implements SUM. You cannot override POI's implementations of Excel functions", ex.getMessage()); } @Test public void testExceptionsB() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unknown function: SUMXXX"); - FunctionEval.registerFunction("SUMXXX", TestFunctionRegistry::na); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> FunctionEval.registerFunction("SUMXXX", TestFunctionRegistry::na) + ); + assertTrue(ex.getMessage().contains("Unknown function: SUMXXX")); } @Test public void testExceptionsC() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ISODD is a function from the Excel Analysis Toolpack. " + - "Use AnalysisToolpack.registerFunction(String name, FreeRefFunction func) instead."); - FunctionEval.registerFunction("ISODD", TestFunctionRegistry::na); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> FunctionEval.registerFunction("ISODD", TestFunctionRegistry::na) + ); + assertEquals("ISODD is a function from the Excel Analysis Toolpack. " + + "Use AnalysisToolpack.registerFunction(String name, FreeRefFunction func) instead.", + ex.getMessage()); } private static ValueEval atpFunc(ValueEval[] args, OperationEvaluationContext ec) { @@ -138,23 +140,30 @@ public class TestFunctionRegistry { @Test public void testExceptionsD() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("POI already implememts ISODD. You cannot override POI's implementations of Excel functions"); - AnalysisToolPak.registerFunction("ISODD", TestFunctionRegistry::atpFunc); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> AnalysisToolPak.registerFunction("ISODD", TestFunctionRegistry::atpFunc) + ); + assertEquals("POI already implements ISODD. You cannot override POI's implementations of Excel functions", ex.getMessage()); } @Test public void testExceptionsE() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ISODDXXX is not a function from the Excel Analysis Toolpack."); - AnalysisToolPak.registerFunction("ISODDXXX", TestFunctionRegistry::atpFunc); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> AnalysisToolPak.registerFunction("ISODDXXX", TestFunctionRegistry::atpFunc) + ); + assertEquals("ISODDXXX is not a function from the Excel Analysis Toolpack.", ex.getMessage()); } @Test public void testExceptionsF() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("SUM is a built-in Excel function. " + - "Use FunctoinEval.registerFunction(String name, Function func) instead."); - AnalysisToolPak.registerFunction("SUM", TestFunctionRegistry::atpFunc); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> AnalysisToolPak.registerFunction("SUM", TestFunctionRegistry::atpFunc) + ); + assertEquals("SUM is a built-in Excel function. " + + "Use FunctoinEval.registerFunction(String name, Function func) instead.", + ex.getMessage()); } } diff --git a/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java b/src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java index 578452fe50..70745ef979 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 @@ -19,6 +19,7 @@ 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 java.io.IOException; @@ -28,15 +29,10 @@ 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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class BaseTestForkedEvaluator { - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - protected Workbook newWorkbook() { return new HSSFWorkbook(); } @@ -66,34 +62,33 @@ public class BaseTestForkedEvaluator { */ @Test public void testBasic() throws IOException { - Workbook wb = createWorkbook(); - - // The stability classifier is useful to reduce memory consumption of caching logic - IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1; + try (Workbook wb = createWorkbook()) { - ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null); - ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null); + // The stability classifier is useful to reduce memory consumption of caching logic + IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1; - // fe1 and fe2 can be used concurrently on separate threads + ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null); + ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null); - fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0)); - fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1)); + // fe1 and fe2 can be used concurrently on separate threads - fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2)); - fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0)); + fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0)); + fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1)); - NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); - assertNotNull(eval1); - assertEquals(18.9, eval1.getNumberValue(), 0.0); - NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0); - assertNotNull(eval2); - assertEquals(4.0, eval2.getNumberValue(), 0.0); - fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0)); - eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); - assertNotNull(eval1); - assertEquals(13.9, eval1.getNumberValue(), 0.0); + fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2)); + fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0)); - wb.close(); + NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); + assertNotNull(eval1); + assertEquals(18.9, eval1.getNumberValue(), 0.0); + NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0); + assertNotNull(eval2); + assertEquals(4.0, eval2.getNumberValue(), 0.0); + fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0)); + eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0); + assertNotNull(eval1); + assertEquals(13.9, eval1.getNumberValue(), 0.0); + } } /** @@ -108,13 +103,15 @@ public class BaseTestForkedEvaluator { */ @Test public void testMissingInputCellH() throws IOException { - expectedEx.expect(UnsupportedOperationException.class); - expectedEx.expectMessage("Underlying cell 'A2' is missing in master sheet."); try (Workbook wb = createWorkbook()) { ForkedEvaluator fe = ForkedEvaluator.create(wb, null, null); // attempt update input at cell A2 (which is missing) - fe.updateCell("Inputs", 1, 0, new NumberEval(4.0)); + UnsupportedOperationException ex = assertThrows( + UnsupportedOperationException.class, + () -> fe.updateCell("Inputs", 1, 0, new NumberEval(4.0)) + ); + assertEquals("Underlying cell 'A2' is missing in master sheet.", ex.getMessage()); } } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java index 1264a15ca9..4579cefadd 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java @@ -1014,21 +1014,21 @@ public abstract class BaseTestBugzillaIssues { try (Workbook wb = _testDataProvider.createWorkbook()) { int startingFonts = wb instanceof HSSFWorkbook ? 4 : 1; - assertEquals(startingFonts, wb.getNumberOfFontsAsInt()); + assertEquals(startingFonts, wb.getNumberOfFonts()); // Get a font, and slightly change it Font a = wb.createFont(); - assertEquals(startingFonts + 1, wb.getNumberOfFontsAsInt()); + assertEquals(startingFonts + 1, wb.getNumberOfFonts()); a.setFontHeightInPoints((short) 23); - assertEquals(startingFonts + 1, wb.getNumberOfFontsAsInt()); + assertEquals(startingFonts + 1, wb.getNumberOfFonts()); // Get two more, unchanged /*Font b =*/ wb.createFont(); - assertEquals(startingFonts + 2, wb.getNumberOfFontsAsInt()); + assertEquals(startingFonts + 2, wb.getNumberOfFonts()); /*Font c =*/ wb.createFont(); - assertEquals(startingFonts + 3, wb.getNumberOfFontsAsInt()); + assertEquals(startingFonts + 3, wb.getNumberOfFonts()); } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java index 89594af0f9..30d80a73c7 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java @@ -17,7 +17,13 @@ package org.apache.poi.ss.usermodel; -import static org.junit.Assert.*; +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 java.io.IOException; @@ -58,7 +64,7 @@ public abstract class BaseTestFont { @Test public final void testGetNumberOfFonts() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); - int num0 = wb.getNumberOfFontsAsInt(); + int num0 = wb.getNumberOfFonts(); Font f1=wb.createFont(); f1.setBold(true); @@ -103,7 +109,7 @@ public abstract class BaseTestFont { font.setFontName("Courier"); int font1Idx = font.getIndexAsInt(); wb1.createCellStyle().setFont(font); - assertEquals(num0 + 1, wb1.getNumberOfFontsAsInt()); + assertEquals(num0 + 1, wb1.getNumberOfFonts()); CellStyle cellStyleTitle=wb1.createCellStyle(); cellStyleTitle.setFont(font); @@ -114,7 +120,7 @@ public abstract class BaseTestFont { wb1.close(); s1 = wb2.getSheetAt(0); - assertEquals(num0 + 1, wb2.getNumberOfFontsAsInt()); + assertEquals(num0 + 1, wb2.getNumberOfFonts()); int idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndexAsInt(); Font fnt = wb2.getFontAt(idx); assertNotNull(fnt); @@ -127,7 +133,7 @@ public abstract class BaseTestFont { font2.setFontHeightInPoints((short)15); int font2Idx = font2.getIndexAsInt(); wb2.createCellStyle().setFont(font2); - assertEquals(num0 + 2, wb2.getNumberOfFontsAsInt()); + assertEquals(num0 + 2, wb2.getNumberOfFonts()); // Save and re-load Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); @@ -135,7 +141,7 @@ public abstract class BaseTestFont { s1 = wb3.getSheetAt(0); assertNotNull(s1); - assertEquals(num0 + 2, wb3.getNumberOfFontsAsInt()); + assertEquals(num0 + 2, wb3.getNumberOfFonts()); assertNotNull(wb3.getFontAt(font1Idx)); assertNotNull(wb3.getFontAt(font2Idx)); @@ -150,7 +156,7 @@ public abstract class BaseTestFont { @Test public final void test45338() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); - int num0 = wb.getNumberOfFontsAsInt(); + int num0 = wb.getNumberOfFonts(); Sheet s = wb.createSheet(); s.createRow(0); @@ -178,7 +184,7 @@ public abstract class BaseTestFont { Font nf = wb.createFont(); int nfIdx = nf.getIndexAsInt(); - assertEquals(num0 + 1, wb.getNumberOfFontsAsInt()); + assertEquals(num0 + 1, wb.getNumberOfFonts()); assertSame(nf, wb.getFontAt(nfIdx)); @@ -191,7 +197,7 @@ public abstract class BaseTestFont { nf.setTypeOffset((short)2); nf.setUnderline((byte)2); - assertEquals(num0 + 1, wb.getNumberOfFontsAsInt()); + assertEquals(num0 + 1, wb.getNumberOfFonts()); assertEquals(nf, wb.getFontAt(nfIdx)); assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx)); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java index 02930a9959..2af3022617 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java @@ -17,23 +17,34 @@ 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 java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.PaneInformation; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; - -import static org.apache.poi.POITestCase.assertBetween; -import static org.junit.Assert.*; -import static org.junit.Assume.assumeTrue; /** * Common superclass for testing {@link org.apache.poi.hssf.usermodel.HSSFCell}, @@ -43,160 +54,150 @@ import static org.junit.Assume.assumeTrue; public abstract class BaseTestSheet { private static final int ROW_COUNT = 40000; - @Rule - public ExpectedException thrown = ExpectedException.none(); - protected final ITestDataProvider _testDataProvider; protected BaseTestSheet(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } - + protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { // do nothing for Sheet base class. This will be overridden for SXSSFSheets. } @Test public void createRow() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertEquals(0, sheet.getPhysicalNumberOfRows()); - - //Test that we get null for undefined rownumber - assertNull(sheet.getRow(1)); - - // Test row creation with consecutive indexes - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - assertEquals(0, row1.getRowNum()); - assertEquals(1, row2.getRowNum()); - Iterator it = sheet.rowIterator(); - assertTrue(it.hasNext()); - assertSame(row1, it.next()); - assertTrue(it.hasNext()); - assertSame(row2, it.next()); - assertEquals(1, sheet.getLastRowNum()); - - // Test row creation with non consecutive index - Row row101 = sheet.createRow(100); - assertNotNull(row101); - assertEquals(100, sheet.getLastRowNum()); - assertEquals(3, sheet.getPhysicalNumberOfRows()); - - // Test overwriting an existing row - Row row2_ovrewritten = sheet.createRow(1); - Cell cell = row2_ovrewritten.createCell(0); - cell.setCellValue(100); - Iterator it2 = sheet.rowIterator(); - assertTrue(it2.hasNext()); - assertSame(row1, it2.next()); - assertTrue(it2.hasNext()); - Row row2_ovrewritten_ref = it2.next(); - assertSame(row2_ovrewritten, row2_ovrewritten_ref); - assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + assertEquals(0, sheet.getPhysicalNumberOfRows()); + + //Test that we get null for undefined rownumber + assertNull(sheet.getRow(1)); + + // Test row creation with consecutive indexes + Row row1 = sheet.createRow(0); + Row row2 = sheet.createRow(1); + assertEquals(0, row1.getRowNum()); + assertEquals(1, row2.getRowNum()); + Iterator it = sheet.rowIterator(); + assertTrue(it.hasNext()); + assertSame(row1, it.next()); + assertTrue(it.hasNext()); + assertSame(row2, it.next()); + assertEquals(1, sheet.getLastRowNum()); + + // Test row creation with non consecutive index + Row row101 = sheet.createRow(100); + assertNotNull(row101); + assertEquals(100, sheet.getLastRowNum()); + assertEquals(3, sheet.getPhysicalNumberOfRows()); + + // Test overwriting an existing row + Row row2_ovrewritten = sheet.createRow(1); + Cell cell = row2_ovrewritten.createCell(0); + cell.setCellValue(100); + Iterator it2 = sheet.rowIterator(); + assertTrue(it2.hasNext()); + assertSame(row1, it2.next()); + assertTrue(it2.hasNext()); + Row row2_ovrewritten_ref = it2.next(); + assertSame(row2_ovrewritten, row2_ovrewritten_ref); + assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0); + } } - + @Test(expected=IllegalArgumentException.class) public void createRowBeforeFirstRow() throws IOException { - final Workbook workbook = _testDataProvider.createWorkbook(); - final Sheet sh = workbook.createSheet(); - sh.createRow(0); - try { + try (Workbook workbook = _testDataProvider.createWorkbook()) { + final Sheet sh = workbook.createSheet(); + sh.createRow(0); // Negative rows not allowed sh.createRow(-1); - } finally { - workbook.close(); } } - + @Test(expected=IllegalArgumentException.class) public void createRowAfterLastRow() throws IOException { final SpreadsheetVersion version = _testDataProvider.getSpreadsheetVersion(); - final Workbook workbook = _testDataProvider.createWorkbook(); - final Sheet sh = workbook.createSheet(); - sh.createRow(version.getLastRowIndex()); - try { + 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); - } finally { - workbook.close(); } } @Test public void removeRow() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet1 = workbook.createSheet(); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(-1, sheet1.getFirstRowNum()); - assertEquals(-1, sheet1.getLastRowNum()); - - Row row0 = sheet1.createRow(0); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(0, sheet1.getFirstRowNum()); - assertEquals(0, sheet1.getLastRowNum()); - sheet1.removeRow(row0); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(-1, sheet1.getFirstRowNum()); - assertEquals(-1, sheet1.getLastRowNum()); - - sheet1.createRow(1); - Row row2 = sheet1.createRow(2); - assertEquals(2, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(2, sheet1.getLastRowNum()); - - assertNotNull(sheet1.getRow(1)); - assertNotNull(sheet1.getRow(2)); - sheet1.removeRow(row2); - assertNotNull(sheet1.getRow(1)); - assertNull(sheet1.getRow(2)); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(1, sheet1.getLastRowNum()); - - Row row3 = sheet1.createRow(3); - Sheet sheet2 = workbook.createSheet(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Specified row does not belong to this sheet"); - sheet2.removeRow(row3); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet1 = workbook.createSheet(); + assertEquals(0, sheet1.getPhysicalNumberOfRows()); + assertEquals(-1, sheet1.getFirstRowNum()); + assertEquals(-1, sheet1.getLastRowNum()); + + Row row0 = sheet1.createRow(0); + assertEquals(1, sheet1.getPhysicalNumberOfRows()); + assertEquals(0, sheet1.getFirstRowNum()); + assertEquals(0, sheet1.getLastRowNum()); + sheet1.removeRow(row0); + assertEquals(0, sheet1.getPhysicalNumberOfRows()); + assertEquals(-1, sheet1.getFirstRowNum()); + assertEquals(-1, sheet1.getLastRowNum()); + + sheet1.createRow(1); + Row row2 = sheet1.createRow(2); + assertEquals(2, sheet1.getPhysicalNumberOfRows()); + assertEquals(1, sheet1.getFirstRowNum()); + assertEquals(2, sheet1.getLastRowNum()); + + assertNotNull(sheet1.getRow(1)); + assertNotNull(sheet1.getRow(2)); + sheet1.removeRow(row2); + assertNotNull(sheet1.getRow(1)); + assertNull(sheet1.getRow(2)); + assertEquals(1, sheet1.getPhysicalNumberOfRows()); + assertEquals(1, sheet1.getFirstRowNum()); + assertEquals(1, sheet1.getLastRowNum()); + + Row row3 = sheet1.createRow(3); + Sheet sheet2 = workbook.createSheet(); + + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet2.removeRow(row3) + ); + assertEquals("Specified row does not belong to this sheet", ex.getMessage()); + } } @Test public void cloneSheet() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - Cell cell2 = row.createCell(1); - cell.setCellValue(factory.createRichTextString("clone_test")); - cell2.setCellFormula("SIN(1)"); - - Sheet clonedSheet = workbook.cloneSheet(0); - Row clonedRow = clonedSheet.getRow(0); - - //Check for a good clone - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - - //Check that the cells are not somehow linked - cell.setCellValue(factory.createRichTextString("Difference Check")); - cell2.setCellFormula("cos(2)"); - 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"); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + CreationHelper factory = workbook.getCreationHelper(); + Sheet sheet = workbook.createSheet("Test Clone"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + Cell cell2 = row.createCell(1); + cell.setCellValue(factory.createRichTextString("clone_test")); + cell2.setCellFormula("SIN(1)"); + + Sheet clonedSheet = workbook.cloneSheet(0); + Row clonedRow = clonedSheet.getRow(0); + + //Check for a good clone + assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); + + //Check that the cells are not somehow linked + cell.setCellValue(factory.createRichTextString("Difference Check")); + cell2.setCellFormula("cos(2)"); + 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"); + } + assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); + assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)"); } - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)"); - - workbook.close(); } /** tests that the sheet name for multiple clones of the same sheet is unique @@ -204,29 +205,28 @@ public abstract class BaseTestSheet { */ @Test public void cloneSheetMultipleTimes() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("clone_test")); - //Clone the sheet multiple times - workbook.cloneSheet(0); - workbook.cloneSheet(0); - - assertNotNull(workbook.getSheet("Test Clone")); - assertNotNull(workbook.getSheet("Test Clone (2)")); - assertEquals("Test Clone (3)", workbook.getSheetName(2)); - assertNotNull(workbook.getSheet("Test Clone (3)")); - - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.createSheet("abc ( 123)"); - workbook.cloneSheet(0); - assertEquals("abc (124)", workbook.getSheetName(1)); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + CreationHelper factory = workbook.getCreationHelper(); + Sheet sheet = workbook.createSheet("Test Clone"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + cell.setCellValue(factory.createRichTextString("clone_test")); + //Clone the sheet multiple times + workbook.cloneSheet(0); + workbook.cloneSheet(0); + + assertNotNull(workbook.getSheet("Test Clone")); + assertNotNull(workbook.getSheet("Test Clone (2)")); + assertEquals("Test Clone (3)", workbook.getSheetName(2)); + assertNotNull(workbook.getSheet("Test Clone (3)")); + + workbook.removeSheetAt(0); + workbook.removeSheetAt(0); + workbook.removeSheetAt(0); + workbook.createSheet("abc ( 123)"); + workbook.cloneSheet(0); + assertEquals("abc (124)", workbook.getSheetName(1)); + } } /** @@ -234,91 +234,86 @@ public abstract class BaseTestSheet { */ @Test public void printSetupLandscapeNew() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheetL = wb1.createSheet("LandscapeS"); - Sheet sheetP = wb1.createSheet("LandscapeP"); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(1, sheetP.getPrintSetup().getCopies()); - - // Change one on each - sheetL.getPrintSetup().setLandscape(true); - sheetP.getPrintSetup().setCopies((short)3); - - // Check taken - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheetL = wb2.getSheet("LandscapeS"); - sheetP = wb2.getSheet("LandscapeP"); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - wb2.close(); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheetL = wb1.createSheet("LandscapeS"); + Sheet sheetP = wb1.createSheet("LandscapeP"); + + // Check two aspects of the print setup + assertFalse(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(1, sheetP.getPrintSetup().getCopies()); + + // Change one on each + sheetL.getPrintSetup().setLandscape(true); + sheetP.getPrintSetup().setCopies((short) 3); + + // Check taken + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetP.getPrintSetup().getCopies()); + + // Save and re-load, and check still there + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + sheetL = wb2.getSheet("LandscapeS"); + sheetP = wb2.getSheet("LandscapeP"); + + assertTrue(sheetL.getPrintSetup().getLandscape()); + assertFalse(sheetP.getPrintSetup().getLandscape()); + assertEquals(1, sheetL.getPrintSetup().getCopies()); + assertEquals(3, sheetP.getPrintSetup().getCopies()); + } + } } - + /** * Disallow creating wholly or partially overlapping merged regions * as this results in a corrupted workbook */ @Test public void addOverlappingMergedRegions() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet(); - - final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - assertEquals(0, sheet.addMergedRegion(baseRegion)); - - try { + try (final Workbook wb = _testDataProvider.createWorkbook()) { + final Sheet sheet = wb.createSheet(); + + final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 + assertEquals(0, sheet.addMergedRegion(baseRegion)); + final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - sheet.addMergedRegion(duplicateRegion); - fail("Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " + - "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { + 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) + ); + final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3 - sheet.addMergedRegion(partiallyOverlappingRegion); - fail("Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " + - "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { + 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) + ); + final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2 - sheet.addMergedRegion(subsetRegion); - fail("Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " + - "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { + 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) + ); + final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); //A1:C3 - sheet.addMergedRegion(supersetRegion); - fail("Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " + - "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here + 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) + ); + + final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); + assertEquals(1, sheet.addMergedRegion(disjointRegion)); } - - final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); - assertEquals(1, sheet.addMergedRegion(disjointRegion)); - - wb.close(); } /* @@ -326,17 +321,16 @@ public abstract class BaseTestSheet { */ @Test public void addMergedRegionWithSingleCellShouldFail() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - - final Sheet sheet = wb.createSheet(); - final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1"); - try { - sheet.addMergedRegion(region); - fail("Should not be able to add a single-cell merged region (" + region.formatAsString() + ")"); - } catch (final IllegalArgumentException e) { - // expected + try (Workbook wb = _testDataProvider.createWorkbook()) { + + 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) + ); } - wb.close(); } /** @@ -346,39 +340,35 @@ public abstract class BaseTestSheet { */ @Test public void addMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertEquals(0, sheet.getNumMergedRegions()); - SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion(); - - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals(1, sheet.getNumMergedRegions()); - - try { - region = new CellRangeAddress(-1, -1, -1, -1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - // TODO: assertEquals("Minimum row number is 0.", e.getMessage()); - } - try { - region = new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), e.getMessage()); - } - try { - region = new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), e.getMessage()); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + assertEquals(0, sheet.getNumMergedRegions()); + SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion(); + + CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); + assertEquals(0, sheet.addMergedRegion(region)); + assertEquals(1, sheet.getNumMergedRegions()); + + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.addMergedRegion(new CellRangeAddress(-1, -1, -1, -1)) + ); + assertEquals("Merged region : must contain 2 or more cells", ex.getMessage()); + + ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1)) + ); + assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), ex.getMessage()); + + ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.addMergedRegion(new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1)) + ); + assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), ex.getMessage()); + + assertEquals(1, sheet.getNumMergedRegions()); } - assertEquals(1, sheet.getNumMergedRegions()); - - wb.close(); } /** @@ -387,65 +377,63 @@ public abstract class BaseTestSheet { */ @Test public void removeMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - assertEquals(0, sheet.addMergedRegion(region)); - region = new CellRangeAddress(2, 3, 0, 1); - assertEquals(1, sheet.addMergedRegion(region)); - - sheet.removeMergedRegion(0); - - region = sheet.getMergedRegion(0); - assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow()); - - sheet.removeMergedRegion(0); - - assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions()); - - //an, add, remove, get(0) would null pointer - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(0); - assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions()); - //add it again! - region.setLastRow(4); - - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); - - //should exist now! - assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); - region = sheet.getMergedRegion(0); - assertEquals("the merged row to doesn't match the one we put in ", 4, region.getLastRow()); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); + assertEquals(0, sheet.addMergedRegion(region)); + region = new CellRangeAddress(2, 3, 0, 1); + assertEquals(1, sheet.addMergedRegion(region)); + + sheet.removeMergedRegion(0); + + region = sheet.getMergedRegion(0); + assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow()); + + sheet.removeMergedRegion(0); + + assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions()); + + //an, add, remove, get(0) would null pointer + assertEquals(0, sheet.addMergedRegion(region)); + assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); + sheet.removeMergedRegion(0); + assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions()); + //add it again! + region.setLastRow(4); + + assertEquals(0, sheet.addMergedRegion(region)); + assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); + + //should exist now! + assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); + region = sheet.getMergedRegion(0); + assertEquals("the merged row to doesn't match the one we put in ", 4, region.getLastRow()); + } } - + /** * Remove multiple merged regions */ @Test public void removeMergedRegions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - Map mergedRegions = new HashMap<>(); - for (int r=0; r<10; r++) { - CellRangeAddress region = new CellRangeAddress(r, r, 0, 1); - mergedRegions.put(r, region); - assertEquals(r, sheet.addMergedRegion(region)); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + Map mergedRegions = new HashMap<>(); + for (int r = 0; r < 10; r++) { + CellRangeAddress region = new CellRangeAddress(r, r, 0, 1); + mergedRegions.put(r, region); + assertEquals(r, sheet.addMergedRegion(region)); + } + assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); + + Collection removed = Arrays.asList(0, 2, 3, 6, 8); + mergedRegions.keySet().removeAll(removed); + sheet.removeMergedRegions(removed); + assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); } - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - - Collection removed = Arrays.asList(0, 2, 3, 6, 8); - mergedRegions.keySet().removeAll(removed); - sheet.removeMergedRegions(removed); - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - - wb.close(); } - + private static void assertCollectionEquals(Collection expected, Collection actual) { Set e = new HashSet<>(expected); Set a = new HashSet<>(actual); @@ -454,28 +442,27 @@ public abstract class BaseTestSheet { @Test public void shiftMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - CreationHelper factory = wb.getCreationHelper(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("first row, first cell")); - - row = sheet.createRow(1); - cell = row.createCell(1); - cell.setCellValue(factory.createRichTextString("second row, second cell")); - - CellRangeAddress region = CellRangeAddress.valueOf("A2:B2"); - assertEquals(0, sheet.addMergedRegion(region)); - - sheet.shiftRows(1, 1, 1); - - region = sheet.getMergedRegion(0); - - CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3"); - assertEquals("Merged region should shift down a row", expectedRegion, region); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + CreationHelper factory = wb.getCreationHelper(); + Sheet sheet = wb.createSheet(); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + cell.setCellValue(factory.createRichTextString("first row, first cell")); + + row = sheet.createRow(1); + cell = row.createCell(1); + cell.setCellValue(factory.createRichTextString("second row, second cell")); + + CellRangeAddress region = CellRangeAddress.valueOf("A2:B2"); + assertEquals(0, sheet.addMergedRegion(region)); + + sheet.shiftRows(1, 1, 1); + + region = sheet.getMergedRegion(0); + + CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3"); + assertEquals("Merged region should shift down a row", expectedRegion, region); + } } /** @@ -486,44 +473,42 @@ public abstract class BaseTestSheet { */ @Test public void addMergedRegionUnsafe() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2"); - CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3"); - CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4"); - CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11"); - assumeTrue(region1.intersects(region2)); - assumeTrue(region2.intersects(region3)); - - assertEquals(0, sh.addMergedRegionUnsafe(region1)); - assertTrue(sh.getMergedRegions().contains(region1)); - - // adding a duplicate or overlapping merged region should not - // raise an exception with the unsafe version of addMergedRegion. - - assertEquals(1, sh.addMergedRegionUnsafe(region2)); - - // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region - assertTrue(sh.getMergedRegions().contains(region2)); - try { - sh.addMergedRegion(region3); - fail("Expected IllegalStateException. region3 overlaps already added merged region2."); - } catch (final IllegalStateException e) { - // expected + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sh = wb.createSheet(); + CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2"); + CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3"); + CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4"); + CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11"); + assumeTrue(region1.intersects(region2)); + assumeTrue(region2.intersects(region3)); + + assertEquals(0, sh.addMergedRegionUnsafe(region1)); + assertTrue(sh.getMergedRegions().contains(region1)); + + // adding a duplicate or overlapping merged region should not + // raise an exception with the unsafe version of addMergedRegion. + + assertEquals(1, sh.addMergedRegionUnsafe(region2)); + + // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region + assertTrue(sh.getMergedRegions().contains(region2)); + assertThrows( + "region3 overlaps already added merged region2.", + IllegalStateException.class, + () -> sh.addMergedRegion(region3) + ); assertFalse(sh.getMergedRegions().contains(region3)); - } - // addMergedRegion should not re-validate previously-added merged regions - assertEquals(2, sh.addMergedRegion(region4)); - - // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time) - try { - sh.validateMergedRegions(); - fail("Expected validation to fail. Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2."); - } catch (final IllegalStateException e) { - // expected - } - wb.close(); + // addMergedRegion should not re-validate previously-added merged regions + assertEquals(2, sh.addMergedRegion(region4)); + + // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time) + assertThrows( + "Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2.", + IllegalStateException.class, + sh::validateMergedRegions + ); + } } /** @@ -531,187 +516,181 @@ public abstract class BaseTestSheet { */ @Test public void displayOptions() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - assertTrue(sheet.isDisplayGridlines()); - assertTrue(sheet.isDisplayRowColHeadings()); - assertFalse(sheet.isDisplayFormulas()); - assertTrue(sheet.isDisplayZeros()); - - sheet.setDisplayGridlines(false); - sheet.setDisplayRowColHeadings(false); - sheet.setDisplayFormulas(true); - sheet.setDisplayZeros(false); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - assertFalse(sheet.isDisplayGridlines()); - assertFalse(sheet.isDisplayRowColHeadings()); - assertTrue(sheet.isDisplayFormulas()); - assertFalse(sheet.isDisplayZeros()); - - wb2.close(); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet(); + + assertTrue(sheet.isDisplayGridlines()); + assertTrue(sheet.isDisplayRowColHeadings()); + assertFalse(sheet.isDisplayFormulas()); + assertTrue(sheet.isDisplayZeros()); + + sheet.setDisplayGridlines(false); + sheet.setDisplayRowColHeadings(false); + sheet.setDisplayFormulas(true); + sheet.setDisplayZeros(false); + + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + + assertFalse(sheet.isDisplayGridlines()); + assertFalse(sheet.isDisplayRowColHeadings()); + assertTrue(sheet.isDisplayFormulas()); + assertFalse(sheet.isDisplayZeros()); + } + } } @Test public void columnWidth() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - //default column width measured in characters - sheet.setDefaultColumnWidth(10); - assertEquals(10, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*10, sheet.getColumnWidth(0)); - assertEquals(256*10, sheet.getColumnWidth(1)); - assertEquals(256*10, sheet.getColumnWidth(2)); - - //set custom width for D-F - for (char i = 'D'; i <= 'F'; i++) { - //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width - int w = 256*12; - sheet.setColumnWidth(i, w); - assertEquals(w, sheet.getColumnWidth(i)); - } - //reset the default column width, columns A-C change, D-F still have custom width - sheet.setDefaultColumnWidth(20); - assertEquals(20, sheet.getDefaultColumnWidth()); - assertEquals(256*20, sheet.getColumnWidth(0)); - assertEquals(256*20, sheet.getColumnWidth(1)); - assertEquals(256*20, sheet.getColumnWidth(2)); - for (char i = 'D'; i <= 'F'; i++) { - int w = 256*12; - assertEquals(w, sheet.getColumnWidth(i)); - } - - // check for 16-bit signed/unsigned error: - sheet.setColumnWidth(10, 40000); - assertEquals(40000, sheet.getColumnWidth(10)); - - //The maximum column width for an individual cell is 255 characters - try { - sheet.setColumnWidth(9, 256*256); - fail("expected exception"); - } catch(IllegalArgumentException e){ - assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage()); - } + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet1 = wb1.createSheet(); + + //default column width measured in characters + sheet1.setDefaultColumnWidth(10); + assertEquals(10, sheet1.getDefaultColumnWidth()); + //columns A-C have default width + assertEquals(256 * 10, sheet1.getColumnWidth(0)); + assertEquals(256 * 10, sheet1.getColumnWidth(1)); + assertEquals(256 * 10, sheet1.getColumnWidth(2)); + + //set custom width for D-F + for (char i = 'D'; i <= 'F'; i++) { + //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width + int w = 256 * 12; + sheet1.setColumnWidth(i, w); + assertEquals(w, sheet1.getColumnWidth(i)); + } + //reset the default column width, columns A-C change, D-F still have custom width + sheet1.setDefaultColumnWidth(20); + assertEquals(20, sheet1.getDefaultColumnWidth()); + assertEquals(256 * 20, sheet1.getColumnWidth(0)); + assertEquals(256 * 20, sheet1.getColumnWidth(1)); + assertEquals(256 * 20, sheet1.getColumnWidth(2)); + for (char i = 'D'; i <= 'F'; i++) { + int w = 256 * 12; + assertEquals(w, sheet1.getColumnWidth(i)); + } - //serialize and read again - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - assertEquals(20, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*20, sheet.getColumnWidth(0)); - assertEquals(256*20, sheet.getColumnWidth(1)); - assertEquals(256*20, sheet.getColumnWidth(2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256*12); - assertEquals(w, sheet.getColumnWidth(i)); + // check for 16-bit signed/unsigned error: + sheet1.setColumnWidth(10, 40000); + assertEquals(40000, sheet1.getColumnWidth(10)); + + //The maximum column width for an individual cell is 255 characters + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet1.setColumnWidth(9, 256 * 256) + ); + assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage()); + + //serialize and read again + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + Sheet sheet2 = wb2.getSheetAt(0); + assertEquals(20, sheet2.getDefaultColumnWidth()); + //columns A-C have default width + assertEquals(256 * 20, sheet2.getColumnWidth(0)); + assertEquals(256 * 20, sheet2.getColumnWidth(1)); + assertEquals(256 * 20, sheet2.getColumnWidth(2)); + //columns D-F have custom width + for (char i = 'D'; i <= 'F'; i++) { + short w = (256 * 12); + assertEquals(w, sheet2.getColumnWidth(i)); + } + assertEquals(40000, sheet2.getColumnWidth(10)); + } } - assertEquals(40000, sheet.getColumnWidth(10)); - - wb2.close(); } - + @Test public void defaultRowHeight() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - sheet.setDefaultRowHeightInPoints(15); - assertEquals((short) 300, sheet.getDefaultRowHeight()); - assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F); - - Row row = sheet.createRow(1); - // new row inherits default height from the sheet - assertEquals(sheet.getDefaultRowHeight(), row.getHeight()); - - // Set a new default row height in twips and test getting the value in points - sheet.setDefaultRowHeight((short) 360); - assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 360, sheet.getDefaultRowHeight()); - - // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 - sheet.setDefaultRowHeight((short) 361); - assertEquals((float)361/20, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 361, sheet.getDefaultRowHeight()); - - // Set a new default row height in points and test getting the value in twips - sheet.setDefaultRowHeightInPoints(17.5f); - assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight()); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + sheet.setDefaultRowHeightInPoints(15); + assertEquals((short) 300, sheet.getDefaultRowHeight()); + assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F); + + Row row = sheet.createRow(1); + // new row inherits default height from the sheet + assertEquals(sheet.getDefaultRowHeight(), row.getHeight()); + + // Set a new default row height in twips and test getting the value in points + sheet.setDefaultRowHeight((short) 360); + assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F); + assertEquals((short) 360, sheet.getDefaultRowHeight()); + + // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 + sheet.setDefaultRowHeight((short) 361); + assertEquals((float) 361 / 20, sheet.getDefaultRowHeightInPoints(), 0F); + assertEquals((short) 361, sheet.getDefaultRowHeight()); + + // Set a new default row height in points and test getting the value in twips + sheet.setDefaultRowHeightInPoints(17.5f); + assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F); + assertEquals((short) (17.5f * 20), sheet.getDefaultRowHeight()); + } } /** cell with formula becomes null on cloning a sheet*/ @Test public void bug35084() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellFormula("A1*2"); - Sheet s1 = wb.cloneSheet(0); - r = s1.getRow(0); - assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check - assertNotNull(r.getCell(1)); - assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2"); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet s = wb.createSheet("Sheet1"); + Row r = s.createRow(0); + r.createCell(0).setCellValue(1); + r.createCell(1).setCellFormula("A1*2"); + Sheet s1 = wb.cloneSheet(0); + r = s1.getRow(0); + assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check + assertNotNull(r.getCell(1)); + assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2"); + } } /** test that new default column styles get applied */ @Test public void defaultColumnStyle() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - CellStyle style = wb.createCellStyle(); - Sheet sheet = wb.createSheet(); - sheet.setDefaultColumnStyle(0, style); - assertNotNull(sheet.getColumnStyle(0)); - assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex()); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - CellStyle style2 = cell.getCellStyle(); - assertNotNull(style2); - assertEquals("style should match", style.getIndex(), style2.getIndex()); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + CellStyle style = wb.createCellStyle(); + Sheet sheet = wb.createSheet(); + sheet.setDefaultColumnStyle(0, style); + assertNotNull(sheet.getColumnStyle(0)); + assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex()); + + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + CellStyle style2 = cell.getCellStyle(); + assertNotNull(style2); + assertEquals("style should match", style.getIndex(), style2.getIndex()); + } } @Test public void outlineProperties() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - - Sheet sheet = wb1.createSheet(); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet(); - //TODO defaults are different in HSSF and XSSF - //assertTrue(sheet.getRowSumsBelow()); - //assertTrue(sheet.getRowSumsRight()); + //TODO defaults are different in HSSF and XSSF + //assertTrue(sheet.getRowSumsBelow()); + //assertTrue(sheet.getRowSumsRight()); - sheet.setRowSumsBelow(false); - sheet.setRowSumsRight(false); + sheet.setRowSumsBelow(false); + sheet.setRowSumsRight(false); - assertFalse(sheet.getRowSumsBelow()); - assertFalse(sheet.getRowSumsRight()); + assertFalse(sheet.getRowSumsBelow()); + assertFalse(sheet.getRowSumsRight()); - sheet.setRowSumsBelow(true); - sheet.setRowSumsRight(true); + sheet.setRowSumsBelow(true); + sheet.setRowSumsRight(true); - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); + assertTrue(sheet.getRowSumsBelow()); + assertTrue(sheet.getRowSumsRight()); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); - wb2.close(); + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + assertTrue(sheet.getRowSumsBelow()); + assertTrue(sheet.getRowSumsRight()); + } + } } /** @@ -719,61 +698,60 @@ public abstract class BaseTestSheet { */ @Test public void sheetProperties() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(true); - assertTrue(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(false); - assertFalse(sheet.getHorizontallyCenter()); - - assertFalse(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(true); - assertTrue(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(false); - assertFalse(sheet.getVerticallyCenter()); - - assertFalse(sheet.isPrintGridlines()); - sheet.setPrintGridlines(true); - assertTrue(sheet.isPrintGridlines()); - - assertFalse(sheet.isPrintRowAndColumnHeadings()); - sheet.setPrintRowAndColumnHeadings(true); - assertTrue(sheet.isPrintRowAndColumnHeadings()); - - assertFalse(sheet.isDisplayFormulas()); - sheet.setDisplayFormulas(true); - assertTrue(sheet.isDisplayFormulas()); - - assertTrue(sheet.isDisplayGridlines()); - sheet.setDisplayGridlines(false); - assertFalse(sheet.isDisplayGridlines()); - - //TODO: default "guts" is different in HSSF and XSSF - //assertTrue(sheet.getDisplayGuts()); - sheet.setDisplayGuts(false); - assertFalse(sheet.getDisplayGuts()); - - assertTrue(sheet.isDisplayRowColHeadings()); - sheet.setDisplayRowColHeadings(false); - assertFalse(sheet.isDisplayRowColHeadings()); - - //TODO: default "autobreaks" is different in HSSF and XSSF - //assertTrue(sheet.getAutobreaks()); - sheet.setAutobreaks(false); - assertFalse(sheet.getAutobreaks()); - - assertFalse(sheet.getScenarioProtect()); - - //TODO: default "fit-to-page" is different in HSSF and XSSF - //assertFalse(sheet.getFitToPage()); - sheet.setFitToPage(true); - assertTrue(sheet.getFitToPage()); - sheet.setFitToPage(false); - assertFalse(sheet.getFitToPage()); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + assertFalse(sheet.getHorizontallyCenter()); + sheet.setHorizontallyCenter(true); + assertTrue(sheet.getHorizontallyCenter()); + sheet.setHorizontallyCenter(false); + assertFalse(sheet.getHorizontallyCenter()); + + assertFalse(sheet.getVerticallyCenter()); + sheet.setVerticallyCenter(true); + assertTrue(sheet.getVerticallyCenter()); + sheet.setVerticallyCenter(false); + assertFalse(sheet.getVerticallyCenter()); + + assertFalse(sheet.isPrintGridlines()); + sheet.setPrintGridlines(true); + assertTrue(sheet.isPrintGridlines()); + + assertFalse(sheet.isPrintRowAndColumnHeadings()); + sheet.setPrintRowAndColumnHeadings(true); + assertTrue(sheet.isPrintRowAndColumnHeadings()); + + assertFalse(sheet.isDisplayFormulas()); + sheet.setDisplayFormulas(true); + assertTrue(sheet.isDisplayFormulas()); + + assertTrue(sheet.isDisplayGridlines()); + sheet.setDisplayGridlines(false); + assertFalse(sheet.isDisplayGridlines()); + + //TODO: default "guts" is different in HSSF and XSSF + //assertTrue(sheet.getDisplayGuts()); + sheet.setDisplayGuts(false); + assertFalse(sheet.getDisplayGuts()); + + assertTrue(sheet.isDisplayRowColHeadings()); + sheet.setDisplayRowColHeadings(false); + assertFalse(sheet.isDisplayRowColHeadings()); + + //TODO: default "autobreaks" is different in HSSF and XSSF + //assertTrue(sheet.getAutobreaks()); + sheet.setAutobreaks(false); + assertFalse(sheet.getAutobreaks()); + + assertFalse(sheet.getScenarioProtect()); + + //TODO: default "fit-to-page" is different in HSSF and XSSF + //assertFalse(sheet.getFitToPage()); + sheet.setFitToPage(true); + assertTrue(sheet.getFitToPage()); + sheet.setFitToPage(false); + assertFalse(sheet.getFitToPage()); + } } public void baseTestGetSetMargin(double[] defaultMargins) throws IOException { @@ -784,255 +762,254 @@ public abstract class BaseTestSheet { //double marginHeader = defaultMargins[4]; //double marginFooter = defaultMargins[5]; - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0); - sheet.setMargin(Sheet.LeftMargin, 10.0); - //left margin is custom, all others are default - assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0); - assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0); - assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0); - assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0); - sheet.setMargin(Sheet.RightMargin, 11.0); - assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0); - sheet.setMargin(Sheet.TopMargin, 12.0); - assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0); - sheet.setMargin(Sheet.BottomMargin, 13.0); - assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0); - - sheet.setMargin(Sheet.FooterMargin, 5.6); - assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0); - sheet.setMargin(Sheet.HeaderMargin, 11.5); - assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0); - - // incorrect margin constant - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unknown margin constant: 65"); - sheet.setMargin((short) 65, 15); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet("Sheet 1"); + assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0); + sheet.setMargin(Sheet.LeftMargin, 10.0); + //left margin is custom, all others are default + assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0); + assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0); + assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0); + assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0); + sheet.setMargin(Sheet.RightMargin, 11.0); + assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0); + sheet.setMargin(Sheet.TopMargin, 12.0); + assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0); + sheet.setMargin(Sheet.BottomMargin, 13.0); + assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0); + + sheet.setMargin(Sheet.FooterMargin, 5.6); + assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0); + sheet.setMargin(Sheet.HeaderMargin, 11.5); + assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0); + + // incorrect margin constant + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> sheet.setMargin((short) 65, 15) + ); + assertEquals("Unknown margin constant: 65", ex.getMessage()); + } } @Test public void rowBreaks() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - //Sheet#getRowBreaks() returns an empty array if no row breaks are defined - assertNotNull(sheet.getRowBreaks()); - assertEquals(0, sheet.getRowBreaks().length); - - sheet.setRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.setRowBreak(15); - assertEquals(2, sheet.getRowBreaks().length); - assertEquals(1, sheet.getRowBreaks()[0]); - assertEquals(15, sheet.getRowBreaks()[1]); - sheet.setRowBreak(1); - assertEquals(2, sheet.getRowBreaks().length); - assertTrue(sheet.isRowBroken(1)); - assertTrue(sheet.isRowBroken(15)); - - //now remove the created breaks - sheet.removeRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.removeRowBreak(15); - assertEquals(0, sheet.getRowBreaks().length); - - assertFalse(sheet.isRowBroken(1)); - assertFalse(sheet.isRowBroken(15)); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + //Sheet#getRowBreaks() returns an empty array if no row breaks are defined + assertNotNull(sheet.getRowBreaks()); + assertEquals(0, sheet.getRowBreaks().length); + + sheet.setRowBreak(1); + assertEquals(1, sheet.getRowBreaks().length); + sheet.setRowBreak(15); + assertEquals(2, sheet.getRowBreaks().length); + assertEquals(1, sheet.getRowBreaks()[0]); + assertEquals(15, sheet.getRowBreaks()[1]); + sheet.setRowBreak(1); + assertEquals(2, sheet.getRowBreaks().length); + assertTrue(sheet.isRowBroken(1)); + assertTrue(sheet.isRowBroken(15)); + + //now remove the created breaks + sheet.removeRowBreak(1); + assertEquals(1, sheet.getRowBreaks().length); + sheet.removeRowBreak(15); + assertEquals(0, sheet.getRowBreaks().length); + + assertFalse(sheet.isRowBroken(1)); + assertFalse(sheet.isRowBroken(15)); + } } @Test public void columnBreaks() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(0)); - - sheet.setColumnBreak(11); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(11, sheet.getColumnBreaks()[0]); - sheet.setColumnBreak(12); - assertEquals(2, sheet.getColumnBreaks().length); - assertTrue(sheet.isColumnBroken(11)); - assertTrue(sheet.isColumnBroken(12)); - - sheet.removeColumnBreak((short) 11); - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 15); //remove non-existing - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 12); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(11)); - assertFalse(sheet.isColumnBroken(12)); - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + assertNotNull(sheet.getColumnBreaks()); + assertEquals(0, sheet.getColumnBreaks().length); + + assertFalse(sheet.isColumnBroken(0)); + + sheet.setColumnBreak(11); + assertNotNull(sheet.getColumnBreaks()); + assertEquals(11, sheet.getColumnBreaks()[0]); + sheet.setColumnBreak(12); + assertEquals(2, sheet.getColumnBreaks().length); + assertTrue(sheet.isColumnBroken(11)); + assertTrue(sheet.isColumnBroken(12)); + + sheet.removeColumnBreak((short) 11); + assertEquals(1, sheet.getColumnBreaks().length); + sheet.removeColumnBreak((short) 15); //remove non-existing + assertEquals(1, sheet.getColumnBreaks().length); + sheet.removeColumnBreak((short) 12); + assertEquals(0, sheet.getColumnBreaks().length); + + assertFalse(sheet.isColumnBroken(11)); + assertFalse(sheet.isColumnBroken(12)); + } } @Test public void getFirstLastRowNum() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.createRow(9); - sheet.createRow(0); - sheet.createRow(1); - assertEquals(0, sheet.getFirstRowNum()); - assertEquals(9, sheet.getLastRowNum()); - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet("Sheet 1"); + sheet.createRow(9); + sheet.createRow(0); + sheet.createRow(1); + assertEquals(0, sheet.getFirstRowNum()); + assertEquals(9, sheet.getLastRowNum()); + } } @Test public void getFooter() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - assertNotNull(sheet.getFooter()); - sheet.getFooter().setCenter("test center footer"); - assertEquals("test center footer", sheet.getFooter().getCenter()); - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet("Sheet 1"); + assertNotNull(sheet.getFooter()); + sheet.getFooter().setCenter("test center footer"); + assertEquals("test center footer", sheet.getFooter().getCenter()); + } } @Test public void getSetColumnHidden() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnHidden(2, true); - assertTrue(sheet.isColumnHidden(2)); - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet("Sheet 1"); + sheet.setColumnHidden(2, true); + assertTrue(sheet.isColumnHidden(2)); + } } @Test public void protectSheet() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertFalse(sheet.getProtect()); - sheet.protectSheet("Test"); - assertTrue(sheet.getProtect()); - sheet.protectSheet(null); - assertFalse(sheet.getProtect()); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + assertFalse(sheet.getProtect()); + sheet.protectSheet("Test"); + assertTrue(sheet.getProtect()); + sheet.protectSheet(null); + assertFalse(sheet.getProtect()); + } } @Test public void createFreezePane() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - // create a workbook - Sheet sheet = wb.createSheet(); - assertNull(sheet.getPaneInformation()); - sheet.createFreezePane(0, 0); - // still null - assertNull(sheet.getPaneInformation()); + try (Workbook wb = _testDataProvider.createWorkbook()) { + // create a workbook + Sheet sheet = wb.createSheet(); + assertNull(sheet.getPaneInformation()); + sheet.createFreezePane(0, 0); + // still null + assertNull(sheet.getPaneInformation()); - sheet.createFreezePane(2, 3); + sheet.createFreezePane(2, 3); - PaneInformation info = sheet.getPaneInformation(); + PaneInformation info = sheet.getPaneInformation(); - assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(2, info.getVerticalSplitLeftColumn()); - assertEquals(2, info.getVerticalSplitPosition()); + assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane()); + assertEquals(3, info.getHorizontalSplitPosition()); + assertEquals(3, info.getHorizontalSplitTopRow()); + assertEquals(2, info.getVerticalSplitLeftColumn()); + assertEquals(2, info.getVerticalSplitPosition()); - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); + sheet.createFreezePane(0, 0); + // If both colSplit and rowSplit are zero then the existing freeze pane is removed + assertNull(sheet.getPaneInformation()); - sheet.createFreezePane(0, 3); + sheet.createFreezePane(0, 3); - info = sheet.getPaneInformation(); + info = sheet.getPaneInformation(); - assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(0, info.getVerticalSplitLeftColumn()); - assertEquals(0, info.getVerticalSplitPosition()); + assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane()); + assertEquals(3, info.getHorizontalSplitPosition()); + assertEquals(3, info.getHorizontalSplitTopRow()); + assertEquals(0, info.getVerticalSplitLeftColumn()); + assertEquals(0, info.getVerticalSplitPosition()); - sheet.createFreezePane(3, 0); + sheet.createFreezePane(3, 0); - info = sheet.getPaneInformation(); + info = sheet.getPaneInformation(); - assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane()); - assertEquals(0, info.getHorizontalSplitPosition()); - assertEquals(0, info.getHorizontalSplitTopRow()); - assertEquals(3, info.getVerticalSplitLeftColumn()); - assertEquals(3, info.getVerticalSplitPosition()); + assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane()); + assertEquals(0, info.getHorizontalSplitPosition()); + assertEquals(0, info.getHorizontalSplitTopRow()); + assertEquals(3, info.getVerticalSplitLeftColumn()); + assertEquals(3, info.getVerticalSplitPosition()); - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); - - wb.close(); + sheet.createFreezePane(0, 0); + // If both colSplit and rowSplit are zero then the existing freeze pane is removed + assertNull(sheet.getPaneInformation()); + } } - + @Test public void getRepeatingRowsAndColumns() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook( - "RepeatingRowsCols." - + _testDataProvider.getStandardFileNameExtension()); - - checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null); - checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null); - checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A"); - checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B"); - wb.close(); + try (Workbook wb = _testDataProvider.openSampleWorkbook( + "RepeatingRowsCols." + + _testDataProvider.getStandardFileNameExtension())) { + + checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null); + checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null); + checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A"); + checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B"); + } } @Test public void setRepeatingRowsAndColumnsBug47294() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet(); - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet1.getRepeatingRows().formatAsString()); - - //must handle sheets with quotas, see Bugzilla #47294 - Sheet sheet2 = wb.createSheet("My' Sheet"); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet1 = wb.createSheet(); + sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); + assertEquals("1:4", sheet1.getRepeatingRows().formatAsString()); + + //must handle sheets with quotas, see Bugzilla #47294 + Sheet sheet2 = wb.createSheet("My' Sheet"); + sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4")); + assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); + } } @Test public void setRepeatingRowsAndColumns() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb1.createSheet("Sheet1"); - Sheet sheet2 = wb1.createSheet("Sheet2"); - Sheet sheet3 = wb1.createSheet("Sheet3"); - - checkRepeatingRowsAndColumns(sheet1, null, null); - - sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5")); - sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); - sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // write out, read back, and test refrain... - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - sheet2 = wb2.getSheetAt(1); - sheet3 = wb2.getSheetAt(2); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // check removing repeating rows and columns - sheet3.setRepeatingRows(null); - checkRepeatingRowsAndColumns(sheet3, null, "A:A"); - - sheet3.setRepeatingColumns(null); - checkRepeatingRowsAndColumns(sheet3, null, null); - wb2.close(); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet1 = wb1.createSheet("Sheet1"); + Sheet sheet2 = wb1.createSheet("Sheet2"); + Sheet sheet3 = wb1.createSheet("Sheet3"); + + checkRepeatingRowsAndColumns(sheet1, null, null); + + sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5")); + sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); + sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4")); + sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); + + checkRepeatingRowsAndColumns(sheet1, "4:5", null); + checkRepeatingRowsAndColumns(sheet2, null, "A:C"); + checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); + + // write out, read back, and test refrain... + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + sheet1 = wb2.getSheetAt(0); + sheet2 = wb2.getSheetAt(1); + sheet3 = wb2.getSheetAt(2); + + checkRepeatingRowsAndColumns(sheet1, "4:5", null); + checkRepeatingRowsAndColumns(sheet2, null, "A:C"); + checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); + + // check removing repeating rows and columns + sheet3.setRepeatingRows(null); + checkRepeatingRowsAndColumns(sheet3, null, "A:A"); + + sheet3.setRepeatingColumns(null); + checkRepeatingRowsAndColumns(sheet3, null, null); + } + } } private void checkRepeatingRowsAndColumns( @@ -1051,61 +1028,60 @@ public abstract class BaseTestSheet { @Test public void baseZoom() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - // here we can only verify that setting some zoom values works, range-checking is different between the implementations - sheet.setZoom(75); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + // here we can only verify that setting some zoom values works, + // range-checking is different between the implementations + sheet.setZoom(75); + } } - + @Test public void baseShowInPane() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - sheet.showInPane(2, 3); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + sheet.showInPane(2, 3); + } } @Test public void bug55723() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + CellRangeAddress range = CellRangeAddress.valueOf("A:B"); + AutoFilter filter = sheet.setAutoFilter(range); + assertNotNull(filter); + // there seems to be currently no generic way to check the setting... + + range = CellRangeAddress.valueOf("B:C"); + filter = sheet.setAutoFilter(range); + assertNotNull(filter); + // there seems to be currently no generic way to check the setting... + } } @Test public void bug55723_Rows() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000"); + AutoFilter filter = sheet.setAutoFilter(range); + assertNotNull(filter); + } } @Test public void bug55723d_RowsOver65k() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000"); + AutoFilter filter = sheet.setAutoFilter(range); + assertNotNull(filter); + } } /** @@ -1113,179 +1089,177 @@ public abstract class BaseTestSheet { */ @Test public void bug48325() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Test"); - trackColumnsForAutoSizingIfSXSSF(sheet); - CreationHelper factory = wb.getCreationHelper(); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - Font font = wb.createFont(); - RichTextString rts = factory.createRichTextString(""); - rts.applyFont(font); - cell.setCellValue(rts); - - sheet.autoSizeColumn(0); - - assertNotNull(_testDataProvider.writeOutAndReadBack(wb)); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet("Test"); + trackColumnsForAutoSizingIfSXSSF(sheet); + CreationHelper factory = wb.getCreationHelper(); + + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + + Font font = wb.createFont(); + RichTextString rts = factory.createRichTextString(""); + rts.applyFont(font); + cell.setCellValue(rts); + + sheet.autoSizeColumn(0); + + assertNotNull(_testDataProvider.writeOutAndReadBack(wb)); + } } @Test public void getCellComment() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Drawing dg = sheet.createDrawingPatriarch(); - Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor()); - Cell cell = sheet.createRow(9).createCell(2); - comment.setAuthor("test C10 author"); - cell.setCellComment(comment); - - CellAddress ref = new CellAddress(9, 2); - assertNotNull(sheet.getCellComment(ref)); - assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + Drawing dg = sheet.createDrawingPatriarch(); + Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor()); + Cell cell = sheet.createRow(9).createCell(2); + comment.setAuthor("test C10 author"); + cell.setCellComment(comment); + + CellAddress ref = new CellAddress(9, 2); + assertNotNull(sheet.getCellComment(ref)); + assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor()); + + assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); + } } @Test public void getCellComments() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("TEST"); - - // a sheet with no cell comments should return an empty map (not null or raise NPE). - assertTrue(sheet.getCellComments().isEmpty()); - - Drawing dg = sheet.createDrawingPatriarch(); - ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); - - int nRows = 5; - int nCols = 6; - - for (int r=0; r=0; c--) { - // When the comment box is visible, have it show in a 1x3 space - anchor.setCol1(c); - anchor.setCol2(c); - anchor.setRow1(r); - anchor.setRow2(r); - - // Create the comment and set the text-author - Comment comment = dg.createCellComment(anchor); - Cell cell = sheet.getRow(r).createCell(c); - comment.setAuthor("Author " + r); - RichTextString text = workbook.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c); - comment.setString(text); - - // Assign the comment to the cell - cell.setCellComment(comment); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet("TEST"); + + // a sheet with no cell comments should return an empty map (not null or raise NPE). + assertTrue(sheet.getCellComments().isEmpty()); + + Drawing dg = sheet.createDrawingPatriarch(); + ClientAnchor anchor = wb1.getCreationHelper().createClientAnchor(); + + int nRows = 5; + int nCols = 6; + + for (int r = 0; r < nRows; r++) { + sheet.createRow(r); + // Create columns in reverse order + for (int c = nCols - 1; c >= 0; c--) { + // When the comment box is visible, have it show in a 1x3 space + anchor.setCol1(c); + anchor.setCol2(c); + anchor.setRow1(r); + anchor.setRow2(r); + + // Create the comment and set the text-author + Comment comment = dg.createCellComment(anchor); + Cell cell = sheet.getRow(r).createCell(c); + comment.setAuthor("Author " + r); + RichTextString text = wb1.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c); + comment.setString(text); + + // Assign the comment to the cell + cell.setCellComment(comment); + } + } + + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + Sheet sh = wb2.getSheet("TEST"); + Map cellComments = sh.getCellComments(); + assertEquals(nRows * nCols, cellComments.size()); + + for (Entry e : cellComments.entrySet()) { + CellAddress ref = e.getKey(); + Comment aComment = e.getValue(); + assertEquals("Author " + ref.getRow(), aComment.getAuthor()); + String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn(); + assertEquals(text, aComment.getString().getString()); + } } } - - Workbook wb = _testDataProvider.writeOutAndReadBack(workbook); - Sheet sh = wb.getSheet("TEST"); - Map cellComments = sh.getCellComments(); - assertEquals(nRows*nCols, cellComments.size()); - - for (Entry e : cellComments.entrySet()) { - CellAddress ref = e.getKey(); - Comment aComment = e.getValue(); - assertEquals("Author " + ref.getRow(), aComment.getAuthor()); - String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn(); - assertEquals(text, aComment.getString().getString()); - } - - workbook.close(); - wb.close(); } - + @Test public void getHyperlink() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - - assertEquals("list size before add", 0, sheet.getHyperlinkList().size()); - cell.setHyperlink(hyperlink); - assertEquals("list size after add", 1, sheet.getHyperlinkList().size()); - - assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0)); - 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)); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); + hyperlink.setAddress("https://poi.apache.org/"); + + Sheet sheet = workbook.createSheet(); + Cell cell = sheet.createRow(5).createCell(1); + + assertEquals("list size before add", 0, sheet.getHyperlinkList().size()); + cell.setHyperlink(hyperlink); + assertEquals("list size after add", 1, sheet.getHyperlinkList().size()); + + assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0)); + 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)); + } } - + @Test - public void removeAllHyperlinks() { - Workbook workbook = _testDataProvider.createWorkbook(); - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - cell.setHyperlink(hyperlink); - - assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size()); - // Save a workbook with a hyperlink - Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook); - assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Remove all hyperlinks from a saved workbook - workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink(); - assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Verify that hyperlink was removed from workbook after writing out - Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2); - assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size()); + public void removeAllHyperlinks() throws IOException { + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); + hyperlink.setAddress("https://poi.apache.org/"); + Sheet sheet = workbook.createSheet(); + Cell cell = sheet.createRow(5).createCell(1); + cell.setHyperlink(hyperlink); + + assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size()); + + // Save a workbook with a hyperlink + try (Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook)) { + assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size()); + + // Remove all hyperlinks from a saved workbook + workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink(); + assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size()); + + // Verify that hyperlink was removed from workbook after writing out + try (Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2)) { + assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size()); + } + } + } } @Test public void newMergedRegionAt() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - assertEquals(0, sheet.addMergedRegion(region)); - assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString()); - assertEquals(1, sheet.getNumMergedRegions()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - - workbook.close(); + try (Workbook workbook = _testDataProvider.createWorkbook()) { + Sheet sheet = workbook.createSheet(); + CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); + assertEquals(0, sheet.addMergedRegion(region)); + assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString()); + assertEquals(1, sheet.getNumMergedRegions()); + + assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); + } } @Test public void showInPaneManyRowsBug55248() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet("Sheet 1"); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet("Sheet 1"); - sheet.showInPane(0, 0); + sheet.showInPane(0, 0); - for(int i = ROW_COUNT/2;i < ROW_COUNT;i++) { - sheet.createRow(i); - sheet.showInPane(i, 0); - // this one fails: sheet.showInPane((short)i, 0); - } + for (int i = ROW_COUNT / 2; i < ROW_COUNT; i++) { + sheet.createRow(i); + sheet.showInPane(i, 0); + // this one fails: sheet.showInPane((short)i, 0); + } - int i = 0; - sheet.showInPane(i, i); + int i = 0; + sheet.showInPane(i, i); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - checkRowCount(wb2); - - wb2.close(); - wb1.close(); + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + checkRowCount(wb2); + } + } } private void checkRowCount(Workbook wb) { @@ -1294,28 +1268,27 @@ public abstract class BaseTestSheet { assertNotNull(sh); assertEquals(ROW_COUNT-1, sh.getLastRowNum()); } - - + + @Test public void testRightToLeft() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.isRightToLeft()); - sheet.setRightToLeft(true); - assertTrue(sheet.isRightToLeft()); - sheet.setRightToLeft(false); - assertFalse(sheet.isRightToLeft()); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + + assertFalse(sheet.isRightToLeft()); + sheet.setRightToLeft(true); + assertTrue(sheet.isRightToLeft()); + sheet.setRightToLeft(false); + assertFalse(sheet.isRightToLeft()); + } } - + @Test public void testNoMergedRegionsIsEmptyList() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertTrue(sheet.getMergedRegions().isEmpty()); - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet = wb.createSheet(); + assertTrue(sheet.getMergedRegions().isEmpty()); + } } /** @@ -1323,63 +1296,61 @@ public abstract class BaseTestSheet { */ @Test public void setActiveCell() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - CellAddress B42 = new CellAddress("B42"); - - // active cell behavior is undefined if not set. - // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null. - if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) { - fail("If not set, active cell should default to null or A1"); - } - - sheet.setActiveCell(B42); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + try (Workbook wb1 = _testDataProvider.createWorkbook()) { + Sheet sheet = wb1.createSheet(); + CellAddress B42 = new CellAddress("B42"); + + // active cell behavior is undefined if not set. + // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null. + if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) { + fail("If not set, active cell should default to null or A1"); + } - assertEquals(B42, sheet.getActiveCell()); + sheet.setActiveCell(B42); - wb1.close(); - wb2.close(); + try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + assertEquals(B42, sheet.getActiveCell()); + } + } } @Test public void autoSizeDate() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellValue(123456); - - // for the streaming-variant we need to enable autosize-tracking to make it work - trackColumnsForAutoSizingIfSXSSF(s); - - // Will be sized fairly small - s.autoSizeColumn((short)0); - s.autoSizeColumn((short)1); - - // Size ranges due to different fonts on different machines - assertBetween("Single number column width", s.getColumnWidth(0), 350, 570); - assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100); - - // Set a date format - CellStyle cs = wb.createCellStyle(); - DataFormat f = wb.createDataFormat(); - cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss")); - r.getCell(0).setCellStyle(cs); - r.getCell(1).setCellStyle(cs); - - assertTrue(DateUtil.isCellDateFormatted(r.getCell(0))); - assertTrue(DateUtil.isCellDateFormatted(r.getCell(1))); - - // Should get much bigger now - s.autoSizeColumn((short)0); - s.autoSizeColumn((short)1); - - assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300); - assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet s = wb.createSheet("Sheet1"); + Row r = s.createRow(0); + r.createCell(0).setCellValue(1); + r.createCell(1).setCellValue(123456); + + // for the streaming-variant we need to enable autosize-tracking to make it work + trackColumnsForAutoSizingIfSXSSF(s); + + // Will be sized fairly small + s.autoSizeColumn((short) 0); + s.autoSizeColumn((short) 1); + + // Size ranges due to different fonts on different machines + assertBetween("Single number column width", s.getColumnWidth(0), 350, 570); + assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100); + + // Set a date format + CellStyle cs = wb.createCellStyle(); + DataFormat f = wb.createDataFormat(); + cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss")); + r.getCell(0).setCellStyle(cs); + r.getCell(1).setCellStyle(cs); + + assertTrue(DateUtil.isCellDateFormatted(r.getCell(0))); + assertTrue(DateUtil.isCellDateFormatted(r.getCell(1))); + + // Should get much bigger now + s.autoSizeColumn((short) 0); + s.autoSizeColumn((short) 1); + + assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300); + assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300); + } } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java index d040cf216f..b36078d310 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java @@ -23,6 +23,7 @@ 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; @@ -37,9 +38,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.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public abstract class BaseTestWorkbook { @@ -49,10 +48,6 @@ public abstract class BaseTestWorkbook { _testDataProvider = testDataProvider; } - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test public void sheetIterator_forEach() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { @@ -131,14 +126,15 @@ public abstract class BaseTestWorkbook { //getting a sheet by invalid index or non-existing name assertNull(wb.getSheet("Sheet1")); - try { - wb.getSheetAt(0); - fail("should have thrown exceptiuon due to invalid sheet index"); - } catch (IllegalArgumentException e) { - // expected during successful test - // no negative index in the range message - assertFalse(e.getMessage().contains("-1")); - } + IllegalArgumentException ex = assertThrows( + "should have thrown exception due to invalid sheet index", + IllegalArgumentException.class, + () -> wb.getSheetAt(0) + ); + // expected during successful test no negative index in the range message + assertFalse(ex.getMessage().contains("-1")); + + assertThrows(IllegalArgumentException.class, () -> wb.getSheetAt(0)); Sheet sheet0 = wb.createSheet(); Sheet sheet1 = wb.createSheet(); @@ -155,25 +151,24 @@ public abstract class BaseTestWorkbook { assertEquals("Sheet3", fetchedSheet.getSheetName()); assertEquals(3, wb.getNumberOfSheets()); assertSame(originalSheet, fetchedSheet); - try { - wb.createSheet("sHeeT3"); - fail("should have thrown exceptiuon due to duplicate sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertEquals("The workbook already contains a sheet named 'sHeeT3'", e.getMessage()); - } + ex = assertThrows( + "should have thrown exception due to duplicate sheet name", + IllegalArgumentException.class, + () -> wb.createSheet("sHeeT3") + ); + // expected during successful test + assertEquals("The workbook already contains a sheet named 'sHeeT3'", ex.getMessage()); //names cannot be blank or contain any of /\*?[] String[] invalidNames = {"", "Sheet/", "Sheet\\", "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'", "My:Sheet"}; for (String sheetName : invalidNames) { - try { - wb.createSheet(sheetName); - fail("should have thrown exception due to invalid sheet name: " + sheetName); - } catch (IllegalArgumentException e) { - // expected during successful test - } + assertThrows( + "should have thrown exception due to invalid sheet name: " + sheetName, + IllegalArgumentException.class, + () -> wb.createSheet(sheetName) + ); } //still have 3 sheets assertEquals(3, wb.getNumberOfSheets()); @@ -854,28 +849,27 @@ public abstract class BaseTestWorkbook { @Test public void getSheetIndex() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - Sheet sheet4 = wb.createSheet("Sheet4"); - - assertEquals(0, wb.getSheetIndex(sheet1)); - assertEquals(1, wb.getSheetIndex(sheet2)); - assertEquals(2, wb.getSheetIndex(sheet3)); - assertEquals(3, wb.getSheetIndex(sheet4)); - - // remove sheets - wb.removeSheetAt(0); - wb.removeSheetAt(2); - - // ensure that sheets are moved up and removed sheets are not found any more - assertEquals(-1, wb.getSheetIndex(sheet1)); - assertEquals(0, wb.getSheetIndex(sheet2)); - assertEquals(1, wb.getSheetIndex(sheet3)); - assertEquals(-1, wb.getSheetIndex(sheet4)); - - wb.close(); + try (Workbook wb = _testDataProvider.createWorkbook()) { + Sheet sheet1 = wb.createSheet("Sheet1"); + Sheet sheet2 = wb.createSheet("Sheet2"); + Sheet sheet3 = wb.createSheet("Sheet3"); + Sheet sheet4 = wb.createSheet("Sheet4"); + + assertEquals(0, wb.getSheetIndex(sheet1)); + assertEquals(1, wb.getSheetIndex(sheet2)); + assertEquals(2, wb.getSheetIndex(sheet3)); + assertEquals(3, wb.getSheetIndex(sheet4)); + + // remove sheets + wb.removeSheetAt(0); + wb.removeSheetAt(2); + + // ensure that sheets are moved up and removed sheets are not found any more + assertEquals(-1, wb.getSheetIndex(sheet1)); + assertEquals(0, wb.getSheetIndex(sheet2)); + assertEquals(1, wb.getSheetIndex(sheet3)); + assertEquals(-1, wb.getSheetIndex(sheet4)); + } } @Test @@ -884,9 +878,11 @@ public abstract class BaseTestWorkbook { Sheet sheet1 = wb.createSheet("Sheet1"); assertNotNull(sheet1); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("already contains a sheet named 'Sheet1'"); - wb.createSheet("Sheet1"); + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> wb.createSheet("Sheet1") + ); + assertEquals("The workbook already contains a sheet named 'Sheet1'", ex.getMessage()); } } diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java index e0df851a6f..7e048dbc3a 100644 --- a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java +++ b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java @@ -20,23 +20,20 @@ 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 java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} */ public final class TestLittleEndianStreams { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testRead() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -95,9 +92,8 @@ public final class TestLittleEndianStreams { assertEquals(0x8899, lei.readUShort()); // only one byte left, so this should fail - thrown.expect(RuntimeException.class); - thrown.expectMessage("Buffer overrun"); - lei.readFully(new byte[4]); + RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); + assertTrue(ex.getMessage().contains("Buffer overrun")); } @Test @@ -106,9 +102,8 @@ public final class TestLittleEndianStreams { LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2); // only one byte left, so this should fail - thrown.expect(RuntimeException.class); - thrown.expectMessage("Buffer overrun"); - lei.readFully(new byte[4]); + RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); + assertTrue(ex.getMessage().contains("Buffer overrun")); } @Test @@ -117,8 +112,7 @@ public final class TestLittleEndianStreams { LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2, 2); // only one byte left, so this should fail - thrown.expect(RuntimeException.class); - thrown.expectMessage("Buffer overrun"); - lei.readFully(new byte[4]); + RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); + assertTrue(ex.getMessage().contains("Buffer overrun")); } } diff --git a/src/testcases/org/apache/poi/util/TestTempFile.java b/src/testcases/org/apache/poi/util/TestTempFile.java index 47fa72dbe8..ac1904dabc 100644 --- a/src/testcases/org/apache/poi/util/TestTempFile.java +++ b/src/testcases/org/apache/poi/util/TestTempFile.java @@ -19,6 +19,7 @@ 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 java.io.File; @@ -29,16 +30,11 @@ import java.util.Arrays; import org.apache.poi.poifs.dev.TestPOIFSDump; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class TestTempFile { private String previousTempDir; private File tempDir; - - @Rule - public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws IOException { @@ -109,14 +105,14 @@ public class TestTempFile { // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" assertTrue("Unable to delete temp file", 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")); } - + @Test public void testCreateTempDirectory() throws IOException { @@ -132,11 +128,11 @@ public class TestTempFile { // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" assertTrue("Unable to delete tempDir", tempDir.delete()); } - + @Test public void testSetTempFileCreationStrategy() throws IOException { TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - + // Should be able to create two tempfiles with same prefix and suffix File file1 = TempFile.createTempFile("TestTempFile", ".tst"); File file2 = TempFile.createTempFile("TestTempFile", ".tst"); @@ -145,9 +141,8 @@ public class TestTempFile { assertTrue(file2.delete()); assertNotNull(file1); assertTrue(file1.delete()); - - thrown.expect(IllegalArgumentException.class); + //noinspection ConstantConditions - TempFile.setTempFileCreationStrategy(null); + assertThrows(IllegalArgumentException.class, () -> TempFile.setTempFileCreationStrategy(null)); } }