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
This commit is contained in:
Andreas Beeker 2020-08-18 13:50:31 +00:00
parent f51306457d
commit a73348fe8b
38 changed files with 1487 additions and 1646 deletions

135
build.xml
View File

@ -208,10 +208,20 @@ under the License.
<loadresource property="versionDir">
<string>@{artifact}</string>
<filterchain>
<replaceregex pattern="[^:]+:[^:]+:(.*)" replace="\1"/>
<replaceregex pattern="[^:]+:[^:]+:([^:]+).*" replace="\1"/>
</filterchain>
</loadresource>
<local name="classifier"/>
<loadresource property="classifier">
<string>@{artifact}</string>
<filterchain>
<replaceregex pattern="[^:]+:[^:]+:[^:]+:?([^:]*)" replace="\1"/>
<replaceregex pattern="(.+)" replace="-\1"/>
</filterchain>
</loadresource>
<property name="classifier" value=""/>
<local name="version"/>
<property name="version" value="${versionDir}" if:blank="@{snapshot}"/>
<property name="version" value="@{snapshot}"/>
@ -225,13 +235,23 @@ under the License.
</filterchain>
</loadresource>
<local name="jarName"/>
<property name="jarName" value="${artifactId}-${version}${classifier}.@{packaging}"/>
<!-- delete old versions -->
<delete failonerror="false">
<fileset dir="${usageDir}" excludes="${jarName}">
<filename regex="^${artifactId}-[0-9].*${classifier}\.@{packaging}"/>
</fileset>
</delete>
<local name="jarLoc"/>
<property name="jarLoc" value="${usageDir}/@{target}" unless:blank="@{target}"/>
<property name="jarLoc" value="${usageDir}/${artifactId}-${version}.@{packaging}"/>
<property name="jarLoc" value="${usageDir}/${jarName}"/>
<local name="urlLoc"/>
<property name="urlLoc" value="@{url}" unless:blank="@{url}"/>
<property name="urlLoc" value="@{repo}/${groupDir}/${artifactId}/${versionDir}/${artifactId}-${version}.@{packaging}@{query}"/>
<property name="urlLoc" value="@{repo}/${groupDir}/${artifactId}/${versionDir}/${jarName}@{query}"/>
<property name="@{prefix}.@{packaging}" value="${jarLoc}"/>
<property name="@{prefix}.url" value="${urlLoc}"/>
@ -250,50 +270,50 @@ under the License.
<dependency prefix="main.com.zaxxer" artifact="com.zaxxer:SparseBitSet:1.2" usage="main"/>
<dependency prefix="main.junit" artifact="junit:junit:4.13" usage="main-tests"/>
<dependency prefix="main.jmh" artifact="org.openjdk.jmh:jmh-core:1.19" usage="main-tests"/>
<dependency prefix="main.jmhAnnotation" artifact="org.openjdk.jmh:jmh-generator-annprocess:1.19" usage="main-tests"/>
<dependency prefix="main.hamcrest" artifact="org.hamcrest:hamcrest-core:1.3" usage="main-tests"/>
<dependency prefix="main.xmlunit" artifact="org.xmlunit:xmlunit-core:2.5.1" usage="main-tests"/>
<dependency prefix="main.mockito" artifact="org.mockito:mockito-core:3.3.3" usage="main-tests"/>
<dependency prefix="main.byte-buddy" artifact="net.bytebuddy:byte-buddy:1.10.1" usage="main-tests"/>
<dependency prefix="main.byte-buddy-agent" artifact="net.bytebuddy:byte-buddy-agent:1.10.1" usage="main-tests"/>
<dependency prefix="main.objenesis" artifact="org.objenesis:objenesis:2.6" usage="main-tests"/>
<dependency prefix="main.jmh" artifact="org.openjdk.jmh:jmh-core:1.25" usage="main-tests"/>
<dependency prefix="main.jmhAnnotation" artifact="org.openjdk.jmh:jmh-generator-annprocess:1.25" usage="main-tests"/>
<dependency prefix="main.hamcrest" artifact="org.hamcrest:hamcrest:2.2" usage="main-tests"/>
<dependency prefix="main.xmlunit" artifact="org.xmlunit:xmlunit-core:2.7.0" usage="main-tests"/>
<dependency prefix="main.mockito" artifact="org.mockito:mockito-core:3.5.0" usage="main-tests"/>
<dependency prefix="main.byte-buddy" artifact="net.bytebuddy:byte-buddy:1.10.14" usage="main-tests"/>
<dependency prefix="main.byte-buddy-agent" artifact="net.bytebuddy:byte-buddy-agent:1.10.14" usage="main-tests"/>
<dependency prefix="main.objenesis" artifact="org.objenesis:objenesis:3.1" usage="main-tests"/>
<dependency prefix="main.ant" artifact="org.apache.ant:ant:1.10.8" usage="excelant"/>
<dependency prefix="main.antlauncher" artifact="org.apache.ant:ant-launcher:1.10.8" usage="excelant"/>
<!-- xml signature libs - not part of the distribution -->
<dependency prefix="dsig.xmlsec" artifact="org.apache.santuario:xmlsec:2.1.5" usage="ooxml-provided"/>
<dependency prefix="dsig.xmlsec" artifact="org.apache.santuario:xmlsec:2.2.0" usage="ooxml-provided"/>
<dependency prefix="dsig.bouncycastle-prov" artifact="org.bouncycastle:bcprov-ext-jdk15on:1.66" usage="ooxml-provided"/>
<dependency prefix="dsig.bouncycastle-pkix" artifact="org.bouncycastle:bcpkix-jdk15on:1.66" usage="ooxml-provided"/>
<dependency prefix="dsig.slf4j-api" artifact="org.slf4j:slf4j-api:1.7.30" usage="ooxml-provided"/>
<!-- only used for signing the release - not used with the ooxml signatures -->
<dependency prefix="dsig.bouncycastle-bcpg" artifact="org.bouncycastle:bcpg-jdk15on:1.66" usage="util"/>
<!-- svg/batik libs - not part of the distribution -->
<dependency prefix="svg.xml-apis-ext" artifact="xml-apis:xml-apis-ext:1.3.04" usage="ooxml-provided"/>
<dependency prefix="svg.xmlgraphics-commons" artifact="org.apache.xmlgraphics:xmlgraphics-commons:2.3" usage="ooxml-provided"/>
<dependency prefix="svg.batik-all" artifact="org.apache.xmlgraphics:batik-all:1.12" usage="ooxml-provided"/>
<dependency prefix="svg.xmlgraphics-commons" artifact="org.apache.xmlgraphics:xmlgraphics-commons:2.4" usage="ooxml-provided"/>
<dependency prefix="svg.batik-all" artifact="org.apache.xmlgraphics:batik-all:1.13" usage="ooxml-provided"/>
<!-- jars in the ooxml-lib directory, see the fetch-ooxml-jars target-->
<dependency prefix="ooxml.curvesapi" artifact="com.github.virtuald:curvesapi:1.06" usage="ooxml"/>
<dependency prefix="ooxml.xmlbeans" artifact="org.apache.xmlbeans:xmlbeans:4.0.0" usage="ooxml"
url="https://ci-builds.apache.org/job/POI/job/POI-XMLBeans-DSL-1.8/lastSuccessfulBuild/artifact/build//xmlbeans-4.0.0.jar"/>
<dependency prefix="ooxml.commons-compress" artifact="org.apache.commons:commons-compress:1.20" usage="ooxml"/>
<!-- only used for compiling xmlbeans schemas -->
<!-- <dependency prefix="ooxml.commons-compress" artifact="com.github.javaparser:javaparser-core:3.16.1" usage="ooxml-provided"/>-->
<!-- jars in the ooxml-test-lib directory, see the fetch-ooxml-jars target-->
<dependency prefix="ooxml.test.reflections" artifact="org.reflections:reflections:0.9.11" usage="ooxml-tests"/>
<dependency prefix="ooxml.test.reflections" artifact="org.reflections:reflections:0.9.12" usage="ooxml-tests"/>
<dependency prefix="ooxml.test.guava" artifact="com.google.guava:guava:29.0-jre" usage="ooxml-tests"/>
<dependency prefix="ooxml.test.javassist" artifact="org.javassist:javassist:3.21.0-GA" usage="ooxml-tests"/>
<dependency prefix="ooxml.test.javassist" artifact="org.javassist:javassist:3.27.0-GA" usage="ooxml-tests"/>
<!-- coverage libs -->
<dependency prefix="jacoco" artifact="org.jacoco:jacoco:0.8.5" usage="util" packaging="zip"/>
<dependency prefix="asm" artifact="org.ow2.asm:asm:8.0.1" usage="util"/>
<dependency prefix="asm-commons" artifact="org.ow2.asm:asm-commons:8.0.1" usage="util"/>
<dependency prefix="asm-tree" artifact="org.ow2.asm:asm-tree:8.0.1" usage="util"/>
<dependency prefix="asm" artifact="org.ow2.asm:asm:9.0-beta" usage="util"/>
<dependency prefix="asm-commons" artifact="org.ow2.asm:asm-commons:9.0-beta" usage="util"/>
<dependency prefix="asm-tree" artifact="org.ow2.asm:asm-tree:9.0-beta" usage="util"/>
<!-- license and api checks -->
<dependency prefix="rat" artifact="org.apache.rat:apache-rat:0.12" usage="util"/>
<dependency prefix="rat" artifact="org.apache.rat:apache-rat:0.13" usage="util"/>
<dependency prefix="forbidden" artifact="de.thetaphi:forbiddenapis:3.0.1" usage="util"/>
<property name="maven.ooxml.xsds.version.id" value="1.5"/>
@ -332,23 +352,30 @@ under the License.
<property name="halt.on.test.failure" value="true"/>
<!-- helper jars for pgp signing, building and nexus staging -->
<dependency prefix="dist.bouncycastle-prov" artifact="org.bouncycastle:bcprov-ext-jdk15on:1.65" usage="util"/>
<dependency prefix="dist.bouncycastle-prov" artifact="org.bouncycastle:bcpg-jdk15on:1.65" usage="util"/>
<dependency prefix="dist.commons-openpgp" artifact="org.apache.commons:commons-openpgp:1.0-SNAPSHOT" usage="util"
repo="https://repository.apache.org/content/groups/snapshots" snapshot="1.0-20190121.221905-12"/>
<dependency prefix="dist.nexus-staging" artifact="org.sonatype.nexus.ant:nexus-staging-ant-tasks:1.6.3-uber" usage="util"/>
<dependency prefix="dist.nexus-staging" artifact="org.sonatype.nexus.ant:nexus-staging-ant-tasks:1.6.3:uber" usage="util"/>
<!-- jars required for maven helper targets -->
<dependency prefix="maven.ant" artifact="org.apache.maven:maven-ant-tasks:2.1.3" usage="util"/>
<!-- subclipse.tigris.org is gone - left-over is hosted at https://bintray.com/openmeetings/maven/org.tigris.subclipse.svnant -->
<!-- request will be forwarded to d29vzk4ow07wi7.cloudfront.net which is an Atlassian Marketplace instance -->
<dependency prefix="dist.svnant" artifact="org.tigris.subclipse:svnant:1.3.1" usage="util"
repo="https://dl.bintray.com/openmeetings/maven"/>
<dependency prefix="dist.svnclient" artifact="org.tigris.subclipse:svnclientadapter:1.3.1" usage="util"
repo="https://dl.bintray.com/openmeetings/maven"/>
<dependency prefix="dist.svnkit" artifact="org.tmatesoft.svnkit:svnkit:1.8.11" usage="util"/>
<dependency prefix="dist.svnkit-javahl16" artifact="org.tmatesoft.svnkit:svnkit-javahl16:1.8.11" usage="util"/>
<dependency prefix="dist.sqljet" artifact="org.tmatesoft.sqljet:sqljet:1.1.10" usage="util"/>
<!-- hosted at https://bintray.com/subclipse/maven/svnclientadapter - https://github.com/subclipse/svnclientadapter -->
<dependency prefix="dist.svnclientadapter-base" artifact="org.tigris.svnclientadapter:adapter-base:1.12.0" usage="util"
repo="https://dl.bintray.com/subclipse/maven"/>
<dependency prefix="dist.svnclientadapter-svnkit" artifact="org.tigris.svnclientadapter:adapter-svnkit:1.12.0" usage="util"
repo="https://dl.bintray.com/subclipse/maven"/>
<dependency prefix="dist.svnclientadapter-javahl" artifact="org.tigris.svnclientadapter:adapter-javahl:1.12.0" usage="util"
repo="https://dl.bintray.com/subclipse/maven"/>
<dependency prefix="dist.svnkit" artifact="org.tmatesoft.svnkit:svnkit:1.10.1" usage="util"/>
<dependency prefix="dist.svnkit-javahl16" artifact="org.tmatesoft.svnkit:svnkit-javahl16:1.10.1" usage="util"/>
<dependency prefix="dist.sqljet" artifact="org.tmatesoft.sqljet:sqljet:1.1.13" usage="util"/>
<dependency prefix="dist.antlr" artifact="org.antlr:antlr-runtime:3.5.2" usage="util"/>
<dependency prefix="dist.sequence-library" artifact="de.regnis.q.sequence:sequence-library:1.0.3" usage="util"/>
<dependency prefix="dist.sequence-library" artifact="de.regnis.q.sequence:sequence-library:1.0.4" usage="util"/>
<propertyset id="junit.properties">
@ -560,29 +587,9 @@ under the License.
<delete dir="compile-lib" failonerror="false"/>
<delete dir="ooxml-lib" failonerror="false"/>
<delete dir="ooxml-testlib" failonerror="false"/>
<delete verbose="true" failonerror="false">
<fileset dir="${basedir}/lib" includes="*.jar"/>
<fileset dir="${basedir}/lib/main-tests">
<include name="mockito-core-3.2.4.jar"/>
</fileset>
<fileset dir="${basedir}/lib/ooxml">
<include name="xmlbeans-3.1.0.jar"/>
</fileset>
<fileset dir="${basedir}/lib/ooxml-provided">
<include name="bcpkix-jdk15on-1.65.jar"/>
<include name="bcprov-ext-jdk15on-1.65.jar"/>
</fileset>
<fileset dir="${basedir}/lib/ooxml-tests">
<include name="guava-20.0.jar"/>
</fileset>
<fileset dir="${basedir}/lib/util">
<include name="asm*7.2.jar"/>
<include name="forbiddenapis-2.6.jar"/>
</fileset>
<fileset dir="${basedir}/lib/excelant">
<include name="ant*1.10.1.jar"/>
</fileset>
<delete dir="${basedir}/lib" includes="*.jar" failonerror="false"/>
<delete>
<fileset dir="lib/main-tests" includes="hamcrest-core*"/>
</delete>
<condition property="jars.present">
@ -694,12 +701,15 @@ under the License.
<downloadfile src="${svg.xml-apis-ext.url}" dest="${svg.xml-apis-ext.jar}"/>
<downloadfile src="${svg.xmlgraphics-commons.url}" dest="${svg.xmlgraphics-commons.jar}"/>
</target>
<target name="check-svn-jars">
<condition property="svn.jars.present">
<or>
<and>
<available file="${dist.svnant.jar}"/>
<available file="${dist.svnclient.jar}"/>
<available file="${dist.svnclientadapter-base.jar}"/>
<available file="${dist.svnclientadapter-svnkit.jar}"/>
<available file="${dist.svnclientadapter-javahl.jar}"/>
<available file="${dist.svnkit.jar}"/>
<available file="${dist.svnkit-javahl16.jar}"/>
<available file="${dist.sqljet.jar}"/>
@ -712,7 +722,9 @@ under the License.
</target>
<target name="fetch-svn-jars" depends="check-svn-jars" unless="svn.jars.present">
<downloadfile src="${dist.svnant.url}" dest="${dist.svnant.jar}"/>
<downloadfile src="${dist.svnclient.url}" dest="${dist.svnclient.jar}"/>
<downloadfile src="${dist.svnclientadapter-base.url}" dest="${dist.svnclientadapter-base.jar}"/>
<downloadfile src="${dist.svnclientadapter-svnkit.url}" dest="${dist.svnclientadapter-svnkit.jar}"/>
<downloadfile src="${dist.svnclientadapter-javahl.url}" dest="${dist.svnclientadapter-javahl.jar}"/>
<downloadfile src="${dist.svnkit.url}" dest="${dist.svnkit.jar}"/>
<downloadfile src="${dist.svnkit-javahl16.url}" dest="${dist.svnkit-javahl16.jar}"/>
<downloadfile src="${dist.sqljet.url}" dest="${dist.sqljet.jar}"/>
@ -2475,15 +2487,14 @@ under the License.
<fixcrlf srcDir="${dist.dir}" includes="**/*.md5,**/*.sha1,**/*.sha256,**/*.sha512" eol="unix"/>
<downloadfile src="${dist.bouncycastle-prov.url}" dest="${dist.bouncycastle-prov.jar}"/>
<downloadfile src="${dist.bouncycastle-bcpg.url}" dest="${dist.bouncycastle-bcpg.jar}"/>
<downloadfile src="${dsig.bouncycastle-bcpg.url}" dest="${dsig.bouncycastle-bcpg.jar}"/>
<downloadfile src="${dist.commons-openpgp.url}" dest="${dist.commons-openpgp.jar}"/>
<taskdef resource="org/apache/commons/openpgp/ant/antlib.xml" uri="antlib:org.apache.commons.openpgp.ant">
<classpath>
<pathelement path="${dist.commons-openpgp.jar}"/>
<pathelement path="${dist.bouncycastle-prov.jar}"/>
<pathelement path="${dist.bouncycastle-bcpg.jar}"/>
<pathelement path="${dsig.bouncycastle-prov.jar}"/>
<pathelement path="${dsig.bouncycastle-bcpg.jar}"/>
</classpath>
</taskdef>
@ -2592,7 +2603,9 @@ under the License.
<path id="path.svnant">
<pathelement location="${dist.svnant.jar}"/>
<pathelement location="${dist.svnclient.jar}"/>
<pathelement location="${dist.svnclientadapter-base.jar}"/>
<pathelement location="${dist.svnclientadapter-svnkit.jar}"/>
<pathelement location="${dist.svnclientadapter-javahl.jar}"/>
<pathelement location="${dist.svnkit.jar}"/>
<pathelement location="${dist.svnkit-javahl16.jar}"/>
<pathelement location="${dist.sqljet.jar}"/>

View File

@ -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();
}

View File

@ -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");
}

View File

@ -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");
}
}

View File

@ -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;

View File

@ -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<FileInputStream, POITextExtractor> poifsIS, final boolean loadOOXML)
@ -199,17 +198,6 @@ public class TestExtractorFactory {
}
}
private void testInvalid(FunctionEx<FileInputStream, POITextExtractor> 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);
}
}

View File

@ -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);
}
/**

View File

@ -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");
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"
);
}
private void handleNonOOXML(String file, Class<? extends UnsupportedFileFormatException> 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_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");
}
}
@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");
}
}
@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<Long,Double> ratioCon) throws IOException {
@ -1121,42 +1067,6 @@ public final class TestPackage {
}
}
@SuppressWarnings("SameParameterValue")
private static <T extends Throwable> AnyCauseMatcher<T> getCauseMatcher(Class<T> 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<T extends Throwable> extends TypeSafeMatcher<T> {
private final Class<T> expectedType;
private final String expectedMessage;
AnyCauseMatcher(Class<T> 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 {

View File

@ -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();

View File

@ -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<ArrayComparisonFailure>);
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

View File

@ -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());
}
}

View File

@ -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

View File

@ -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<String,Class<? extends Throwable>> EXCLUDED =
new HashMap<>();
@ -112,24 +108,29 @@ public abstract class BasePPTIteratingTest {
@Test
public void testAllFiles() throws Exception {
String fileName = file.getName();
Class<? extends Throwable> 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<String> getFailedEncryptedFiles() {
return ENCRYPTED_FILES;
}
protected Set<String> getFailedOldFiles() {
return OLD_FILES;
}
}

View File

@ -16,14 +16,16 @@
==================================================================== */
package org.apache.poi.hslf.dev;
import static org.junit.Assert.assertThrows;
import java.io.File;
import java.util.Collections;
import java.util.Set;
import org.apache.poi.EmptyFileException;
import org.apache.poi.hslf.HSLFTestDataSamples;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.fail;
public class TestPPTXMLDump extends BasePPTIteratingTest {
@Test
public void testMain() throws Exception {
@ -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<String> getFailedEncryptedFiles() {
return Collections.emptySet();
}
@Override
protected Set<String> getFailedOldFiles() {
return Collections.emptySet();
}
}

View File

@ -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<String> 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<String> getFailedEncryptedFiles() {
return Collections.emptySet();
}
@Override
protected Set<String> getFailedOldFiles() {
return Collections.emptySet();
}
}

View File

@ -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(),
});

View File

@ -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;

View File

@ -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;

View File

@ -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<String,Class<? extends Throwable>> EXCLUDED =
new HashMap<>();
protected static final Map<String,Class<? extends Throwable>> EXCLUDED = new HashMap<>();
@Parameters(name="{index}: {0}")
public static Iterable<Object[]> 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);
}
Class<? extends Throwable> t = EXCLUDED.get(fileName);
if (t == null) {
runOneFile(file);
} else {
assertThrows(t, () -> runOneFile(file));
}
throw e;
}
}
abstract void runOneFile(File pFile) throws Exception;

View File

@ -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"));
// }
}

View File

@ -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());
}
}

View File

@ -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.

View File

@ -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());
}
/**

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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

View File

@ -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"));
}
}

View File

@ -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"));
}
}
}

View File

@ -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"));
}
}

View File

@ -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;

View File

@ -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());
}
}

View File

@ -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();
try (Workbook wb = createWorkbook()) {
// The stability classifier is useful to reduce memory consumption of caching logic
IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1;
// The stability classifier is useful to reduce memory consumption of caching logic
IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1;
ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null);
ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null);
ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null);
ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null);
// fe1 and fe2 can be used concurrently on separate threads
// fe1 and fe2 can be used concurrently on separate threads
fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0));
fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1));
fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0));
fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1));
fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2));
fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0));
fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2));
fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0));
NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
assertNotNull(eval1);
assertEquals(18.9, eval1.getNumberValue(), 0.0);
NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0);
assertNotNull(eval2);
assertEquals(4.0, eval2.getNumberValue(), 0.0);
fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0));
eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
assertNotNull(eval1);
assertEquals(13.9, eval1.getNumberValue(), 0.0);
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());
}
}
}

View File

@ -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());
}
}

View File

@ -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));

File diff suppressed because it is too large Load Diff

View File

@ -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");
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));
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);
// 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();
// 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());
}
}

View File

@ -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"));
}
}

View File

@ -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));
}
}