#65026 - Migrate tests to Junit 5

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1884783 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2020-12-24 18:42:29 +00:00
parent fb012041e8
commit a0fa9e19b1
1010 changed files with 16265 additions and 20726 deletions

271
build.xml
View File

@ -96,7 +96,7 @@ under the License.
<attribute name="value"/>
<sequential>
<mkdir dir="build/poi-ant-contrib"/>
<javac srcdir="src/excelant/poi-ant-contrib" destdir="build/poi-ant-contrib" includeantruntime="true"/>
<javac srcdir="src/excelant/poi-ant-contrib" destdir="build/poi-ant-contrib" includeantruntime="true" excludes="Junit5Progress.java"/>
<taskdef name="PropertyResetHelper" classname="PropertyReset" classpath="build/poi-ant-contrib"/>
<PropertyResetHelper name="@{name}" value="@{value}" />
</sequential>
@ -271,7 +271,16 @@ under the License.
<dependency prefix="main.com.zaxxer" artifact="com.zaxxer:SparseBitSet:1.2" usage="main"/>
<dependency prefix="main.slf4j-api" artifact="org.slf4j:slf4j-api:1.7.30" usage="main"/>
<dependency prefix="main.junit" artifact="junit:junit:4.13.1" usage="main-tests"/>
<dependency prefix="main.junit-api" artifact="org.junit.jupiter:junit-jupiter-api:5.7.0" usage="main-tests"/>
<dependency prefix="main.junit-jengine" artifact="org.junit.jupiter:junit-jupiter-engine:5.7.0" usage="main-tests"/>
<dependency prefix="main.junit-params" artifact="org.junit.jupiter:junit-jupiter-params:5.7.0" usage="main-tests"/>
<dependency prefix="main.junit-opentest4j" artifact="org.opentest4j:opentest4j:1.2.0" usage="main-tests"/>
<dependency prefix="main.junit-apiguardian" artifact="org.apiguardian:apiguardian-api:1.1.0" usage="main-tests"/>
<dependency prefix="main.junit-pcommons" artifact="org.junit.platform:junit-platform-commons:1.7.0" usage="main-tests"/>
<dependency prefix="main.junit-pengine" artifact="org.junit.platform:junit-platform-engine:1.7.0" usage="main-tests"/>
<dependency prefix="main.junit-plauncher" artifact="org.junit.platform:junit-platform-launcher:1.7.0" usage="main-tests"/>
<dependency prefix="main.jmh" artifact="org.openjdk.jmh:jmh-core:1.26" usage="main-tests"/>
<dependency prefix="main.jmhAnnotation" artifact="org.openjdk.jmh:jmh-generator-annprocess:1.26" usage="main-tests"/>
<dependency prefix="main.hamcrest" artifact="org.hamcrest:hamcrest:2.2" usage="main-tests"/>
@ -409,7 +418,14 @@ under the License.
<!-- some libraries should only be required for compiling/running tests -->
<path id="test.jar.classpath">
<pathelement location="${main.junit.jar}"/>
<pathelement location="${main.junit-api.jar}"/>
<pathelement location="${main.junit-jengine.jar}"/>
<pathelement location="${main.junit-params.jar}"/>
<pathelement location="${main.junit-plauncher.jar}"/>
<pathelement location="${main.junit-pengine.jar}"/>
<pathelement location="${main.junit-pcommons.jar}"/>
<pathelement location="${main.junit-opentest4j.jar}"/>
<pathelement location="${main.junit-apiguardian.jar}"/>
<pathelement location="${main.jmh.jar}"/>
<pathelement location="${main.jmhAnnotation.jar}"/>
<pathelement location="${main.hamcrest.jar}"/>
@ -507,9 +523,9 @@ under the License.
</path>
<patternset id="exclude-scratchpad-test">
<exclude name="**/TestExtractorFactory.java"/>
<exclude name="**/TestEmbedOLEPackage.java"/>
<exclude name="**/TestHxxFEncryption.java"/>
<exclude name="**/TestExtractorFactory.class"/>
<exclude name="**/TestEmbedOLEPackage.class"/>
<exclude name="**/TestHxxFEncryption.class"/>
</patternset>
<!-- Prints POI's Ant usage help -->
@ -611,6 +627,7 @@ under the License.
<include name="mockito-core-3.2*.jar"/>
<include name="mockito-core-3.5*.jar"/>
<include name="hamcrest-core*"/>
<include name="junit-4*.jar"/>
</fileset>
<fileset dir="${basedir}/lib/ooxml">
<include name="xmlbeans-3.1.0.jar"/>
@ -640,7 +657,14 @@ under the License.
<and>
<available file="${main.commons-logging.jar}"/>
<available file="${main.commons-codec.jar}"/>
<available file="${main.junit.jar}"/>
<available file="${main.junit-api.jar}"/>
<available file="${main.junit-jengine.jar}"/>
<available file="${main.junit-params.jar}"/>
<available file="${main.junit-plauncher.jar}"/>
<available file="${main.junit-pengine.jar}"/>
<available file="${main.junit-pcommons.jar}"/>
<available file="${main.junit-opentest4j.jar}"/>
<available file="${main.junit-apiguardian.jar}"/>
<available file="${main.jmh.jar}"/>
<available file="${main.jmhAnnotation.jar}"/>
<available file="${main.hamcrest.jar}"/>
@ -679,7 +703,14 @@ under the License.
<mkdir dir="${main.lib}"/>
<downloadfile src="${main.commons-logging.url}" dest="${main.commons-logging.jar}"/>
<downloadfile src="${main.commons-codec.url}" dest="${main.commons-codec.jar}"/>
<downloadfile src="${main.junit.url}" dest="${main.junit.jar}"/>
<downloadfile src="${main.junit-api.url}" dest="${main.junit-api.jar}"/>
<downloadfile src="${main.junit-jengine.url}" dest="${main.junit-jengine.jar}"/>
<downloadfile src="${main.junit-params.url}" dest="${main.junit-params.jar}"/>
<downloadfile src="${main.junit-plauncher.url}" dest="${main.junit-plauncher.jar}"/>
<downloadfile src="${main.junit-pengine.url}" dest="${main.junit-pengine.jar}"/>
<downloadfile src="${main.junit-pcommons.url}" dest="${main.junit-pcommons.jar}"/>
<downloadfile src="${main.junit-opentest4j.url}" dest="${main.junit-opentest4j.jar}"/>
<downloadfile src="${main.junit-apiguardian.url}" dest="${main.junit-apiguardian.jar}"/>
<downloadfile src="${main.jmh.url}" dest="${main.jmh.jar}"/>
<downloadfile src="${main.jmhAnnotation.url}" dest="${main.jmhAnnotation.jar}"/>
<downloadfile src="${main.hamcrest.url}" dest="${main.hamcrest.jar}"/>
@ -1147,6 +1178,9 @@ under the License.
<attribute name="showoutput" default="false"/>
<attribute name="jacocodest" default="build/jacoco-dest.exec"/>
<attribute name="modulepath-ref"/>
<attribute name="module1" default=""/>
<attribute name="module2" default=""/>
<attribute name="outputDir"/>
<element name="elements" implicit="true"/>
<sequential>
<local name="no.jit.sherlock"/>
@ -1166,6 +1200,23 @@ under the License.
</filterchain>
</loadresource>
<path id="junit-jars">
<pathelement location="${main.junit-api.jar}"/>
<pathelement location="${main.junit-jengine.jar}"/>
<pathelement location="${main.junit-params.jar}"/>
<pathelement location="${main.junit-opentest4j.jar}"/>
<pathelement location="${main.junit-apiguardian.jar}"/>
<pathelement location="${main.junit-pcommons.jar}"/>
<pathelement location="${main.junit-pengine.jar}"/>
<pathelement location="${main.junit-plauncher.jar}"/>
</path>
<mkdir dir="build/poi-ant-contrib"/>
<javac srcdir="src/excelant/poi-ant-contrib" destdir="build/poi-ant-contrib"
includeantruntime="true" includes="Junit5Progress.java" classpathref="junit-jars"/>
<local name="ooxml.lite.agent.exists"/>
<available property="ooxml.lite.agent.exists" file="${ooxml.lite.agent}"/>
@ -1179,32 +1230,64 @@ under the License.
</filtermapper>
</pathconvert>
<jacoco:coverage enabled="${coverage.enabled}" excludes="${coverage.excludes}" destfile="@{jacocodest}">
<junit printsummary="yes" fork="yes" forkmode="once" haltonfailure="${halt.on.test.failure}"
failureproperty="@{failureproperty}" showoutput="@{showoutput}" filtertrace="off">
<syspropertyset refid="junit.properties"/>
<sysproperty key="java.io.tmpdir" value="${tempdir}"/>
<jvmarg value="-Xmx@{heap}M"/>
<jvmarg value="-ea"/>
<local name="use_module1"/>
<local name="use_module2"/>
<condition property="use_module1" value="true" unless:true="${isJava8}">
<length string="@{module1}" when="greater" length="0"/>
</condition>
<condition property="use_module2" value="true" unless:true="${isJava8}">
<length string="@{module2}" when="greater" length="0"/>
</condition>
<!-- some "add-opens" and other properties are needed when running with Java 9 or newer -->
<sysproperty key="sun.reflect.debugModuleAccessChecks" value="true" if:true="${addOpens}" />
<sysproperty key="com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize" value="true" if:true="${addOpens}" />
<jvmarg value="--illegal-access=warn" if:true="${addOpens}" />
<jvmarg value="-javaagent:${ooxml.lite.agent}=${ooxml.lite.report}|${ooxml.lite.includes}" if:true="${ooxml.lite.agent.exists}"/>
<delete file="build/status-as-tests-run.txt" failonerror="false"/>
<!-- jvmarg value="-Duser.timezone=UTC"/ -->
<jvmarg value="${file.leak.detector}" />
<jvmarg value="-Xjit:verbose={compileStart|compileEnd},vlog=build/jit.log${no.jit.sherlock}" if:true="${isIBMVM}"/>
<formatter type="plain"/>
<formatter type="xml"/>
<modulepath refid="@{modulepath-ref}" unless:true="${isJava8}"/>
<classpath if:true="${isJava8}">
<fileset dir="${basedir}" includes="${cp_java}"/>
</classpath>
<!-- As of 2018, JaCoCo is managing expectations and stay on Java 5 and therefore don't support junitlauncher -->
<!-- https://github.com/jacoco/jacoco/issues/673 ... m( -->
<jacoco:agent property="jacocoagent" enabled="${coverage.enabled}" excludes="${coverage.excludes}" destfile="@{jacocodest}"/>
<junitlauncher printsummary="false" haltonfailure="${halt.on.test.failure}" failureproperty="@{failureproperty}">
<classpath>
<path refid="junit-jars" if:true="${isJava8}"/>
<fileset dir="${basedir}" includes="${cp_java}" if:true="${isJava8}"/>
<pathelement location="build/poi-ant-contrib"/>
</classpath>
<testclasses outputDir="@{outputDir}">
<fork>
<syspropertyset refid="junit.properties"/>
<sysproperty key="java.io.tmpdir" value="${tempdir}"/>
<jvmarg value="-Xmx@{heap}M"/>
<jvmarg value="-ea"/>
<!-- some "add-opens" and other properties are needed when running with Java 9 or newer -->
<sysproperty key="sun.reflect.debugModuleAccessChecks" value="true" if:true="${addOpens}" />
<sysproperty key="com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize" value="true" if:true="${addOpens}" />
<jvmarg value="--illegal-access=warn" if:true="${addOpens}" />
<jvmarg value="-javaagent:${ooxml.lite.agent}=${ooxml.lite.report}|${ooxml.lite.includes}" if:true="${ooxml.lite.agent.exists}"/>
<jvmarg line="${jacocoagent}"/>
<!-- jvmarg value="-Duser.timezone=UTC"/ -->
<jvmarg value="${file.leak.detector}" />
<jvmarg value="-Xjit:verbose={compileStart|compileEnd},vlog=build/jit.log${no.jit.sherlock}" if:true="${isIBMVM}"/>
<modulepath refid="@{modulepath-ref}" unless:true="${isJava8}"/>
<jvmarg line="--add-modules org.junit.platform.launcher" unless:true="${isJava8}"/>
<jvmarg line="--add-modules org.junit.jupiter.params" unless:true="${isJava8}"/>
<jvmarg line="--add-modules org.apache.poi.@{module1}" if:set="use_module1"/>
<jvmarg line="--add-modules org.apache.poi.@{module2}" if:set="use_module2"/>
</fork>
<listener type="legacy-plain" sendSysOut="true" outputDir="@{outputDir}"/>
<listener type="legacy-xml" sendSysOut="true" sendSysErr="true" outputDir="@{outputDir}"/>
<listener classname="Junit5Progress"/>
<elements/>
</junit>
</jacoco:coverage>
</testclasses>
</junitlauncher>
<loadfile property="contents" srcFile="build/status-as-tests-run.txt" />
<echo message="${contents}" />
</sequential>
</macrodef>
@ -1222,20 +1305,16 @@ under the License.
<pathelement path="lib/ooxml-tests"/>
</path>
<poiunit failureproperty="ooxml.test.failed" heap="768"
modulepath-ref="restest.modules">
<jvmarg line="--add-modules org.apache.poi.ooxml" unless:true="${isJava8}"/>
<jvmarg line="--add-modules org.apache.poi.scratchpad" unless:true="${isJava8}"/>
<batchtest todir="${ooxml.reports.test}">
<fileset dir="${ooxml.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/TestUnfixedBugs.java"/>
<exclude name="**/All*Tests.java"/>
<exclude name="**/TestSignatureInfo.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
<poiunit failureproperty="ooxml.test.failed" heap="768" modulepath-ref="restest.modules"
module1="ooxml" module2="scratchpad" outputDir="${ooxml.reports.test}">
<zipfileset src="build/dist/maven/poi-ooxml-tests/poi-ooxml-${version.id}-tests.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/TestUnfixedBugs.class"/>
<exclude name="**/All*Tests.class"/>
<exclude name="**/TestSignatureInfo.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
</target>
@ -1461,19 +1540,15 @@ under the License.
</path>
<poiunit failureproperty="main.test.failed" heap="256" showoutput="true" jacocodest="build/jacoco-main.exec"
modulepath-ref="test-main.modules">
<jvmarg line="--add-modules org.apache.poi.poi" unless:true="${isJava8}"/>
<batchtest todir="${main.reports.test}">
<fileset dir="${main.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/All*Tests.java"/>
<exclude name="**/TestUnfixedBugs.java"/>
<exclude name="**/TestcaseRecordInputStream.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
modulepath-ref="test-main.modules" module1="poi" outputDir="${main.reports.test}">
<zipfileset src="build/dist/maven/poi-tests/poi-${version.id}-tests.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/All*Tests.class"/>
<exclude name="**/TestUnfixedBugs.class"/>
<exclude name="**/TestcaseRecordInputStream.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
<delete file="${main.testokfile}"/>
@ -1521,17 +1596,13 @@ under the License.
</path>
<poiunit failureproperty="scratchpad.test.failed" heap="512" jacocodest="build/jacoco-scratchpad.exec"
modulepath-ref="test-scratchpad.modules">
<jvmarg line="--add-modules org.apache.poi.scratchpad" unless:true="${isJava8}"/>
<batchtest todir="${scratchpad.reports.test}">
<fileset dir="${scratchpad.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/AllTests.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
modulepath-ref="test-scratchpad.modules" module1="scratchpad" outputDir="${scratchpad.reports.test}">
<zipfileset src="build/dist/maven/poi-scratchpad-tests/poi-scratchpad-${version.id}-tests.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/All*Tests.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
<delete file="${scratchpad.testokfile}"/>
<antcall target="-test-scratchpad-write-testfile"/>
@ -1554,19 +1625,14 @@ under the License.
<attribute name="type"/>
<sequential>
<poiunit failureproperty="ooxml.test.failed" heap="768" jacocodest="build/jacoco-@{type}.exec"
modulepath-ref="@{modulepath-ref}">
<jvmarg line="--add-modules org.apache.poi.ooxml" unless:true="${isJava8}"/>
<jvmarg line="--add-modules org.apache.poi.scratchpad" unless:true="${isJava8}"/>
<batchtest todir="${ooxml.reports.test}">
<fileset dir="${ooxml.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/TestUnfixedBugs.java"/>
<exclude name="**/All*Tests.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
modulepath-ref="@{modulepath-ref}" module1="ooxml" module2="scratchpad" outputDir="${ooxml.reports.test}">
<zipfileset src="build/dist/maven/poi-ooxml-tests/poi-ooxml-${version.id}-tests.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/All*Tests.class"/>
<exclude name="**/TestUnfixedBugs.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
</sequential>
</macrodef>
@ -1622,16 +1688,12 @@ under the License.
</path>
<poiunit failureproperty="integration.test.failed" heap="1512" showoutput="true" jacocodest="build/jacoco-integration.exec"
modulepath-ref="test-integration.modules">
<jvmarg line="--add-modules org.apache.poi.stress" unless:true="${isJava8}"/>
<batchtest todir="${integration.reports.test}">
<fileset dir="${integration.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
modulepath-ref="test-integration.modules" module1="stress" outputDir="${integration.reports.test}">
<zipfileset src="build/dist/maven/poi-integration/poi-integration-${version.id}.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
<delete file="${integration.testokfile}"/>
<antcall target="-test-integration-write-testfile"/>
@ -1810,16 +1872,12 @@ org/apache/poi/schemas/ooxml/system/ooxml/rectaf36doctype.xsb
</path>
<poiunit failureproperty="excelant.test.failed" jacocodest="build/jacoco-excelant.exec"
modulepath-ref="test-excelant.modules">
<jvmarg line="--add-modules org.apache.poi.excelant" unless:true="${isJava8}"/>
<batchtest todir="${excelant.reports.test}">
<fileset dir="${excelant.src.test}">
<include name="**/${testpattern}.java"/>
<exclude name="**/${testexcludepattern}.java"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</fileset>
</batchtest>
modulepath-ref="test-excelant.modules" module1="excelant" outputDir="${excelant.reports.test}">
<zipfileset src="build/dist/maven/poi-excelant-tests/poi-excelant-${version.id}-tests.jar">
<include name="**/${testpattern}.class"/>
<exclude name="**/${testexcludepattern}.class"/>
<patternset refid="exclude-scratchpad-test" if:true="${scratchpad.ignore}"/>
</zipfileset>
</poiunit>
<delete file="${excelant.testokfile}"/>
<antcall target="-test-excelant-write-testfile"/>
@ -2521,7 +2579,14 @@ org/apache/poi/schemas/ooxml/system/ooxml/rectaf36doctype.xsb
<auxClasspath path="${main.commons-logging.jar}" />
<auxClasspath path="${main.slf4j-api.jar}" />
<auxClasspath path="${main.slf4j-simple.jar}" />
<auxClasspath path="${main.junit.jar}" />
<auxClasspath path="${main.junit-api.jar}" />
<auxClasspath path="${main.junit-jengine.jar}" />
<auxClasspath path="${main.junit-params.jar}" />
<auxClasspath path="${main.junit-plauncher.jar}" />
<auxClasspath path="${main.junit-pengine.jar}" />
<auxClasspath path="${main.junit-pcommons.jar}" />
<auxClasspath path="${main.junit-opentest4j.jar}" />
<auxClasspath path="${main.junit-apiguardian.jar}" />
<auxClasspath path="${main.jmh.jar}"/>
<auxClasspath path="${main.jmhAnnotation.jar}"/>
<auxClasspath path="${main.ant.jar}" />

View File

@ -96,12 +96,6 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>

View File

@ -150,12 +150,6 @@
<version>1.06</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>

View File

@ -80,7 +80,7 @@
<!-- define some of the third-party or plugin-versions globally to use the same in all modules -->
<xmlbeans.version>4.0.0</xmlbeans.version>
<junit.version>4.13.1</junit.version>
<junit.version>5.7.0</junit.version>
<xmlunit.version>2.8.0</xmlunit.version>
<mockito.version>3.6.0</mockito.version>
<maven.plugin.resources.version>3.2.0</maven.plugin.resources.version>
@ -110,13 +110,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.plugin.surefire.version}</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>${maven.plugin.surefire.version}</version>
</dependency>
</dependencies>
<configuration>
<printSummary>false</printSummary>
<systemPropertyVariables>
@ -164,8 +157,8 @@
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
@ -181,6 +174,12 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>

View File

@ -0,0 +1,114 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.Instant;
import org.junit.platform.engine.TestDescriptor.Type;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestExecutionResult.Status;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* Custom listener class for Ants junitlauncher, because it chomps the important running details
*
* @see <a href="https://www.selikoff.net/2018/07/28/ant-and-junit-5-outputting-test-duration-and-failure-to-the-log/">ant and junit 5 outputting test duration and failure to the log</a>
**/
public class Junit5Progress implements TestExecutionListener {
private StringWriter inMemoryWriter = new StringWriter();
private int numSkippedInCurrentClass;
private int numAbortedInCurrentClass;
private int numSucceededInCurrentClass;
private int numFailedInCurrentClass;
private Instant startCurrentClass;
private void resetCountsForNewClass() {
numSkippedInCurrentClass = 0;
numAbortedInCurrentClass = 0;
numSucceededInCurrentClass = 0;
numFailedInCurrentClass = 0;
startCurrentClass = Instant.now();
}
@Override
public void executionStarted(TestIdentifier testIdentifier) {
if ("[engine:junit-jupiter]".equals(testIdentifier.getParentId().orElse(""))) {
println("Ran " + testIdentifier.getLegacyReportingName());
resetCountsForNewClass();
}
}
@Override
public void executionSkipped(TestIdentifier testIdentifier, String reason) {
numSkippedInCurrentClass++;
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
if ("[engine:junit-jupiter]".equals(testIdentifier.getParentId().orElse(""))) {
int totalTestsInClass = numSucceededInCurrentClass + numAbortedInCurrentClass
+ numFailedInCurrentClass + numSkippedInCurrentClass;
Duration duration = Duration.between(startCurrentClass, Instant.now());
double numSeconds = duration.toNanos() / (double) 1_000_000_000;
String output = String.format("Tests run: %d, Failures: %d, Aborted: %d, Skipped: %d, Time elapsed: %f sec",
totalTestsInClass, numFailedInCurrentClass, numAbortedInCurrentClass,
numSkippedInCurrentClass, numSeconds);
println(output);
}
// don't count containers since looking for legacy JUnit 4 counting style
if (testIdentifier.getType() == Type.TEST) {
if (testExecutionResult.getStatus() == Status.SUCCESSFUL) {
numSucceededInCurrentClass++;
} else if (testExecutionResult.getStatus() == Status.ABORTED) {
println(" ABORTED: " + testIdentifier.getDisplayName());
numAbortedInCurrentClass++;
} else if (testExecutionResult.getStatus() == Status.FAILED) {
println(" FAILED: " + testIdentifier.getDisplayName());
numFailedInCurrentClass++;
}
}
}
private void println(String str) {
inMemoryWriter.write(str + "\n");
}
/*
* Append to file on disk since listener can't write to System.out (becuase legacy listeners enabled)
*/
private void flushToDisk() {
try (FileWriter writer = new FileWriter("build/status-as-tests-run.txt", true)) {
writer.write(inMemoryWriter.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void testPlanExecutionFinished(TestPlan testPlan) {
flushToDisk();
}
}

View File

@ -17,7 +17,7 @@
*/
package org.apache.poi.ss.excelant;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.poi.ss.usermodel.Workbook;

View File

@ -20,9 +20,9 @@ package org.apache.poi.ss.excelant;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertNotContained;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.PrintStream;
@ -30,13 +30,12 @@ import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.NullPrintStream;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* JUnit test for the ExcelAnt tasks.
@ -48,10 +47,9 @@ public class TestBuildFile {
private StringBuilder logBuffer;
private StringBuilder fullLogBuffer;
private BuildException buildException;
@Before
@BeforeEach
public void setUp() {
String filename = TestBuildFile.getDataDir() + "/../src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml";
int logLevel = Project.MSG_DEBUG;
@ -77,7 +75,7 @@ public class TestBuildFile {
* is automatically called, since it's trivial to have a
* test target depend on it.
*/
@After
@AfterEach
public void tearDown() {
if (project == null) {
/*
@ -145,7 +143,6 @@ public class TestBuildFile {
System.setErr(new NullPrintStream());
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
buildException = null;
project.executeTarget(targetName);
} finally {
System.setOut(sysOut);
@ -166,12 +163,9 @@ public class TestBuildFile {
try {
executeTarget(target);
} catch (org.apache.tools.ant.BuildException ex) {
buildException = ex;
if ((null != msg) && (!ex.getMessage().equals(msg))) {
fail("Should throw BuildException because '" + cause
+ "' with message '" + msg
+ "' (actual message '" + ex.getMessage() + "' instead)");
}
assertTrue(msg == null || ex.getMessage().equals(msg),
"Should throw BuildException because '" + cause + "' with message '" + msg + "' (actual message '" + ex.getMessage() + "' instead)"
);
return;
}
fail("Should throw BuildException because: " + cause);
@ -182,27 +176,11 @@ public class TestBuildFile {
return dataDirName == null ? "test-data" : dataDirName;
}
/**
* an output stream which saves stuff to our buffer.
*/
protected static class AntOutputStream extends java.io.OutputStream {
private StringBuilder buffer;
public AntOutputStream(StringBuilder buffer) {
this.buffer = buffer;
}
@Override
public void write(int b) {
buffer.append((char) b);
}
}
/**
* Our own personal build listener.
*/
private class AntTestListener implements BuildListener {
private int logLevel;
private final int logLevel;
/**
* Constructs a test listener which will ignore log events
@ -378,8 +356,8 @@ public class TestBuildFile {
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4.");
assertNotNull("The workbook should have been passed to the handler", MockExcelAntWorkbookHandler.workbook);
assertTrue("The handler should have been executed", MockExcelAntWorkbookHandler.executed);
assertNotNull(MockExcelAntWorkbookHandler.workbook, "The workbook should have been passed to the handler");
assertTrue(MockExcelAntWorkbookHandler.executed, "The handler should have been executed");
}
@Test

View File

@ -16,23 +16,23 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntPrecision {
private ExcelAntPrecision fixture ;
@Before
@BeforeEach
public void setUp() {
fixture = new ExcelAntPrecision() ;
}
@After
@AfterEach
public void tearDown() {
fixture = null ;
}

View File

@ -16,14 +16,14 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil;
import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntSet {
@ -35,12 +35,12 @@ public class TestExcelAntSet {
private static final String mortgageCalculatorFileName =
TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@Before
@BeforeEach
public void setUp() {
fixture = new ExcelAntSetDoubleCell() ;
}
@After
@AfterEach
public void tearDown() {
fixture = null ;
}

View File

@ -16,14 +16,14 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil;
import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntSetDoubleCell {
@ -34,14 +34,14 @@ public class TestExcelAntSetDoubleCell {
private static final String mortgageCalculatorFileName =
TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@Before
@BeforeEach
public void setUp() {
fixture = new ExcelAntSetDoubleCell() ;
util = ExcelAntWorkbookUtilFactory.getInstance(mortgageCalculatorFileName ) ;
fixture.setWorkbookUtil( util ) ;
}
@After
@AfterEach
public void tearDown() {
fixture = null ;
}

View File

@ -16,17 +16,17 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntUserDefinedFunction {
private ExcelAntUserDefinedFunctionTestHelper fixture ;
@Before
@BeforeEach
public void setUp() {
fixture = new ExcelAntUserDefinedFunctionTestHelper() ;
}

View File

@ -16,12 +16,12 @@
==================================================================== */
package org.apache.poi.ss.excelant.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntEvaluationResult {
private ExcelAntEvaluationResult fixture;
@ -33,7 +33,7 @@ public class TestExcelAntEvaluationResult {
private double delta = 2.2;
private String cellId = "testCell!$F$1";
@Before
@BeforeEach
public void setUp() {
fixture = new ExcelAntEvaluationResult(completedWithError,
passed,
@ -43,7 +43,7 @@ public class TestExcelAntEvaluationResult {
cellId);
}
@After
@AfterEach
public void tearDown() {
fixture = null;
}

View File

@ -16,12 +16,12 @@
==================================================================== */
package org.apache.poi.ss.excelant.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
@ -37,8 +37,8 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.tools.ant.BuildException;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class TestExcelAntWorkbookUtil {
@ -48,7 +48,7 @@ public class TestExcelAntWorkbookUtil {
private ExcelAntWorkbookUtilTestHelper fixture ;
@After
@AfterEach
public void tearDown() {
fixture = null ;
}
@ -62,12 +62,8 @@ public class TestExcelAntWorkbookUtil {
@Test
public void testLoadNotExistingFile() {
try {
new ExcelAntWorkbookUtilTestHelper("notexistingFile");
fail("Should catch exception here");
} catch (BuildException e) {
assertTrue(e.getMessage().contains("notexistingFile"));
}
BuildException e = assertThrows(BuildException.class, () -> new ExcelAntWorkbookUtilTestHelper("notexistingFile"));
assertTrue(e.getMessage().contains("notexistingFile"));
}
@Test
@ -215,9 +211,9 @@ public class TestExcelAntWorkbookUtil {
precision);
//System.out.println(result);
assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=false"));
assertTrue("Had:" + result, result.toString().contains("returnValue=790.79"));
assertTrue("Had:" + result, result.toString().contains("cellName='MortgageCalculator'!B4"));
assertTrue( result.toString().contains("evaluationCompletedWithError=false"), "Had:" + result );
assertTrue( result.toString().contains("returnValue=790.79"), "Had:" + result );
assertTrue( result.toString().contains("cellName='MortgageCalculator'!B4"), "Had:" + result );
assertFalse(result.toString().contains("#N/A"));
assertFalse(result.evaluationCompleteWithError());
@ -238,10 +234,10 @@ public class TestExcelAntWorkbookUtil {
precision);
//System.out.println(result);
assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=false"));
assertTrue("Had:" + result, result.toString().contains("returnValue=790.79"));
assertTrue("Had:" + result, result.toString().contains("cellName='MortgageCalculator'!B4"));
assertFalse("Should not see an error, but had:" + result, result.toString().contains("#"));
assertTrue( result.toString().contains("evaluationCompletedWithError=false"), "Had:" + result );
assertTrue( result.toString().contains("returnValue=790.79"), "Had:" + result );
assertTrue( result.toString().contains("cellName='MortgageCalculator'!B4"), "Had:" + result );
assertFalse( result.toString().contains("#"), "Should not see an error, but had:" + result );
assertFalse(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
@ -261,10 +257,10 @@ public class TestExcelAntWorkbookUtil {
precision);
System.out.println(result);
assertTrue("Had:" + result, result.toString().contains("evaluationCompletedWithError=true"));
assertTrue("Had:" + result, result.toString().contains("returnValue=0.0"));
assertTrue("Had:" + result, result.toString().contains("cellName='ErrorCell'!A1"));
assertTrue("Had:" + result, result.toString().contains("#N/A"));
assertTrue( result.toString().contains("evaluationCompletedWithError=true"), "Had:" + result );
assertTrue( result.toString().contains("returnValue=0.0"), "Had:" + result );
assertTrue( result.toString().contains("cellName='ErrorCell'!A1"), "Had:" + result );
assertTrue( result.toString().contains("#N/A"), "Had:" + result );
assertTrue(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
@ -301,14 +297,9 @@ public class TestExcelAntWorkbookUtil {
public void testSetNotExistingSheet() {
String cell = "'NotexistingSheet'!C14" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
try {
fixture.setStringValue(cell, "some");
fail("Should catch exception here");
} catch (BuildException e) {
assertTrue(e.getMessage().contains("NotexistingSheet"));
}
fixture = new ExcelAntWorkbookUtilTestHelper(mortgageCalculatorFileName);
BuildException e = assertThrows(BuildException.class, () -> fixture.setStringValue(cell, "some"));
assertTrue(e.getMessage().contains("NotexistingSheet"));
}
@Test

View File

@ -16,11 +16,11 @@
==================================================================== */
package org.apache.poi.ss.excelant.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.poi.ss.excelant.TestBuildFile;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**

View File

@ -16,10 +16,10 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.File;
import java.io.FileInputStream;
@ -90,20 +90,20 @@ public abstract class AbstractFileHandler implements FileHandler {
String fileAndParentName = file.getParentFile().getName() + "/" + file.getName();
try {
extractor = ExtractorFactory.createExtractor(file);
assertNotNull("Should get a POITextExtractor but had none for file " + file, extractor);
assertNotNull(extractor, "Should get a POITextExtractor but had none for file " + file);
assertNotNull("Should get some text but had none for file " + file, extractor.getText());
assertNotNull(extractor.getText(), "Should get some text but had none for file " + file);
// also try metadata
@SuppressWarnings("resource")
POITextExtractor metadataExtractor = extractor.getMetadataTextExtractor();
assertNotNull(metadataExtractor.getText());
assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName));
assertFalse(EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName),
"Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!");
assertEquals("File should not be modified by extractor", length, file.length());
assertEquals("File should not be modified by extractor", modified, file.lastModified());
assertEquals(length, file.length(), "File should not be modified by extractor");
assertEquals(modified, file.lastModified(), "File should not be modified by extractor");
handleExtractingAsStream(file);

View File

@ -16,7 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.BufferedInputStream;
import java.io.File;
@ -28,7 +29,6 @@ import java.util.zip.ZipException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.OldFileFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.junit.Assume;
/**
* This class is used for mass-regression testing via a
@ -49,7 +49,7 @@ public class BaseIntegrationTest {
}
public void test() throws Exception {
assertNotNull("Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file), handler);
assertNotNull( handler, "Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file) );
testOneFile(new File(rootDir, file));
}
@ -61,14 +61,14 @@ public class BaseIntegrationTest {
handleWrongOLE2XMLExtension(inputFile, e);
} catch (OldFileFormatException e) {
// Not even text extraction is supported for these: handler.handleExtracting(inputFile);
Assume.assumeFalse("File " + file + " excluded because it is unsupported old Excel format", true);
assumeFalse( true, "File " + file + " excluded because it is unsupported old Excel format" );
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
assumeFalse( true, "File " + file + " excluded because it is password-encrypted" );
} catch (ZipException e) {
// some files are corrupted
if (e.getMessage().equals("unexpected EOF") || e.getMessage().equals("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
assumeFalse( true, "File " + file + " excluded because the Zip file is incomplete" );
}
throw e;
@ -76,7 +76,7 @@ public class BaseIntegrationTest {
// ignore some other ways of corrupted files
String message = e.getMessage();
if(message != null && message.contains("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
assumeFalse( true, "File " + file + " excluded because the Zip file is incomplete" );
}
// sometimes binary format has XML-format-extension...
@ -92,7 +92,7 @@ public class BaseIntegrationTest {
if(message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file"))) {
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file", true);
assumeFalse( true, "File " + file + " excluded because it is actually a PDF/RTF/HTML file" );
}
if(message != null && message.equals("The document is really a OOXML file")) {
@ -107,7 +107,7 @@ public class BaseIntegrationTest {
handler.handleExtracting(inputFile);
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
assumeFalse( true, "File " + file + " excluded because it is password-encrypted" );
}
}
@ -117,10 +117,9 @@ public class BaseIntegrationTest {
String message = e.getMessage();
// ignore some file-types that we do not want to handle here
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file",
message != null && (message.equals("The document is really a RTF file") ||
assumeFalse( message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file")));
message.equals("The document is really a HTML file")), "File " + file + " excluded because it is actually a PDF/RTF/HTML file" );
if(message != null && (message.equals("The document is really a XLS file"))) {
handler = TestAllFiles.HANDLERS.get(".xls");

View File

@ -16,8 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
@ -29,7 +29,7 @@ import org.apache.poi.hdgf.extractor.VisioTextExtractor;
import org.apache.poi.hdgf.streams.Stream;
import org.apache.poi.hdgf.streams.TrailerStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HDGFFileHandler extends POIFSFileHandler {
@Override

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -30,7 +30,7 @@ import org.apache.poi.hmef.attribute.TNEFProperty;
import org.apache.poi.hsmf.datatypes.MAPIProperty;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.util.LittleEndian;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HMEFFileHandler extends AbstractFileHandler {
@ -58,8 +58,8 @@ public class HMEFFileHandler extends AbstractFileHandler {
} else {
bodyStr = msg.getBody();
}
assertNotNull("Body is not set", bodyStr);
assertNotNull("Subject is not set", msg.getSubject());
assertNotNull( bodyStr, "Body is not set" );
assertNotNull( msg.getSubject(), "Subject is not set" );
}
// a test-case to test this locally without executing the full TestAllFiles

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -25,7 +25,7 @@ import java.io.InputStream;
import org.apache.poi.hpbf.HPBFDocument;
import org.apache.poi.hpbf.extractor.PublisherTextExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HPBFFileHandler extends POIFSFileHandler {
@Override

View File

@ -16,7 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -39,8 +40,7 @@ import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HPSFFileHandler extends POIFSFileHandler {
private static final String NL = System.getProperty("line.separator");
@ -70,7 +70,7 @@ public class HPSFFileHandler extends POIFSFileHandler {
@Override
public void handleFile(InputStream stream, String path) throws Exception {
Assume.assumeFalse(EXCLUDES_HANDLE_FILE.contains(path));
assumeFalse(EXCLUDES_HANDLE_FILE.contains(path));
POIFSFileSystem poifs = new POIFSFileSystem(stream);
HPSFPropertiesOnlyDocument hpsf = new HPSFPropertiesOnlyDocument(poifs);
DocumentSummaryInformation dsi = hpsf.getDocumentSummaryInformation();
@ -96,7 +96,7 @@ public class HPSFFileHandler extends POIFSFileHandler {
@Override
public void handleAdditional(File file) throws Exception {
Assume.assumeFalse(EXCLUDES_HANDLE_ADD.contains(file.getParentFile().getName()+"/"+file.getName()));
assumeFalse(EXCLUDES_HANDLE_ADD.contains(file.getParentFile().getName()+"/"+file.getName()));
if (copyOutput == null) {
copyOutput = TempFile.createTempFile("hpsfCopy", "out");
copyOutput.deleteOnExit();

View File

@ -16,16 +16,18 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.SystemOutLogger;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HSLFFileHandler extends SlideShowHandler {
@Override
@ -38,7 +40,7 @@ public class HSLFFileHandler extends SlideShowHandler {
org.apache.poi.hslf.record.Record[] records = slide.getRecords();
assertNotNull(records);
for(org.apache.poi.hslf.record.Record record : records) {
assertNotNull("Found a record which was null", record);
assertNotNull( record, "Found a record which was null" );
assertTrue(record.getRecordType() >= 0);
}

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -25,7 +25,7 @@ import java.io.InputStream;
import org.apache.poi.hsmf.MAPIMessage;
import org.apache.poi.hsmf.datatypes.AttachmentChunks;
import org.apache.poi.hsmf.datatypes.DirectoryChunk;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HSMFFileHandler extends POIFSFileHandler {
@Override

View File

@ -16,8 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -34,7 +34,7 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.NullPrintStream;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HSSFFileHandler extends SpreadsheetHandler {
private final POIFSFileHandler delegate = new POIFSFileHandler();
@ -92,8 +92,7 @@ public class HSSFFileHandler extends SpreadsheetHandler {
BiffViewer.main(new String[]{file.getAbsolutePath()});
assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent));
assertFalse( EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent), "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!" );
} catch (OldExcelFormatException e) {
// old excel formats are not supported here
} catch (RuntimeException e) {

View File

@ -16,9 +16,9 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.FileInputStream;
import java.io.InputStream;
@ -27,7 +27,7 @@ import java.util.List;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Needs to be implemented in this package to have access to
@ -50,14 +50,12 @@ public class HSSFRecordsStresser {
try {
Record newRecord = record.copy();
assertEquals("Expecting the same class back from clone(), but had Record of type " + record.getClass() + " and got back a " + newRecord.getClass() + " from clone()",
record.getClass(), newRecord.getClass());
assertEquals( record.getClass(), newRecord.getClass(), "Expecting the same class back from clone(), but had Record of type " + record.getClass() + " and got back a " + newRecord.getClass() + " from clone()" );
byte[] origBytes = record.serialize();
byte[] newBytes = newRecord.serialize();
assertArrayEquals("Record of type " + record.getClass() + " should return the same byte array via the clone() method, but did return a different array",
origBytes, newBytes);
assertArrayEquals( origBytes, newBytes, "Record of type " + record.getClass() + " should return the same byte array via the clone() method, but did return a different array" );
} catch (RuntimeException e) {
// some Records do not implement clone, ignore those for now
assertTrue(e.getMessage().contains("needs to define a clone method"));

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -27,7 +27,7 @@ import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.Picture;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HWPFFileHandler extends POIFSFileHandler {
@Override

View File

@ -16,8 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
@ -28,7 +28,7 @@ import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.xwpf.usermodel.XWPFRelation;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class OPCFileHandler extends AbstractFileHandler {
@Override
@ -43,11 +43,10 @@ public class OPCFileHandler extends AbstractFileHandler {
assertEquals(ContentTypes.CORE_PROPERTIES_PART, part.getContentType());
}
if (part.getPartName().toString().equals("/word/document.xml")) {
assertTrue("Expected one of " + XWPFRelation.MACRO_DOCUMENT + ", " + XWPFRelation.DOCUMENT + ", " + XWPFRelation.TEMPLATE +
", but had " + part.getContentType(),
XWPFRelation.DOCUMENT.getContentType().equals(part.getContentType()) ||
assertTrue( XWPFRelation.DOCUMENT.getContentType().equals(part.getContentType()) ||
XWPFRelation.MACRO_DOCUMENT.getContentType().equals(part.getContentType()) ||
XWPFRelation.TEMPLATE.getContentType().equals(part.getContentType()));
XWPFRelation.TEMPLATE.getContentType().equals(part.getContentType()), "Expected one of " + XWPFRelation.MACRO_DOCUMENT + ", " + XWPFRelation.DOCUMENT + ", " + XWPFRelation.TEMPLATE +
", but had " + part.getContentType() );
}
if (part.getPartName().toString().equals("/word/theme/theme1.xml")) {
assertEquals(XWPFRelation.THEME.getContentType(), part.getContentType());

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -28,7 +28,7 @@ import java.io.InputStream;
import org.apache.poi.POIDocument;
import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class POIFSFileHandler extends AbstractFileHandler {

View File

@ -19,7 +19,7 @@
package org.apache.poi.stress;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.FileInputStream;
@ -39,8 +39,8 @@ import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.SuppressForbidden;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.tools.ant.DirectoryScanner;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Helper class to scan a folder for files and return a collection of
@ -191,7 +191,7 @@ public class POIFileScanner {
return TestAllFiles.NullFileHandler.instance;
}
@Ignore
@Disabled
@Test
@SuppressForbidden("Just an ignored test")
public void testInvalidFile() throws IOException, InterruptedException {

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.io.InputStream;

View File

@ -16,6 +16,18 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import org.apache.poi.sl.draw.Drawable;
import org.apache.poi.sl.usermodel.GroupShape;
import org.apache.poi.sl.usermodel.Notes;
@ -29,18 +41,6 @@ import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.sl.usermodel.TextShape;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public abstract class SlideShowHandler extends POIFSFileHandler {
public void handleSlideShow(SlideShow<?,?> ss) throws IOException {
renderSlides(ss);
@ -127,10 +127,8 @@ public abstract class SlideShowHandler extends POIFSFileHandler {
private void readPictures(SlideShow<?,?> ss) {
for (PictureData pd : ss.getPictureData()) {
Dimension dim = pd.getImageDimension();
assertTrue("Expecting a valid height, but had an image with height: " + dim.getHeight(),
dim.getHeight() >= 0);
assertTrue("Expecting a valid width, but had an image with width: " + dim.getWidth(),
dim.getWidth() >= 0);
assertTrue( dim.getHeight() >= 0, "Expecting a valid height, but had an image with height: " + dim.getHeight() );
assertTrue( dim.getWidth() >= 0, "Expecting a valid width, but had an image with width: " + dim.getWidth() );
}
}

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

View File

@ -17,9 +17,8 @@
package org.apache.poi.stress;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.BufferedInputStream;
import java.io.File;
@ -34,18 +33,16 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.poi.OldFileFormatException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.tools.ant.DirectoryScanner;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.opentest4j.TestAbortedException;
/**
* This is an integration test which performs various actions on all stored test-files and tries
@ -54,7 +51,7 @@ import org.junit.runners.Parameterized.Parameters;
* This test looks for any file under the test-data directory and tries to do some useful
* processing with it based on it's type.
*
* The test is implemented as a junit {@link Parameterized} test, which leads
* The test is implemented as a junit {@link ParameterizedTest} test, which leads
* to one test-method call for each file (currently around 950 files are handled).
*
* There is a a mapping of extension to implementations of the interface
@ -71,7 +68,6 @@ import org.junit.runners.Parameterized.Parameters;
* here as well! This is to ensure that files that should not work really do not work, e.g.
* that we do not remove expected sanity checks.
*/
@RunWith(Parameterized.class)
public class TestAllFiles {
private static final File ROOT_DIR = new File("test-data");
private static final boolean IGNORE_SCRATCHPAD = Boolean.getBoolean("scratchpad.ignore");
@ -344,8 +340,7 @@ public class TestAllFiles {
"spreadsheet/61300.xls"//intentionally fuzzed -- used to cause infinite loop
);
@Parameters(name="{index}: {0} using {1}")
public static Iterable<Object[]> files() {
public static Stream<Arguments> files() {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(ROOT_DIR);
scanner.setExcludes(SCAN_EXCLUDES);
@ -354,7 +349,7 @@ public class TestAllFiles {
System.out.println("Handling " + scanner.getIncludedFiles().length + " files");
List<Object[]> files = new ArrayList<>();
List<Arguments> files = new ArrayList<>();
for(String file : scanner.getIncludedFiles()) {
file = file.replace('\\', '/'); // ... failures/handlers lookup doesn't work on windows otherwise
if (IGNORED.contains(file)) {
@ -362,49 +357,41 @@ public class TestAllFiles {
continue;
}
FileHandler handler = HANDLERS.get(getExtension(file));
files.add(new Object[] { file, handler });
files.add(Arguments.of( file, handler ));
// for some file-types also run OPCFileHandler
if(handler instanceof XSSFFileHandler ||
handler instanceof XWPFFileHandler ||
handler instanceof XSLFFileHandler ||
handler instanceof XDGFFileHandler) {
files.add(new Object[] { file, new OPCFileHandler() });
files.add(Arguments.of( file, new OPCFileHandler() ));
}
if (handler instanceof HSSFFileHandler ||
handler instanceof HSLFFileHandler ||
handler instanceof HWPFFileHandler ||
handler instanceof HDGFFileHandler) {
files.add(new Object[] { file, new HPSFFileHandler() });
files.add(Arguments.of( file, new HPSFFileHandler() ));
}
}
return files;
return files.stream();
}
@SuppressWarnings("DefaultAnnotationParam")
@Parameter(value=0)
public String file;
// the display name annotation is ignored by ants junitlauncher listeners :(
// ... even when using a custom display name generator
@ParameterizedTest(name = "#{index} {0}" )
@MethodSource("files")
public void testAllFiles(String file, FileHandler handler) throws Exception {
assertNotNull(handler, "Did not find a handler for file " + file);
@Parameter(value=1)
public FileHandler handler;
@Before
public void setPassword() {
// this also removes the password for non encrypted files
String pass = TestAllFiles.FILE_PASSWORD.get(file);
Biff8EncryptionKey.setCurrentUserPassword(pass);
}
@Test
public void testAllFiles() throws Exception {
if(handler == null) {
fail("Did not find a handler for file " + file);
}
System.out.println("Reading " + file + " with " + handler.getClass().getSimpleName());
assertNotNull("Unknown file extension for file: " + file + ": " + getExtension(file), handler);
assertNotNull( handler, "Unknown file extension for file: " + file + ": " + getExtension(file) );
File inputFile = new File(ROOT_DIR, file);
// special cases where docx-handling breaks, but OPCPackage handling works
@ -416,14 +403,12 @@ public class TestAllFiles {
try {
try (InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64 * 1024)) {
handler.handleFile(stream, file);
assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!",
OLD_FILES_HWPF.contains(file) && !ignoreHPSF);
assertFalse( OLD_FILES_HWPF.contains(file) && !ignoreHPSF, "Expected to fail for file " + file + " and handler " + handler + ", but did not fail!" );
}
handler.handleExtracting(inputFile);
assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!",
EXPECTED_FAILURES.contains(file) && !ignoredOPC && !ignoreHPSF);
assertFalse( EXPECTED_FAILURES.contains(file) && !ignoredOPC && !ignoreHPSF, "Expected to fail for file " + file + " and handler " + handler + ", but did not fail!" );
} catch (OldFileFormatException e) {
// for old word files we should still support extracting text
if(OLD_FILES_HWPF.contains(file)) {
@ -435,7 +420,7 @@ public class TestAllFiles {
throw new Exception("While handling " + file, e);
}
}
} catch (AssumptionViolatedException e) {
} catch (TestAbortedException e) {
// file handler ignored this file
} catch (Exception e) {
// check if we expect failure for this file
@ -448,7 +433,7 @@ public class TestAllFiles {
try {
// let some file handlers do additional stuff
handler.handleAdditional(inputFile);
} catch (AssumptionViolatedException e) {
} catch (TestAbortedException e) {
// file handler ignored this file
} catch (Exception e) {
if(!EXPECTED_FAILURES.contains(file) && !AbstractFileHandler.EXPECTED_EXTRACTOR_FAILURES.contains(file)) {

View File

@ -21,7 +21,7 @@ import java.io.InputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.xdgf.usermodel.XmlVisioDocument;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class XDGFFileHandler extends AbstractFileHandler {
@Override

View File

@ -16,8 +16,8 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
@ -27,7 +27,7 @@ import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.sl.extractor.SlideShowExtractor;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlideShow;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class XSLFFileHandler extends SlideShowHandler {
@Override
@ -64,7 +64,7 @@ public class XSLFFileHandler extends SlideShowHandler {
extractor.setNotesByDefault(false);
extractor.setMasterByDefault(false);
assertEquals("With all options disabled we should not get text", "", extractor.getText());
assertEquals("", extractor.getText(), "With all options disabled we should not get text");
}
}

View File

@ -24,7 +24,7 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XLSBUnsupportedException;
import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class XSSFBFileHandler extends AbstractFileHandler {

View File

@ -16,10 +16,10 @@
==================================================================== */
package org.apache.poi.stress;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
@ -54,7 +54,7 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.extractor.XSSFExportToXml;
import org.apache.poi.xssf.usermodel.XSSFMap;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
public class XSSFFileHandler extends SpreadsheetHandler {
@ -78,7 +78,7 @@ public class XSSFFileHandler extends SpreadsheetHandler {
Decryptor dec = ei.getDecryptor();
try {
boolean b = dec.verifyPassword(pass);
assertTrue("password mismatch", b);
assertTrue( b, "password mismatch" );
} catch (EncryptedDocumentException e) {
String msg = "Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files";
assumeFalse(msg.equals(e.getMessage()));
@ -190,8 +190,7 @@ public class XSSFFileHandler extends SpreadsheetHandler {
XLSX2CSV.main(new String[]{file.getAbsolutePath()});
ExcelComparator.main(new String[]{file.getAbsolutePath(), file.getAbsolutePath()});
assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
EXPECTED_ADDITIONAL_FAILURES.contains(testFile));
assertFalse( EXPECTED_ADDITIONAL_FAILURES.contains(testFile), "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!" );
} catch (OLE2NotOfficeXmlFileException e) {
// we have some files that are not actually OOXML and thus cannot be tested here

View File

@ -22,7 +22,7 @@ import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class XWPFFileHandler extends AbstractFileHandler {
@Override

View File

@ -17,6 +17,7 @@
package org.apache.poi.poifs.nio;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -35,7 +36,7 @@ import org.apache.poi.util.POILogger;
/**
* A POIFS {@link DataSource} backed by a File
*/
public class FileBackedDataSource extends DataSource {
public class FileBackedDataSource extends DataSource implements Closeable {
private final static POILogger logger = POILogFactory.getLogger(FileBackedDataSource.class);
private final FileChannel channel;

View File

@ -17,80 +17,13 @@
package org.apache.poi.ss.formula.atp;
import java.util.Calendar;
import java.util.regex.Pattern;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.EvaluationException;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.Removal;
/**
* Parser for java dates.
* @deprecated in 5.0.0 - use {@link org.apache.poi.ss.util.DateParser}
*/
public class DateParser {
private DateParser() {
// enforcing singleton
}
/**
* Parses a date from a string.
*
* @param strVal a string with a date pattern.
* @return a date parsed from argument.
* @throws EvaluationException exception upon parsing.
*/
public static Calendar parseDate(String strVal) throws EvaluationException {
String[] parts = Pattern.compile("/").split(strVal);
if (parts.length != 3) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
String part2 = parts[2];
int spacePos = part2.indexOf(' ');
if (spacePos > 0) {
// drop time portion if present
part2 = part2.substring(0, spacePos);
}
int f0;
int f1;
int f2;
try {
f0 = Integer.parseInt(parts[0]);
f1 = Integer.parseInt(parts[1]);
f2 = Integer.parseInt(part2);
} catch (NumberFormatException e) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
if (f0 < 0 || f1 < 0 || f2 < 0 || (f0 > 12 && f1 > 12 && f2 > 12)) {
// easy to see this cannot be a valid date
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
if (f0 >= 1900 && f0 < 9999) {
// when 4 digit value appears first, the format is YYYY/MM/DD, regardless of OS settings
return makeDate(f0, f1, f2);
}
// otherwise the format seems to depend on OS settings (default date format)
// if (false) {
// // MM/DD/YYYY is probably a good guess, if the in the US
// return makeDate(f2, f0, f1);
// }
// TODO - find a way to choose the correct date format
throw new RuntimeException("Unable to determine date format for text '" + strVal + "'");
}
/**
* @param month 1-based
*/
private static Calendar makeDate(int year, int month, int day) throws EvaluationException {
if (month < 1 || month > 12) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
Calendar cal = LocaleUtil.getLocaleCalendar(year, month - 1, 1, 0, 0, 0);
if (day < 1 || day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
cal.set(Calendar.DAY_OF_MONTH, day);
return cal;
}
@Removal(version = "6.0.0")
@Deprecated
public class DateParser extends org.apache.poi.ss.util.DateParser {
}

View File

@ -35,7 +35,7 @@ import org.apache.poi.util.LocaleUtil;
* Parser for java dates.
*/
public class DateParser {
private DateParser() {
protected DateParser() {
// enforcing singleton
}

View File

@ -25,4 +25,8 @@ module org.apache.poi.excelant {
exports org.apache.poi.ss.excelant.util;
opens org.apache.poi.ss.excelant;
// test specific exports
requires org.junit.jupiter.api;
requires org.junit.jupiter.params;
}

View File

@ -16,12 +16,12 @@
==================================================================== */
module org.apache.poi.stress {
requires junit;
requires org.junit.jupiter.api;
requires org.junit.jupiter.params;
requires net.bytebuddy;
requires java.desktop;
requires org.apache.poi.examples;
exports org.apache.poi.stress;
}

View File

@ -98,28 +98,29 @@ module org.apache.poi.ooxml {
// test specific exports
requires junit;
requires org.junit.jupiter.api;
requires org.junit.jupiter.params;
requires com.google.common;
exports org.apache.poi.extractor.ooxml to junit;
exports org.apache.poi.openxml4j.opc.compliance to junit;
exports org.apache.poi.poifs.crypt.tests to junit;
exports org.apache.poi.sl.tests to junit;
exports org.apache.poi.sl.tests.draw to junit;
exports org.apache.poi.ss.tests to junit;
exports org.apache.poi.ss.tests.extractor to junit;
exports org.apache.poi.ss.tests.format to junit;
exports org.apache.poi.ss.tests.formula to junit;
exports org.apache.poi.ss.tests.formula.eval to junit;
exports org.apache.poi.ss.tests.formula.functions to junit;
exports org.apache.poi.ss.tests.usermodel to junit;
exports org.apache.poi.ss.tests.util to junit;
exports org.apache.poi.util.tests to junit;
exports org.apache.poi.xslf to junit;
exports org.apache.poi.xslf.extractor to junit;
exports org.apache.poi.xssf.io to junit;
exports org.apache.poi.xssf.usermodel.charts to junit;
exports org.apache.poi.xwpf to junit;
exports org.apache.poi.extractor.ooxml to org.junit.platform.commons;
exports org.apache.poi.openxml4j.opc.compliance to org.junit.platform.commons;
exports org.apache.poi.poifs.crypt.tests to org.junit.platform.commons;
exports org.apache.poi.sl.tests to org.junit.platform.commons;
exports org.apache.poi.sl.tests.draw to org.junit.platform.commons;
exports org.apache.poi.ss.tests to org.junit.platform.commons;
exports org.apache.poi.ss.tests.extractor to org.junit.platform.commons;
exports org.apache.poi.ss.tests.format to org.junit.platform.commons;
exports org.apache.poi.ss.tests.formula to org.junit.platform.commons;
exports org.apache.poi.ss.tests.formula.eval to org.junit.platform.commons;
exports org.apache.poi.ss.tests.formula.functions to org.junit.platform.commons;
exports org.apache.poi.ss.tests.usermodel to org.junit.platform.commons;
exports org.apache.poi.ss.tests.util to org.junit.platform.commons;
exports org.apache.poi.util.tests to org.junit.platform.commons;
exports org.apache.poi.xslf to org.junit.platform.commons;
exports org.apache.poi.xslf.extractor to org.junit.platform.commons;
exports org.apache.poi.xssf.io to org.junit.platform.commons;
exports org.apache.poi.xssf.usermodel.charts to org.junit.platform.commons;
exports org.apache.poi.xwpf to org.junit.platform.commons;
}

View File

@ -103,8 +103,11 @@ module org.apache.poi.poi {
exports org.apache.poi.wp.usermodel;
// test specific exports
requires junit;
requires net.bytebuddy;
opens org.apache.poi.hpsf.basic to junit;
opens org.apache.poi.hssf.record.pivot to junit;
requires org.junit.jupiter.api;
requires org.junit.jupiter.params;
opens org.apache.poi.hpsf.basic to org.junit.platform.commons;
opens org.apache.poi.hssf.record.pivot to org.junit.platform.commons;
opens org.apache.poi.hssf.dev to org.junit.platform.commons;
}

View File

@ -76,13 +76,14 @@ module org.apache.poi.scratchpad {
// test specific exports
requires junit;
requires org.junit.jupiter.api;
requires org.junit.jupiter.params;
requires org.mockito;
exports org.apache.poi.hemf.hemfplus.extractor to junit;
exports org.apache.poi.hslf to junit;
exports org.apache.poi.hwmf to junit;
exports org.apache.poi.hwpf.util to junit;
exports org.apache.poi.hemf.hemfplus.extractor to org.junit.platform.commons;
exports org.apache.poi.hslf to org.junit.platform.commons;
exports org.apache.poi.hwmf to org.junit.platform.commons;
exports org.apache.poi.hwpf.util to org.junit.platform.commons;
opens org.apache.poi.hwpf.model to org.mockito;
opens org.apache.poi.hwpf.model.types to org.mockito;

View File

@ -17,13 +17,12 @@
package org.apache.poi.extractor.ooxml;
import static org.apache.poi.POITestCase.assertContains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
@ -31,7 +30,6 @@ import java.io.IOException;
import java.util.Locale;
import org.apache.poi.POIDataSamples;
import org.apache.poi.UnsupportedFileFormatException;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.extractor.POIOLE2TextExtractor;
import org.apache.poi.extractor.POITextExtractor;
@ -39,6 +37,7 @@ import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.extractor.EventBasedExcelExtractor;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.ooxml.extractor.POIXMLExtractorFactory;
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
@ -47,7 +46,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.xmlbeans.XmlException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test that the extractor factory plays nicely
@ -86,17 +85,17 @@ public class TestExtractorFactory {
private static final File vsd = getFileAndCheck(dgTests, "Test_Visio-Some_Random_Text.vsd");
private static final File vsdx = getFileAndCheck(dgTests, "test.vsdx");
private static POIDataSamples pubTests = POIDataSamples.getPublisherInstance();
private static File pub = getFileAndCheck(pubTests, "Simple.pub");
private static final POIDataSamples pubTests = POIDataSamples.getPublisherInstance();
private static final File pub = getFileAndCheck(pubTests, "Simple.pub");
private static final POIXMLExtractorFactory xmlFactory = new POIXMLExtractorFactory();
private static File getFileAndCheck(POIDataSamples samples, String name) {
File file = samples.getFile(name);
assertNotNull("Did not get a file for " + name, file);
assertTrue("Did not get a type file for " + name, file.isFile());
assertTrue("File did not exist: " + name, file.exists());
assertNotNull(file, "Did not get a file for " + name);
assertTrue(file.isFile(), "Did not get a type file for " + name);
assertTrue(file.exists(), "File did not exist: " + name);
return file;
}
@ -127,6 +126,7 @@ public class TestExtractorFactory {
R apply(T t) throws IOException, OpenXML4JException, XmlException;
}
@SuppressWarnings("ConstantConditions")
@Test
public void testFile() throws Exception {
for (int i = 0; i < TEST_SET.length; i += 4) {
@ -172,6 +172,7 @@ public class TestExtractorFactory {
assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0"));
}
@SuppressWarnings("ConstantConditions")
private void testStream(final FunctionEx<FileInputStream, POITextExtractor> poifsIS, final boolean loadOOXML)
throws IOException, OpenXML4JException, XmlException {
for (int i = 0; i < TEST_SET.length; i += 4) {
@ -182,22 +183,21 @@ public class TestExtractorFactory {
try (FileInputStream fis = new FileInputStream(testFile);
POITextExtractor ext = poifsIS.apply(fis)) {
testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]);
} catch (IllegalArgumentException e) {
fail("failed to process "+testFile);
}
}
}
private void testExtractor(final POITextExtractor ext, final String testcase, final String extrClass, final Integer minLength) {
assertEquals("invalid extractor for " + testcase, extrClass, ext.getClass().getSimpleName());
assertEquals(extrClass, ext.getClass().getSimpleName(), "invalid extractor for " + testcase);
final String actual = ext.getText();
if (minLength == -1) {
assertContains(actual.toLowerCase(Locale.ROOT), "test");
} else {
assertTrue("extracted content too short for " + testcase, actual.length() > minLength);
assertTrue(actual.length() > minLength, "extracted content too short for " + testcase);
}
}
@SuppressWarnings("ConstantConditions")
@Test
public void testPackage() throws Exception {
for (int i = 0; i < TEST_SET.length; i += 4) {
@ -208,19 +208,17 @@ public class TestExtractorFactory {
try (final OPCPackage pkg = OPCPackage.open(testFile, PackageAccess.READ);
final POITextExtractor ext = xmlFactory.create(pkg)) {
assertNotNull(ext);
testExtractor(ext, (String) TEST_SET[i], (String) TEST_SET[i + 2], (Integer) TEST_SET[i + 3]);
pkg.revert();
}
}
}
@Test(expected = UnsupportedFileFormatException.class)
public void testPackageInvalid() throws Exception {
@Test
public void testPackageInvalid() {
// Text
try (final OPCPackage pkg = OPCPackage.open(txt, PackageAccess.READ);
final POITextExtractor ignored = xmlFactory.create(pkg)) {
fail("extracting from invalid package");
}
assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(txt, PackageAccess.READ));
}
@Test
@ -334,7 +332,7 @@ public class TestExtractorFactory {
final String actual = embeds.length+"-"+numWord+"-"+numXls+"-"+numPpt+"-"+numMsg+"-"+numWordX;
final String expected = (String)testObj[i+2];
assertEquals("invalid number of embeddings - "+testObj[i], expected, actual);
assertEquals(expected, actual, "invalid number of embeddings - "+testObj[i]);
}
}
@ -445,28 +443,31 @@ public class TestExtractorFactory {
* #59074 - Excel 95 files should give a helpful message, not just
* "No supported documents found in the OLE2 stream"
*/
@Test
public void bug59074() throws Exception {
try (POITextExtractor extractor = ExtractorFactory.createExtractor(POIDataSamples.getSpreadSheetInstance().getFile("59074.xls"))) {
String text = extractor.getText();
assertContains(text, "testdoc");
assertContains(text, "Exotic warrant");
}
}
@Test(expected = IllegalStateException.class)
public void testGetEmbeddedFromXMLExtractor() throws IOException {
@Test
public void testGetEmbeddedFromXMLExtractor() {
// currently not implemented
ExtractorFactory.getEmbeddedDocsTextExtractors(null);
assertThrows(IllegalStateException.class, () -> ExtractorFactory.getEmbeddedDocsTextExtractors(null));
}
// This bug is currently open. This test will fail with "expected error not thrown" when the bug has been fixed.
// When this happens, change this from @Test(expected=...) to @Test
// bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor
@Test(expected=AssertionError.class)
@Test
public void test45565() throws Exception {
try (POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("45565.xls"))) {
String text = extractor.getText();
assertContains(text, "testdoc");
assertContains(text, "test phrase");
assertThrows(AssertionError.class, () -> {
assertContains(text, "testdoc");
assertContains(text, "test phrase");
});
}
}
}

View File

@ -16,9 +16,9 @@
==================================================================== */
package org.apache.poi.ooxml;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ -30,7 +30,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.util.IOUtils;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Class to test that HXF correctly detects OOXML
@ -52,15 +52,14 @@ public class TestDetectAsOOXML {
};
for (Object[] fm : fileAndMagic) {
InputStream is = HSSFTestDataSamples.openSampleFileStream((String)fm[0]);
is = FileMagic.prepareToCheckMagic(is);
FileMagic act = FileMagic.valueOf(is);
try (InputStream is = FileMagic.prepareToCheckMagic(HSSFTestDataSamples.openSampleFileStream((String)fm[0]))) {
FileMagic act = FileMagic.valueOf(is);
assertEquals("OOXML files should be detected, others not",
act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is));
assertEquals(act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is),
"OOXML files should be detected, others not");
assertEquals("file magic failed for "+fm[0], fm[1], act);
is.close();
assertEquals(fm[1], act, "file magic failed for " + fm[0]);
}
}
}

View File

@ -19,9 +19,9 @@
package org.apache.poi.ooxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
@ -30,7 +30,7 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XSLFSlideShow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Class to test that we handle embeded bits in OOXML files properly

View File

@ -17,13 +17,17 @@
package org.apache.poi.ooxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@ -47,7 +51,8 @@ import org.apache.poi.util.TempFile;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xwpf.usermodel.XWPFRelation;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
/**
* Test recursive read and write of OPC packages
@ -110,110 +115,88 @@ public final class TestPOIXMLDocument {
traverse(p, context);
} else {
POIXMLDocumentPart prev = context.get(uri);
assertSame("Duplicate POIXMLDocumentPart instance for targetURI=" + uri, prev, p.getDocumentPart());
assertSame(prev, p.getDocumentPart(), "Duplicate POIXMLDocumentPart instance for targetURI=" + uri);
}
}
}
public void assertReadWrite(OPCPackage pkg1) throws Exception {
private void assertReadWrite(POIDataSamples samples, String filename) throws Exception {
try (InputStream is = samples.openResourceAsStream(filename);
OPCPackage pkg1 = PackageHelper.open(is)){
File tmp = TempFile.createTempFile("poi-ooxml", ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp);
OPCParser doc = new OPCParser(pkg1)) {
doc.parse(new TestFactory());
traverse(doc);
doc.write(out);
out.close();
OPCParser doc = new OPCParser(pkg1);
doc.parse(new TestFactory());
// Should not be able to write to an output stream that has been closed
// FIXME: A better exception class (IOException?) and message should be raised
// indicating that the document could not be written because the output stream is closed.
// see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)}
OpenXML4JRuntimeException e = assertThrows(OpenXML4JRuntimeException.class, () -> doc.write(out),
"Should not be able to write to an output stream that has been closed.");
assertTrue(e.getMessage().matches("Fail to save: an error occurs while saving the package : " +
"The part .+ failed to be saved in the stream with marshaller .+"));
traverse(doc);
// Should not be able to write a document that has been closed
doc.close();
IOException e2 = assertThrows(IOException.class, () -> doc.write(new NullOutputStream()),
"Should not be able to write a document that has been closed.");
assertEquals("Cannot write data, document seems to have been closed already", e2.getMessage());
File tmp = TempFile.createTempFile("poi-ooxml", ".tmp");
FileOutputStream out = new FileOutputStream(tmp);
doc.write(out);
out.close();
// Should not be able to write to an output stream that has been closed
try {
doc.write(out);
fail("Should not be able to write to an output stream that has been closed.");
} catch (final OpenXML4JRuntimeException e) {
// FIXME: A better exception class (IOException?) and message should be raised
// indicating that the document could not be written because the output stream is closed.
// see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)}
if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) {
// expected
} else {
throw e;
// Should be able to close a document multiple times, though subsequent closes will have no effect.
}
}
// Should not be able to write a document that has been closed
doc.close();
try {
doc.write(new NullOutputStream());
fail("Should not be able to write a document that has been closed.");
} catch (final IOException e) {
if (e.getMessage().equals("Cannot write data, document seems to have been closed already")) {
// expected
} else {
throw e;
}
}
// Should be able to close a document multiple times, though subsequent closes will have no effect.
doc.close();
@SuppressWarnings("resource")
OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
doc = new OPCParser(pkg1);
try {
doc.parse(new TestFactory());
traverse(doc);
try (OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
OPCParser doc = new OPCParser(pkg1)) {
doc.parse(new TestFactory());
traverse(doc);
assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
ArrayList<PackagePart> l1 = pkg1.getParts();
ArrayList<PackagePart> l2 = pkg2.getParts();
ArrayList<PackagePart> l1 = pkg1.getParts();
ArrayList<PackagePart> l2 = pkg2.getParts();
assertEquals(l1.size(), l2.size());
for (int i=0; i < l1.size(); i++){
PackagePart p1 = l1.get(i);
PackagePart p2 = l2.get(i);
assertEquals(l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
PackagePart p1 = l1.get(i);
PackagePart p2 = l2.get(i);
assertEquals(p1.getContentType(), p2.getContentType());
assertEquals(p1.hasRelationships(), p2.hasRelationships());
if(p1.hasRelationships()){
assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
assertEquals(p1.getContentType(), p2.getContentType());
assertEquals(p1.hasRelationships(), p2.hasRelationships());
if (p1.hasRelationships()) {
assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
}
assertEquals(p1.getPartName(), p2.getPartName());
}
assertEquals(p1.getPartName(), p2.getPartName());
}
} finally {
doc.close();
pkg1.close();
pkg2.close();
}
}
@Test
public void testPPTX() throws Exception {
POIDataSamples pds = POIDataSamples.getSlideShowInstance();
assertReadWrite(PackageHelper.open(pds.openResourceAsStream("PPTWithAttachments.pptm")));
assertReadWrite(POIDataSamples.getSlideShowInstance(), "PPTWithAttachments.pptm");
}
@Test
public void testXLSX() throws Exception {
POIDataSamples pds = POIDataSamples.getSpreadSheetInstance();
assertReadWrite(PackageHelper.open(pds.openResourceAsStream("ExcelWithAttachments.xlsm")));
assertReadWrite(POIDataSamples.getSpreadSheetInstance(), "ExcelWithAttachments.xlsm");
}
@Test
public void testDOCX() throws Exception {
POIDataSamples pds = POIDataSamples.getDocumentInstance();
assertReadWrite(PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")));
assertReadWrite(POIDataSamples.getDocumentInstance(), "WordWithAttachments.docx");
}
@Test
public void testRelationOrder() throws Exception {
POIDataSamples pds = POIDataSamples.getDocumentInstance();
@SuppressWarnings("resource")
OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
try (OPCParser doc = new OPCParser(pkg)) {
try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx");
OPCPackage pkg = PackageHelper.open(is);
OPCParser doc = new OPCParser(pkg)) {
doc.parse(new TestFactory());
for (POIXMLDocumentPart rel : doc.getRelations()) {
@ -226,9 +209,9 @@ public final class TestPOIXMLDocument {
@Test
public void testGetNextPartNumber() throws Exception {
POIDataSamples pds = POIDataSamples.getDocumentInstance();
@SuppressWarnings("resource")
OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
try (OPCParser doc = new OPCParser(pkg)) {
try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx");
OPCPackage pkg = PackageHelper.open(is);
OPCParser doc = new OPCParser(pkg)) {
doc.parse(new TestFactory());
// Non-indexed parts: Word is taken, Excel is not
@ -272,34 +255,32 @@ public final class TestPOIXMLDocument {
@Test
public void testVSDX() throws Exception {
POIDataSamples pds = POIDataSamples.getDiagramInstance();
@SuppressWarnings("resource")
OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT);
assertNotNull(part);
assertEquals(0, part.getRelationCounter());
part.close();
try (InputStream is = pds.openResourceAsStream("test.vsdx");
OPCPackage open = PackageHelper.open(is);
POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT)) {
assertNotNull(part);
assertEquals(0, part.getRelationCounter());
}
}
@Test
public void testVSDXPart() throws IOException {
POIDataSamples pds = POIDataSamples.getDiagramInstance();
OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
try (InputStream is = pds.openResourceAsStream("test.vsdx");
OPCPackage open = PackageHelper.open(is)) {
POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT);
POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT);
assertNotNull(part);
assertEquals(0, part.getRelationCounter());
open.close();
assertNotNull(part);
assertEquals(0, part.getRelationCounter());
}
}
@Test(expected=POIXMLException.class)
@Test
public void testInvalidCoreRel() throws IOException {
POIDataSamples pds = POIDataSamples.getDiagramInstance();
try (OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"))) {
new POIXMLDocumentPart(open, "somethingillegal");
assertThrows(POIXMLException.class, () -> new POIXMLDocumentPart(open, "somethingillegal"));
}
}
@ -316,23 +297,20 @@ public final class TestPOIXMLDocument {
}
@Test
public void testOSGIClassLoading() {
public void testOSGIClassLoading() throws IOException {
byte[] data;
try (InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx")) {
data = IOUtils.toByteArray(is);
}
// the schema type loader is cached per thread in POIXMLTypeLoader.
// So create a new Thread and change the context class loader (which would normally be used)
// to not contain the OOXML classes
Runnable run = () -> {
InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx");
XMLSlideShow ppt = null;
try {
ppt = new XMLSlideShow(is);
ppt.getSlides().get(0).getShapes();
} catch (IOException e) {
fail("failed to load XMLSlideShow");
} finally {
IOUtils.closeQuietly(ppt);
IOUtils.closeQuietly(is);
}
};
Runnable run = () -> assertDoesNotThrow(() -> {
try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(data))) {
assertNotNull(ppt.getSlides().get(0).getShapes());
}}
);
ClassLoader cl = getClass().getClassLoader();
UncaughtHandler uh = new UncaughtHandler();
@ -347,14 +325,10 @@ public final class TestPOIXMLDocument {
ta[i].start();
}
for (Thread thread : ta) {
try {
thread.join();
} catch (InterruptedException e) {
fail("failed to join thread");
}
assertDoesNotThrow((Executable) thread::join, "failed to join thread");
}
}
assertFalse("Should not have an exception now, but had " + uh.e, uh.hasException());
assertFalse(uh.hasException(), "Should not have an exception now, but had " + uh.e);
}
private static class UncaughtHandler implements UncaughtExceptionHandler {
@ -362,7 +336,6 @@ public final class TestPOIXMLDocument {
public synchronized void uncaughtException(Thread t, Throwable e) {
this.e = e;
}
public synchronized boolean hasException() {

View File

@ -17,36 +17,33 @@
package org.apache.poi.ooxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
import org.apache.poi.ooxml.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Test setting extended and custom OOXML properties
@ -57,7 +54,7 @@ public final class TestPOIXMLProperties {
private POIXMLProperties _props;
private CoreProperties _coreProperties;
@Before
@BeforeEach
public void setUp() throws IOException {
sampleDoc = XWPFTestDataSamples.openSampleDocument("documentProperties.docx");
sampleNoThumb = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
@ -68,7 +65,7 @@ public final class TestPOIXMLProperties {
assertNotNull(_props);
}
@After
@AfterEach
public void closeResources() throws Exception {
sampleDoc.close();
sampleNoThumb.close();
@ -158,53 +155,48 @@ public final class TestPOIXMLProperties {
*/
@Test
public void testCustomProperties() throws Exception {
POIXMLDocument wb1 = new XSSFWorkbook();
try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties();
customProps.addProperty("test-1", "string val");
customProps.addProperty("test-2", 1974);
customProps.addProperty("test-3", 36.6);
//adding a duplicate
try {
POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties();
customProps.addProperty("test-1", "string val");
customProps.addProperty("test-2", 1974);
customProps.addProperty("test-3", 36.6);
fail("expected exception");
} catch(IllegalArgumentException e){
//adding a duplicate
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> customProps.addProperty("test-3", 36.6));
assertEquals("A property with this name already exists in the custom properties", e.getMessage());
customProps.addProperty("test-4", true);
try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps =
wb2.getProperties().getCustomProperties().getUnderlyingProperties();
assertEquals(4, ctProps.sizeOfPropertyArray());
org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p;
p = ctProps.getPropertyArray(0);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-1", p.getName());
assertEquals("string val", p.getLpwstr());
assertEquals(2, p.getPid());
p = ctProps.getPropertyArray(1);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-2", p.getName());
assertEquals(1974, p.getI4());
assertEquals(3, p.getPid());
p = ctProps.getPropertyArray(2);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-3", p.getName());
assertEquals(36.6, p.getR8(), 0);
assertEquals(4, p.getPid());
p = ctProps.getPropertyArray(3);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-4", p.getName());
assertTrue(p.getBool());
assertEquals(5, p.getPid());
}
}
customProps.addProperty("test-4", true);
POIXMLDocument wb2 = XSSFTestDataSamples.writeOutAndReadBack((XSSFWorkbook)wb1);
wb1.close();
org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps =
wb2.getProperties().getCustomProperties().getUnderlyingProperties();
assertEquals(4, ctProps.sizeOfPropertyArray());
org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p;
p = ctProps.getPropertyArray(0);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-1", p.getName());
assertEquals("string val", p.getLpwstr());
assertEquals(2, p.getPid());
p = ctProps.getPropertyArray(1);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-2", p.getName());
assertEquals(1974, p.getI4());
assertEquals(3, p.getPid());
p = ctProps.getPropertyArray(2);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-3", p.getName());
assertEquals(36.6, p.getR8(), 0);
assertEquals(4, p.getPid());
p = ctProps.getPropertyArray(3);
assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid());
assertEquals("test-4", p.getName());
assertTrue(p.getBool());
assertEquals(5, p.getPid());
wb2.close();
}
@Test
@ -246,7 +238,7 @@ public final class TestPOIXMLProperties {
@Test
public void testGetSetRevision() {
String revision = _coreProperties.getRevision();
assertTrue("Revision number is 1", Integer.parseInt(revision) > 1);
assertTrue(Integer.parseInt(revision) > 1, "Revision number is 1");
_coreProperties.setRevision("20");
assertEquals("20", _coreProperties.getRevision());
_coreProperties.setRevision("20xx");
@ -274,7 +266,7 @@ public final class TestPOIXMLProperties {
return utcString.equals(dateTimeUtcString);
}
@Ignore("Fails to add some of the thumbnails, needs more investigation")
@Disabled("Fails to add some of the thumbnails, needs more investigation")
@Test
public void testThumbnails() throws Exception {
POIXMLProperties noThumbProps = sampleNoThumb.getProperties();
@ -346,23 +338,23 @@ public final class TestPOIXMLProperties {
XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertNotNull(wbBack);
// properties documents are read lazily, so we have to access them to verify they parse properly
assertNotNull("First writeOutAndReadBack", wbBack.getProperties());
assertEquals("First prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr());
assertNotNull(wbBack.getProperties(), "First writeOutAndReadBack");
assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "First prop check");
customProperties.addProperty(propName + "1", propValue);
wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertNotNull(wbBack);
// properties documents are read lazily, so we have to access them to verify they parse properly
assertNotNull("Second writeOutAndReadBack", wbBack.getProperties());
assertEquals("Second prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr());
assertEquals("Second prop check1", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr());
assertNotNull(wbBack.getProperties(), "Second writeOutAndReadBack");
assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Second prop check");
assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Second prop check1");
wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertNotNull(wbBack);
// properties documents are read lazily, so we have to access them to verify they parse properly
assertNotNull("Third writeOutAndReadBack", wbBack.getProperties());
assertEquals("Third prop check", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr());
assertEquals("Third prop check1", propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr());
assertNotNull(wbBack.getProperties(), "Third writeOutAndReadBack");
assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Third prop check");
assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Third prop check1");
/* Manual test to write out the file more than once:
File test1 = File.createTempFile("test1", ".xlsx", new File("C:\\temp"));

View File

@ -17,9 +17,9 @@
package org.apache.poi.ooxml;
import static org.apache.poi.POITestCase.assertContains;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ooxml.extractor.POIXMLPropertiesTextExtractor;
@ -28,7 +28,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xslf.usermodel.XSLFSlideShow;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public final class TestXMLPropertiesTextExtractor {
private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance();

View File

@ -1,36 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j.opc;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestContentType.class
, TestFileHelper.class
, TestListParts.class
, TestPackage.class
, TestPackageCoreProperties.class
, TestPackagePartName.class
, TestPackageThumbnail.class
, TestPackagingURIHelper.class
, TestRelationships.class
})
public final class AllOpenXML4JTests {
}

View File

@ -17,11 +17,11 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.InputStream;
@ -30,7 +30,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Tests for content type (ContentType class).
@ -81,12 +81,8 @@ public final class TestContentType {
"te{xt/xml", "tex}t/xml", "te xt/xml",
"text" + (char) 9 + "/xml", "text xml", " text/xml "};
for (String contentType : contentTypesToTest) {
try {
new ContentType(contentType);
} catch (InvalidFormatException e) {
continue;
}
fail("Must have fail for content type: '" + contentType + "' !");
assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
"Must have fail for content type: '" + contentType + "' !");
}
}
@ -120,12 +116,8 @@ public final class TestContentType {
"text/\u0080" // characters above ASCII are not allowed
};
for (String contentType : contentTypesToTest) {
try {
new ContentType(contentType);
} catch (InvalidFormatException e) {
continue;
}
fail("Must have fail for content type: '" + contentType + "' !");
assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
"Must have fail for content type: '" + contentType + "' !");
}
}
@ -138,12 +130,8 @@ public final class TestContentType {
public void testContentTypeCommentFailure() {
String[] contentTypesToTest = new String[]{"text/xml(comment)"};
for (String contentType : contentTypesToTest) {
try {
new ContentType(contentType);
} catch (InvalidFormatException e) {
continue;
}
fail("Must have fail for content type: '" + contentType + "' !");
assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
"Must have fail for content type: '" + contentType + "' !");
}
}

View File

@ -17,13 +17,13 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.util.TreeMap;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test TestFileHelper class.

View File

@ -17,8 +17,8 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
@ -28,8 +28,8 @@ import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public final class TestListParts {
private static final POILogger logger = POILogFactory.getLogger(TestListParts.class);
@ -38,7 +38,7 @@ public final class TestListParts {
private TreeMap<PackagePartName, String> values;
@Before
@BeforeEach
public void setUp() throws Exception {
values = new TreeMap<>();

View File

@ -22,13 +22,14 @@ import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
@ -70,12 +71,12 @@ import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
@ -88,10 +89,9 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFRelation;
import org.apache.xmlbeans.XmlException;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@ -288,7 +288,7 @@ public final class TestPackage {
for (int i = 0; i < nodeCount; i++) {
Element element = (Element) nodeList.item(i);
String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/');
assertTrue(value.charAt(0) != '/', "Root target must not start with a leading slash ('/'): " + value);
}
}
@ -340,11 +340,7 @@ public final class TestPackage {
StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
// Save and close
try {
pkg.close();
} catch (IOException e) {
fail();
}
assertDoesNotThrow(pkg::close);
ZipFileAssert.assertEquals(expectedFile, targetFile);
assertTrue(targetFile.delete());
@ -406,7 +402,7 @@ public final class TestPackage {
* TODO: fix and enable
*/
@Test
@Ignore
@Disabled
public void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException {
String originalFile = getSampleFileName("TestPackageCommon.docx");
File targetFile = getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
@ -519,12 +515,8 @@ public final class TestPackage {
FileHelper.copyFile(origFile, tempFile);
try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) {
// Save it to the same file - not allowed
try {
p.save(tempFile);
fail("You shouldn't be able to call save(File) to overwrite the current file");
} catch(InvalidOperationException e) {
// expected here
}
assertThrows(InvalidOperationException.class, () -> p.save(tempFile),
"You shouldn't be able to call save(File) to overwrite the current file");
}
// Delete it
assertTrue(tempFile.delete());
@ -668,12 +660,12 @@ public final class TestPackage {
private void handleNonOOXML(String file, Class<? extends UnsupportedFileFormatException> exception, String... messageParts) throws IOException {
try (InputStream stream = xlsSamples.openResourceAsStream(file)) {
ThrowingRunnable[] trs = {
Executable[] trs = {
() -> OPCPackage.open(stream),
() -> OPCPackage.open(xlsSamples.getFile(file))
};
for (ThrowingRunnable tr : trs) {
Exception ex = assertThrows("Shouldn't be able to open "+file, exception, tr);
for (Executable tr : trs) {
Exception ex = assertThrows(exception, tr, "Shouldn't be able to open "+file);
Stream.of(messageParts).forEach(mp -> assertTrue(ex.getMessage().contains(mp)));
}
}
@ -792,7 +784,7 @@ public final class TestPackage {
return false;
}
private void openXmlBombFile(String file) throws IOException, OpenXML4JException, XmlException {
private void openXmlBombFile(String file) throws IOException {
final double minInf = ZipSecureFile.getMinInflateRatio();
ZipSecureFile.setMinInflateRatio(0.002);
try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) {
@ -827,7 +819,7 @@ public final class TestPackage {
}
@Test
public void zipBombCheckSizesSizeTooBig() throws IOException, EncryptedDocumentException {
public void zipBombCheckSizesSizeTooBig() throws EncryptedDocumentException {
POIXMLException ex = assertThrows(
POIXMLException.class,
() -> getZipStatsAndConsume((max_size, min_ratio) -> {
@ -896,10 +888,10 @@ public final class TestPackage {
}
// bug 60128
@Test(expected=NotOfficeXmlFileException.class)
public void testCorruptFile() throws InvalidFormatException {
@Test
public void testCorruptFile() {
File file = getSampleFile("invalid.xlsx");
OPCPackage.open(file, PackageAccess.READ);
assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(file, PackageAccess.READ));
}
private interface CountingStream {
@ -944,16 +936,19 @@ public final class TestPackage {
break;
}
}
assertTrue("Core not found in " + p.getParts(), foundCoreProps);
assertFalse("Document should not be found in " + p.getParts(), foundDocument);
assertFalse("Theme1 should not found in " + p.getParts(), foundTheme1);
assertTrue(foundCoreProps, "Core not found in " + p.getParts());
assertFalse(foundDocument, "Document should not be found in " + p.getParts());
assertFalse(foundTheme1, "Theme1 should not found in " + p.getParts());
}
}
@Test
public void unparseableCentralDirectory() throws IOException {
File f = getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx");
SlideShowFactory.create(f, null, true).close();
try (SlideShow<?,?> ppt = SlideShowFactory.create(f, null, true)) {
assertNotNull(ppt);
assertNotNull(ppt.getSlides().get(0));
}
}
@Test
@ -967,15 +962,13 @@ public final class TestPackage {
}
// feed the corrupted zip file to OPCPackage
try {
OPCPackage.open(tmp, PackageAccess.READ);
} catch (Exception e) {
// expected: the zip file is invalid
// this test does not care if open() throws an exception or not.
}
// expected: the zip file is invalid
// this test does not care if open() throws an exception or not.
assertThrows(Exception.class, () -> OPCPackage.open(tmp, PackageAccess.READ));
// If the stream is not closed on exception, it will keep a file descriptor to tmp,
// and requests to the OS to delete the file will fail.
assertTrue("Can't delete tmp file", tmp.delete());
assertTrue(tmp.delete(), "Can't delete tmp file");
}
/**
@ -984,30 +977,31 @@ public final class TestPackage {
* stream / file the broken file is being read from.
* See bug #60128 for more
*/
@Test(expected = NotOfficeXmlFileException.class)
@Test
public void testTidyStreamOnInvalidFile1() throws Exception {
openInvalidFile("SampleSS.ods", false);
}
@Test(expected = NotOfficeXmlFileException.class)
@Test
public void testTidyStreamOnInvalidFile2() throws Exception {
openInvalidFile("SampleSS.ods", true);
}
@Test(expected = NotOfficeXmlFileException.class)
@Test
public void testTidyStreamOnInvalidFile3() throws Exception {
openInvalidFile("SampleSS.txt", false);
}
@Test(expected = NotOfficeXmlFileException.class)
@Test
public void testTidyStreamOnInvalidFile4() throws Exception {
openInvalidFile("SampleSS.txt", true);
}
@Test(expected = InvalidFormatException.class)
@Test
public void testBug62592() throws Exception {
InputStream is = openSampleStream("62592.thmx");
/*OPCPackage p =*/ OPCPackage.open(is);
try (InputStream is = openSampleStream("62592.thmx")) {
assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is));
}
}
@Test
@ -1049,20 +1043,23 @@ public final class TestPackage {
private static void openInvalidFile(final String name, final boolean useStream) throws IOException, InvalidFormatException {
ZipPackage pkgTest = null;
private static void openInvalidFile(final String name, final boolean useStream) throws IOException {
ZipPackage[] pkgTest = { null };
try (final InputStream is = (useStream) ? xlsSamples.openResourceAsStream(name) : null) {
try (final ZipPackage pkg = (useStream) ? new ZipPackage(is, PackageAccess.READ) : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) {
pkgTest = pkg;
assertNotNull(pkg.getZipArchive());
assertFalse(pkg.getZipArchive().isClosed());
pkg.getParts();
fail("Shouldn't work");
}
assertThrows(NotOfficeXmlFileException.class, () -> {
try (final ZipPackage pkg = (useStream)
? new ZipPackage(is, PackageAccess.READ)
: new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) {
pkgTest[0] = pkg;
assertNotNull(pkg.getZipArchive());
assertFalse(pkg.getZipArchive().isClosed());
pkg.getParts();
}
});
} finally {
if (pkgTest != null) {
assertNotNull(pkgTest.getZipArchive());
assertTrue(pkgTest.getZipArchive().isClosed());
if (pkgTest[0] != null) {
assertNotNull(pkgTest[0].getZipArchive());
assertTrue(pkgTest[0].getZipArchive().isClosed());
}
}
}
@ -1075,7 +1072,7 @@ public final class TestPackage {
Files.copy(testFile, tmpFile);
int numPartsBefore = 0;
String md5Before = Files.hash(tmpFile, Hashing.md5()).toString();
String md5Before = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString();
RuntimeException ex = null;
try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE))
@ -1091,11 +1088,11 @@ public final class TestPackage {
ex = e;
}
// verify there was an exception while closing the file
assertNotNull("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex);
assertNotNull(ex, "Fail to save: an error occurs while saving the package : Bugzilla 63029");
assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage());
// assert that md5 after closing is the same, i.e. the source is left intact
String md5After = Files.hash(tmpFile, Hashing.md5()).toString();
String md5After = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString();
assertEquals(md5Before, md5After);
// try to read the source file once again

View File

@ -33,11 +33,11 @@ import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty;
import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public final class TestPackageCoreProperties {
/**
@ -229,31 +229,29 @@ public final class TestPackageCoreProperties {
@Test
public void testEntitiesInCoreProps_56164() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml");
OPCPackage p = OPCPackage.open(is);
is.close();
try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml");
OPCPackage p = OPCPackage.open(is)) {
// Should have 3 root relationships
boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
for (PackageRelationship pr : p.getRelationships()) {
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT))
foundDocRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES))
foundCorePropRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
foundExtPropRel = true;
// Should have 3 root relationships
boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
for (PackageRelationship pr : p.getRelationships()) {
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT))
foundDocRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES))
foundCorePropRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
foundExtPropRel = true;
}
assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships());
assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships());
assertTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships());
// Get the Core Properties
PackagePropertiesPart props = (PackagePropertiesPart) p.getPackageProperties();
// used to resolve a value but now we ignore DTD entities for security reasons
assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent());
}
assertTrue("Core/Doc Relationship not found in " + p.getRelationships(), foundDocRel);
assertTrue("Core Props Relationship not found in " + p.getRelationships(), foundCorePropRel);
assertTrue("Ext Props Relationship not found in " + p.getRelationships(), foundExtPropRel);
// Get the Core Properties
PackagePropertiesPart props = (PackagePropertiesPart)p.getPackageProperties();
// used to resolve a value but now we ignore DTD entities for security reasons
assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent());
p.close();
}
@Test

View File

@ -17,9 +17,9 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public final class TestPackagePartName {

View File

@ -17,13 +17,14 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test the addition of thumbnail in a package.
@ -42,25 +43,19 @@ public final class TestPackageThumbnail {
File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx");
// Open package
OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE);
try {
try (OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE)) {
p.addThumbnail(imagePath);
// Save the package in the output directory
p.save(outputFile);
// Open the newly created file to check core properties saved values.
OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
try {
if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
.size() == 0)
fail("Thumbnail not added to the package !");
} finally {
p2.revert();
p2.close();
try (OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ)) {
assertNotEquals(0, p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL).size(),
"Thumbnail not added to the package !");
p2.revert();
}
} finally {
p.revert();
assertTrue(outputFile.delete());
p.revert();
}
assertTrue(outputFile.delete());
}
}

View File

@ -16,13 +16,13 @@
==================================================================== */
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.net.URI;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestPackagingURIHelper {
@ -92,8 +92,7 @@ public class TestPackagingURIHelper {
// Relative part name
PackagePartName relativeName = PackagingURIHelper.createPartName(
"media/image1.gif", partBase);
assertEquals("The part name must be equal to "
+ partNameToValid.getName(), partNameToValid, relativeName);
assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName());
pkg.revert();
}
@ -113,8 +112,7 @@ public class TestPackagingURIHelper {
// Relative part name
PackagePartName relativeName = PackagingURIHelper.createPartName(
new URI("media/image1.gif"), partBase);
assertEquals("The part name must be equal to "
+ partNameToValid.getName(), partNameToValid, relativeName);
assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName());
pkg.revert();
}

View File

@ -19,10 +19,10 @@ package org.apache.poi.openxml4j.opc;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -33,7 +33,7 @@ import java.util.regex.Pattern;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestRelationships {
@ -66,7 +66,7 @@ public class TestRelationships {
assertNotNull(rel);
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
PackagePart sheetPart = pkg.getPart(relName);
assertEquals("Number of relationships1 for " + sheetPart.getPartName(), 1, sheetPart.getRelationships().size());
assertEquals(1, sheetPart.getRelationships().size(), "Number of relationships1 for " + sheetPart.getPartName());
}
}
}
@ -430,16 +430,13 @@ public class TestRelationships {
// Should have 3 root relationships
boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
for (PackageRelationship pr : p.getRelationships()) {
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT))
foundDocRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES))
foundCorePropRel = true;
if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
foundExtPropRel = true;
foundDocRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT);
foundCorePropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES);
foundExtPropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES);
}
assertEquals("Core/Doc Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundDocRel);
assertEquals("Core Props Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundCorePropRel);
assertEquals("Ext Props Relationship not found in " + p.getRelationships(), isOldXercesActive(), foundExtPropRel);
assertEquals(isOldXercesActive(), foundDocRel, "Core Doc Relationship not found in " + p.getRelationships());
assertEquals(isOldXercesActive(), foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships());
assertEquals(isOldXercesActive(), foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships());
}
}
}

View File

@ -17,11 +17,12 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
@ -34,7 +35,7 @@ import java.util.TreeMap;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.poi.util.IOUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
@ -55,14 +56,14 @@ public final class ZipFileAssert {
TreeMap<String, ByteArrayOutputStream> file1,
TreeMap<String, ByteArrayOutputStream> file2) {
Set<String> listFile1 = file1.keySet();
Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size());
Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:");
for (String fileName : listFile1) {
// extract the contents for both
ByteArrayOutputStream contain1 = file1.get(fileName);
ByteArrayOutputStream contain2 = file2.get(fileName);
assertNotNull(fileName + " not found in 2nd zip", contain2);
assertNotNull(contain2, fileName + " not found in 2nd zip");
// no need to check for contain1. The key come from it
if (fileName.matches(".*\\.(xml|rels)$")) {
@ -75,11 +76,11 @@ public final class ZipFileAssert {
withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
build();
assertFalse(fileName+": "+diff.toString(), diff.hasDifferences());
assertFalse(diff.hasDifferences(), fileName+": "+diff.toString());
} else {
// not xml, may be an image or other binary format
Assert.assertEquals(fileName + " does not have the same size in both zip:", contain1.size(), contain2.size());
assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray());
Assertions.assertEquals(contain1.size(), contain2.size(), fileName + " does not have the same size in both zip:");
assertArrayEquals(contain1.toByteArray(), contain2.toByteArray(), "contents differ");
}
}
}
@ -126,21 +127,12 @@ public final class ZipFileAssert {
assertNotNull(expected);
assertNotNull(actual);
assertTrue("File does not exist [" + expected.getAbsolutePath()
+ "]", expected.exists());
assertTrue("File does not exist [" + actual.getAbsolutePath()
+ "]", actual.exists());
assertTrue(expected.exists(), "File does not exist [" + expected.getAbsolutePath() + "]");
assertTrue(actual.exists(), "File does not exist [" + actual.getAbsolutePath() + "]");
assertTrue(expected.canRead(), "Expected file not readable");
assertTrue(actual.canRead(), "Actual file not readable");
assertTrue("Expected file not readable", expected.canRead());
assertTrue("Actual file not readable", actual.canRead());
try {
TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected);
TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual);
equals(file1, file2);
} catch (IOException e) {
fail(e.toString());
}
assertDoesNotThrow(() -> equals(decompress(expected), decompress(actual)));
}
private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator {

View File

@ -19,11 +19,12 @@ package org.apache.poi.openxml4j.opc.compliance;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -44,7 +45,7 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test core properties Open Packaging Convention compliance.
@ -90,20 +91,12 @@ public final class TestOPCComplianceCoreProperties {
pkg.revert();
}
private static String extractInvalidFormatMessage(String sampleNameSuffix) {
InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
OPCPackage pkg;
try {
pkg = OPCPackage.open(is);
} catch (InvalidFormatException e) {
// no longer required for successful test
private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException {
try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) {
InvalidFormatException e = assertThrows(InvalidFormatException.class,
() -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown");
return e.getMessage();
} catch (IOException e) {
throw new RuntimeException(e);
}
pkg.revert();
fail("expected OPC compliance exception was not thrown");
return null;
}
/**
@ -112,12 +105,12 @@ public final class TestOPCComplianceCoreProperties {
@Test
public void testOnlyOneCorePropertiesPart() throws Exception {
// We have relaxed this check, so we can read the file anyway
try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_" + "OnlyOneCorePropertiesPartFAIL.docx");
OPCPackage pkg = OPCPackage.open(is)) {
assertNotNull(pkg);
} catch (Exception e) {
fail("M4.1 should be being relaxed");
}
assertDoesNotThrow(() -> {
try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx");
OPCPackage pkg = OPCPackage.open(is)) {
assertNotNull(pkg);
}
}, "M4.1 should be being relaxed");
// We will use the first core properties, and ignore the others
@ -148,55 +141,41 @@ public final class TestOPCComplianceCoreProperties {
* Test M4.1 rule.
*/
@Test
public void testOnlyOneCorePropertiesPart_AddRelationship() {
InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
OPCPackage pkg;
try {
pkg = OPCPackage.open(is);
} catch (InvalidFormatException | IOException e) {
throw new RuntimeException(e);
}
URI partUri = createURI("/docProps/core2.xml");
try {
pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL,
PackageRelationshipTypes.CORE_PROPERTIES);
// no longer fail on compliance error
//fail("expected OPC compliance exception was not thrown");
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} catch (InvalidOperationException e) {
// expected during successful test
public void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException {
try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
OPCPackage pkg = OPCPackage.open(is);
URI partUri = createURI("/docProps/core2.xml");
InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES),
"expected OPC compliance exception was not thrown"
);
assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage());
pkg.revert();
}
pkg.revert();
}
/**
* Test M4.1 rule.
*/
@Test
public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException {
public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException {
String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath());
try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
URI partUri = createURI("/docProps/core2.xml");
try {
pkg.createPart(PackagingURIHelper.createPartName(partUri),
ContentTypes.CORE_PROPERTIES_PART);
// no longer fail on compliance error
//fail("expected OPC compliance exception was not thrown");
} catch (InvalidOperationException e) {
// expected during successful test
URI partUri = createURI("/docProps/core2.xml");
InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
pkg.createPart(PackagingURIHelper.createPartName(partUri), ContentTypes.CORE_PROPERTIES_PART),
"expected OPC compliance exception was not thrown");
assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage());
pkg.revert();
}
pkg.revert();
}
/**
* Test M4.2 rule.
*/
@Test
public void testDoNotUseCompatibilityMarkup() {
public void testDoNotUseCompatibilityMarkup() throws IOException {
String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx");
assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg);
}
@ -205,7 +184,7 @@ public final class TestOPCComplianceCoreProperties {
* Test M4.3 rule.
*/
@Test
public void testDCTermsNamespaceLimitedUse() {
public void testDCTermsNamespaceLimitedUse() throws IOException {
String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx");
assertEquals("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
@ -214,7 +193,7 @@ public final class TestOPCComplianceCoreProperties {
* Test M4.4 rule.
*/
@Test
public void testUnauthorizedXMLLangAttribute() {
public void testUnauthorizedXMLLangAttribute() throws IOException {
String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx");
assertEquals("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
@ -223,7 +202,7 @@ public final class TestOPCComplianceCoreProperties {
* Test M4.5 rule.
*/
@Test
public void testLimitedXSITypeAttribute_NotPresent() {
public void testLimitedXSITypeAttribute_NotPresent() throws IOException {
String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx");
assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg);
}
@ -232,7 +211,7 @@ public final class TestOPCComplianceCoreProperties {
* Test M4.5 rule.
*/
@Test
public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() {
public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() throws IOException {
String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx");
assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg);
}
@ -244,45 +223,43 @@ public final class TestOPCComplianceCoreProperties {
@Test
public void testNoCoreProperties_saveNew() throws Exception {
String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath());
// Verify it has empty properties
assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// Save and re-load
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pkg.save(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
pkg.revert();
pkg = OPCPackage.open(bais);
try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
// Verify it has empty properties
assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// An Empty Properties part has been added in the save/load
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
pkg.close();
// Save and re-load
pkg.save(baos);
pkg.revert();
}
try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
// An Empty Properties part has been added in the save/load
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
}
// Open a new copy of it
pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath());
try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
// Save and re-load, without having touched the properties yet
baos.reset();
pkg.save(baos);
pkg.revert();
}
// Save and re-load, without having touched the properties yet
baos = new ByteArrayOutputStream();
pkg.save(baos);
pkg.revert();
bais = new ByteArrayInputStream(baos.toByteArray());
pkg = OPCPackage.open(bais);
// Check that this too added empty properties without error
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
// Check that this too added empty properties without error
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
}
}
/**
@ -295,37 +272,34 @@ public final class TestOPCComplianceCoreProperties {
// Copy this into a temp file, so we can play with it
File tmp = TempFile.createTempFile("poi-test", ".opc");
FileOutputStream out = new FileOutputStream(tmp);
InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName);
IOUtils.copy(
in,
out);
out.close();
in.close();
try (FileOutputStream out = new FileOutputStream(tmp);
InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) {
IOUtils.copy(in, out);
}
// Open it from that temp file
OPCPackage pkg = OPCPackage.open(tmp);
try (OPCPackage pkg = OPCPackage.open(tmp)) {
// Empty properties
assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// Empty properties
assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// Save and close
pkg.close();
// Save and close
}
// Re-open and check
pkg = OPCPackage.open(tmp);
try (OPCPackage pkg = OPCPackage.open(tmp)) {
// An Empty Properties part has been added in the save/load
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// An Empty Properties part has been added in the save/load
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
// Finish and tidy
pkg.revert();
// Finish and tidy
pkg.revert();
}
assertTrue(tmp.delete());
}
}

View File

@ -17,8 +17,10 @@
package org.apache.poi.openxml4j.opc.compliance;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import org.apache.poi.POIDataSamples;
@ -31,42 +33,31 @@ import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.junit.Test;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Open Packaging Convention package model compliance.
*
* M1.11 : A package implementer shall neither create nor recognize a part with
* a part name derived from another part name by appending segments to it.
*
* @author Julien Chable
*/
public class TestOPCCompliancePackageModel {
/**
* A package implementer shall neither create nor recognize a part with a
* part name derived from another part name by appending segments to it.
* [M1.11]
*/
@Test
public void testPartNameDerivationAdditionFailure() {
OPCPackage pkg = OPCPackage.create("TODELETEIFEXIST.docx");
try {
PackagePartName name = PackagingURIHelper
.createPartName("/word/document.xml");
PackagePartName nameDerived = PackagingURIHelper
.createPartName("/word/document.xml/image1.gif");
pkg.createPart(name, ContentTypes.XML);
pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF);
} catch (InvalidOperationException e) {
pkg.revert();
return;
} catch (InvalidFormatException e) {
fail(e.getMessage());
private static File TESTFILE;
@BeforeAll
public static void setup() throws IOException {
TESTFILE = TempFile.createTempFile("TODELETEIFEXIST", ".docx");
}
@BeforeEach
public void tearDown() {
if (TESTFILE.exists()) {
assertTrue(TESTFILE.delete());
}
fail("A package implementer shall neither create nor recognize a part with a"
+ " part name derived from another part name by appending segments to it."
+ " [M1.11]");
}
/**
@ -75,16 +66,32 @@ public class TestOPCCompliancePackageModel {
* [M1.11]
*/
@Test
public void testPartNameDerivationReadingFailure() throws IOException {
String filename = "OPCCompliance_DerivedPartNameFAIL.docx";
try {
OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename));
} catch (InvalidFormatException e) {
return;
public void testPartNameDerivationAdditionFailure() throws InvalidFormatException, IOException {
try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
PackagePartName name = PackagingURIHelper.createPartName("/word/document.xml");
PackagePartName nameDerived = PackagingURIHelper.createPartName("/word/document.xml/image1.gif");
pkg.createPart(name, ContentTypes.XML);
assertThrows(InvalidOperationException.class, () -> pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF),
"A package implementer shall neither create nor recognize a part with a part name derived from another " +
"part name by appending segments to it. [M1.11]");
pkg.revert();
}
fail("A package implementer shall neither create nor recognize a part with a"
+ " part name derived from another part name by appending segments to it."
+ " [M1.11]");
}
/**
* A package implementer shall neither create nor recognize a part with a
* part name derived from another part name by appending segments to it.
* [M1.11]
*/
@Test
public void testPartNameDerivationReadingFailure() {
String filename = "OPCCompliance_DerivedPartNameFAIL.docx";
assertThrows(InvalidFormatException.class, () ->
OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)),
"A package implementer shall neither create nor recognize a part with a part name derived from another" +
" part name by appending segments to it. [M1.11]"
);
}
/**
@ -94,22 +101,17 @@ public class TestOPCCompliancePackageModel {
*/
@Test
public void testAddPackageAlreadyAddFailure() throws Exception {
OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
PackagePartName name1 = null;
PackagePartName name2 = null;
try {
name1 = PackagingURIHelper.createPartName("/word/document.xml");
name2 = PackagingURIHelper.createPartName("/word/document.xml");
} catch (InvalidFormatException e) {
throw new Exception(e.getMessage());
try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
PackagePartName name1 = PackagingURIHelper.createPartName("/word/document.xml");
PackagePartName name2 = PackagingURIHelper.createPartName("/word/document.xml");
pkg.createPart(name1, ContentTypes.XML);
assertThrows(PartAlreadyExistsException.class, () -> pkg.createPart(name2, ContentTypes.XML),
"Packages shall not contain equivalent part names and package implementers shall neither create nor " +
"recognize packages with equivalent part names. [M1.12]"
);
pkg.revert();
}
pkg.createPart(name1, ContentTypes.XML);
try {
pkg.createPart(name2, ContentTypes.XML);
} catch (PartAlreadyExistsException e) {
return;
}
fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
}
/**
@ -119,20 +121,15 @@ public class TestOPCCompliancePackageModel {
*/
@Test
public void testAddPackageAlreadyAddFailure2() throws Exception {
OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
PackagePartName partName = null;
try {
partName = PackagingURIHelper.createPartName("/word/document.xml");
} catch (InvalidFormatException e) {
throw new Exception(e.getMessage());
}
pkg.createPart(partName, ContentTypes.XML);
try {
try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
PackagePartName partName = PackagingURIHelper.createPartName("/word/document.xml");
pkg.createPart(partName, ContentTypes.XML);
} catch (InvalidOperationException e) {
return;
assertThrows(InvalidOperationException.class, () -> pkg.createPart(partName, ContentTypes.XML),
"Packages shall not contain equivalent part names and package implementers shall neither create nor " +
"recognize packages with equivalent part names. [M1.12]"
);
pkg.revert();
}
fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
}
/**
@ -144,22 +141,15 @@ public class TestOPCCompliancePackageModel {
* relationship as invalid.
*/
@Test
public void testAddRelationshipRelationshipsPartFailure() {
OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
PackagePartName name1 = null;
try {
name1 = PackagingURIHelper
.createPartName("/test/_rels/document.xml.rels");
} catch (InvalidFormatException e) {
fail("This exception should never happen !");
}
public void testAddRelationshipRelationshipsPartFailure() throws IOException, InvalidFormatException {
try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
PackagePartName name1 = PackagingURIHelper.createPartName("/test/_rels/document.xml.rels");
try {
pkg.addRelationship(name1, TargetMode.INTERNAL,
PackageRelationshipTypes.CORE_DOCUMENT);
} catch (InvalidOperationException e) {
return;
assertThrows(InvalidOperationException.class,
() -> pkg.addRelationship(name1, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT),
"The Relationships part shall not have relationships to any other part [M1.25]"
);
pkg.revert();
}
fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part");
}
}

View File

@ -17,19 +17,20 @@
package org.apache.poi.openxml4j.opc.compliance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.isValidPartName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test part name Open Packaging Convention compliance.
@ -100,8 +101,7 @@ public final class TestOPCCompliancePartName {
assertEquals("[Content_Types].xml", s);
continue;
}
assertFalse("This part name SHOULD NOT be valid: " + s,
PackagingURIHelper.isValidPartName(uri));
assertFalse(isValidPartName(uri), "This part name SHOULD NOT be valid: " + s);
}
}
@ -110,24 +110,19 @@ public final class TestOPCCompliancePartName {
*/
@Test
public void testValidPartNames() throws URISyntaxException {
String[] validNames = { "/xml/item1.xml", "/document.xml",
"/a/%D1%86.xml" };
for (String s : validNames)
assertTrue("This part name SHOULD be valid: " + s,
PackagingURIHelper.isValidPartName(new URI(s)));
String[] validNames = { "/xml/item1.xml", "/document.xml", "/a/%D1%86.xml" };
for (String s : validNames) {
assertTrue(isValidPartName(new URI(s)), "This part name SHOULD be valid: " + s);
}
}
/**
* A part name shall not be empty. [M1.1]
*/
@Test
public void testEmptyPartNameFailure() throws URISyntaxException {
try {
PackagingURIHelper.createPartName(new URI(""));
fail("A part name shall not be empty. [M1.1]");
} catch (InvalidFormatException e) {
// Normal behaviour
}
public void testEmptyPartNameFailure() {
assertThrows(InvalidFormatException.class, () -> createPartName(new URI("")),
"A part name shall not be empty. [M1.1]");
}
/**
@ -138,18 +133,13 @@ public final class TestOPCCompliancePartName {
* A segment shall include at least one non-dot character. [M1.10]
*/
@Test
public void testPartNameWithInvalidSegmentsFailure() {
public void testPartNameWithInvalidSegmentsFailure() throws URISyntaxException {
String[] invalidNames = { "//document.xml", "//word/document.xml",
"/word//document.rels", "/word//rels//document.rels",
"/xml./doc.xml", "/document.", "/./document.xml",
"/word/./doc.rels", "/%2F/document.xml" };
try {
for (String s : invalidNames)
assertFalse(
"A part name shall not have empty segments. [M1.3]",
PackagingURIHelper.isValidPartName(new URI(s)));
} catch (URISyntaxException e) {
fail();
for (String s : invalidNames) {
assertFalse(isValidPartName(new URI(s)), "A part name shall not have empty segments. [M1.3]");
}
}
@ -158,16 +148,11 @@ public final class TestOPCCompliancePartName {
* [M1.6].
*/
@Test
public void testPartNameWithNonPCharCharacters() {
public void testPartNameWithNonPCharCharacters() throws URISyntaxException {
String[] validNames = { "/doc&.xml" };
try {
for (String s : validNames)
assertTrue(
"A segment shall not contain non pchar characters [M1.6] : "
+ s, PackagingURIHelper
.isValidPartName(new URI(s)));
} catch (URISyntaxException e) {
fail();
for (String s : validNames) {
assertTrue(isValidPartName(new URI(s)),
"A segment shall not contain non pchar characters [M1.6] : " + s);
}
}
@ -175,16 +160,10 @@ public final class TestOPCCompliancePartName {
* A segment shall not contain percent-encoded unreserved characters [M1.8].
*/
@Test
public void testPartNameWithUnreservedEncodedCharactersFailure() {
public void testPartNameWithUnreservedEncodedCharactersFailure() throws URISyntaxException {
String[] invalidNames = { "/a/docum%65nt.xml" };
try {
for (String s : invalidNames)
assertFalse(
"A segment shall not contain percent-encoded unreserved characters [M1.8] : "
+ s, PackagingURIHelper
.isValidPartName(new URI(s)));
} catch (URISyntaxException e) {
fail();
for (String s : invalidNames) {
assertFalse(isValidPartName(new URI(s)), "A segment shall not contain percent-encoded unreserved characters [M1.8] : " + s);
}
}
@ -192,28 +171,18 @@ public final class TestOPCCompliancePartName {
* A part name shall start with a forward slash ('/') character. [M1.4]
*/
@Test
public void testPartNameStartsWithAForwardSlashFailure()
throws URISyntaxException {
try {
PackagingURIHelper.createPartName(new URI("document.xml"));
fail("A part name shall start with a forward slash ('/') character. [M1.4]");
} catch (InvalidFormatException e) {
// Normal behaviour
}
public void testPartNameStartsWithAForwardSlashFailure() {
assertThrows(InvalidFormatException.class, () -> createPartName(new URI("document.xml")),
"A part name shall start with a forward slash ('/') character. [M1.4]");
}
/**
* A part name shall not have a forward slash as the last character. [M1.5]
*/
@Test
public void testPartNameEndsWithAForwardSlashFailure()
throws URISyntaxException {
try {
PackagingURIHelper.createPartName(new URI("/document.xml/"));
fail("A part name shall not have a forward slash as the last character. [M1.5]");
} catch (InvalidFormatException e) {
// Normal behaviour
}
public void testPartNameEndsWithAForwardSlashFailure() {
assertThrows(InvalidFormatException.class, () -> createPartName(new URI("/document.xml/")),
"A part name shall not have a forward slash as the last character. [M1.5]");
}
/**
@ -225,8 +194,8 @@ public final class TestOPCCompliancePartName {
String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" };
for (int i = 0; i < partName1.length || i < partName2.length; ++i) {
PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]);
PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]);
PackagePartName p1 = createPartName(partName1[i]);
PackagePartName p2 = createPartName(partName2[i]);
assertEquals(p1, p2);
assertEquals(0, p1.compareTo(p2));
assertEquals(p1.hashCode(), p2.hashCode());
@ -244,8 +213,8 @@ public final class TestOPCCompliancePartName {
String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" };
for (int i = 0; i < partName1.length || i < partName2.length; ++i) {
PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]);
PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]);
PackagePartName p1 = createPartName(partName1[i]);
PackagePartName p2 = createPartName(partName2[i]);
assertNotEquals(p1, p2);
assertNotEquals(0, p1.compareTo(p2));
assertNotEquals(p1.hashCode(), p2.hashCode());

View File

@ -17,9 +17,8 @@
package org.apache.poi.openxml4j.opc.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -47,8 +46,8 @@ import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;
@ -127,11 +126,10 @@ public final class TestContentTypeManager {
/**
* Test the addition then removal of content types in a package.
*/
@Ignore
@Disabled
@Test
public void testContentTypeRemovalPackage() {
// TODO
fail("test not written");
}
protected byte[] toByteArray(Workbook wb) {

View File

@ -18,7 +18,8 @@
package org.apache.poi.openxml4j.opc.internal.marshallers;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -27,40 +28,45 @@ import java.io.OutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestZipPackagePropertiesMarshaller {
private PartMarshaller marshaller = new ZipPackagePropertiesMarshaller();
private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller();
@Test(expected=IllegalArgumentException.class)
public void nonZipOutputStream() throws OpenXML4JException {
private boolean marshall() throws OpenXML4JException {
return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream()));
}
private boolean marshall(OutputStream zos) throws OpenXML4JException {
PackagePartName rootUri = PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI);
PackagePropertiesPart part = new PackagePropertiesPart(null, rootUri);
return marshaller.marshall(part, zos);
}
@Test
public void nonZipOutputStream() {
OutputStream notAZipOutputStream = new ByteArrayOutputStream(0);
marshaller.marshall(null, notAZipOutputStream);
assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream));
}
@Test
public void withZipOutputStream() throws Exception {
assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)),
new ZipArchiveOutputStream(new ByteArrayOutputStream())));
assertTrue(marshall());
}
@Test
public void writingFails() throws Exception {
assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)),
new ZipArchiveOutputStream(new ByteArrayOutputStream())));
}
@Test(expected=OpenXML4JException.class)
public void ioException() throws Exception {
marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)),
new ZipArchiveOutputStream(new ByteArrayOutputStream()) {
@Override
public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
throw new IOException("TestException");
}
});
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) {
@Override
public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
throw new IOException("TestException");
}
};
assertThrows(OpenXML4JException.class, () -> marshall(zos));
}
}

View File

@ -20,12 +20,12 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.Enumeration;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestZipSecureFile {
@Test

View File

@ -16,19 +16,19 @@
==================================================================== */
package org.apache.poi.poifs.crypt.dsig;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.Base64;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class TestSignatureConfig {
@Test
@Ignore("failing in automated builds, due to issues loading security classes")
@Disabled("failing in automated builds, due to issues loading security classes")
public void testDigestAlgo() throws Exception {
SignatureConfig sc = new SignatureConfig();
assertEquals(HashAlgorithm.sha256, sc.getDigestAlgo());
@ -53,7 +53,7 @@ public class TestSignatureConfig {
final HashAlgorithm ha = HashAlgorithm.valueOf(check[0]);
try (final DigestOutputStream dos = new DigestOutputStream(ha, null)) {
final String magic = Base64.getEncoder().encodeToString(dos.getHashMagic());
assertEquals("hash digest magic mismatches", check[1], magic);
assertEquals(check[1], magic, "hash digest magic mismatches");
}
}
}

View File

@ -23,11 +23,12 @@
================================================================= */
package org.apache.poi.poifs.crypt.dsig;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@ -152,11 +153,10 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.etsi.uri.x01903.v13.DigestAlgAndValueType;
import org.etsi.uri.x01903.v13.QualifyingPropertiesType;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.w3.x2000.x09.xmldsig.ReferenceType;
import org.w3.x2000.x09.xmldsig.SignatureDocument;
import org.w3c.dom.Document;
@ -169,12 +169,12 @@ public class TestSignatureInfo {
private KeyPair keyPair;
private X509Certificate x509;
@AfterClass
@AfterAll
public static void removeUserLocale() {
LocaleUtil.resetUserLocale();
}
@BeforeClass
@BeforeAll
public static void initBouncy() {
CryptoFunctions.registerBouncyCastle();
@ -189,8 +189,8 @@ public class TestSignatureInfo {
// in the xmlsec jar file
String additionalJar = System.getProperty("additionaljar");
//System.out.println("Having: " + additionalJar);
Assume.assumeTrue("Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar,
additionalJar == null || additionalJar.trim().length() == 0);
assumeTrue(additionalJar == null || additionalJar.trim().length() == 0,
"Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar);
System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");
@ -198,7 +198,7 @@ public class TestSignatureInfo {
// System.setProperty("line.separator", "\n");
}
@Ignore("This test is very sensitive, it breaks with every little change to the produced XML")
@Disabled("This test is very sensitive, it breaks with every little change to the produced XML")
@Test
public void bug61182() throws Exception {
final String pfxInput =
@ -277,7 +277,7 @@ public class TestSignatureInfo {
// separator set to the various system configurations
String sep = SystemProperties.getProperty("line.separator");
String signExp;
assumeTrue("Hashes only known for Windows/Unix/Mac", sep == null || "\n".equals(sep) || "\r\n".equals(sep) || "\r".equals(sep));
assumeTrue(sep == null || "\n".equals(sep) || "\r\n".equals(sep) || "\r".equals(sep), "Hashes only known for Windows/Unix/Mac");
signExp = (sep == null || "\n".equals(sep)) ? unixSignExp : ("\r\n".equals(sep)) ? winSignExp : macSignExp;
String signAct = si.getSignatureParts().iterator().next().
@ -355,12 +355,12 @@ public class TestSignatureInfo {
}
assertNotNull(result);
assertEquals("test-file: " + testFile, 1, result.size());
assertEquals(1, result.size(), "test-file: " + testFile);
X509Certificate signer = result.get(0);
LOG.log(POILogger.DEBUG, "signer: ", signer.getSubjectX500Principal());
boolean b = si.verifySignature();
assertTrue("test-file: " + testFile, b);
assertTrue(b, "test-file: " + testFile);
pkg.revert();
}
}
@ -382,14 +382,14 @@ public class TestSignatureInfo {
}
assertNotNull(result);
assertEquals("test-file: " + testFile, 2, result.size());
assertEquals(2, result.size(), "test-file: " + testFile);
X509Certificate signer1 = result.get(0);
X509Certificate signer2 = result.get(1);
LOG.log(POILogger.DEBUG, "signer 1: ", signer1.getSubjectX500Principal());
LOG.log(POILogger.DEBUG, "signer 2: ", signer2.getSubjectX500Principal());
boolean b = si.verifySignature();
assertTrue("test-file: " + testFile, b);
assertTrue(b, "test-file: " + testFile);
pkg.revert();
}
}
@ -433,7 +433,7 @@ public class TestSignatureInfo {
si.setOpcPackage(pkg);
si.setSignatureConfig(sic);
boolean b = si.verifySignature();
assertFalse("signature should be broken", b);
assertFalse(b, "signature should be broken");
}
}
}
@ -555,21 +555,21 @@ public class TestSignatureInfo {
throw e;
}
if ((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) {
Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e,
e.getCause().getMessage().contains("timed out"));
assumeFalse(e.getCause().getMessage().contains("timed out"),
"Only allowing ConnectException with 'timed out' as message here, but had: " + e);
} else if (e.getCause() instanceof IOException) {
Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,
e.getCause().getMessage().contains("Error contacting TSP server"));
assumeFalse(e.getCause().getMessage().contains("Error contacting TSP server"),
"Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e);
} else if (e.getCause() instanceof RuntimeException) {
Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,
e.getCause().getMessage().contains("This site is cur"));
assumeFalse(e.getCause().getMessage().contains("This site is cur"),
"Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e);
}
throw e;
}
// verify
Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
assertTrue("Had: " + pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN), spIter.hasNext());
assertTrue(spIter.hasNext(), "Had: " + pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN));
SignaturePart sp = spIter.next();
boolean valid = sp.validate();
assertTrue(valid);
@ -697,9 +697,9 @@ public class TestSignatureInfo {
si.confirmSignature();
for (SignaturePart sp : si.getSignatureParts()) {
assertTrue("Could not validate", sp.validate());
assertTrue(sp.validate(), "Could not validate");
X509Certificate signer = sp.getSigner();
assertNotNull("signer undefined?!", signer);
assertNotNull(signer, "signer undefined?!");
List<X509Certificate> certChainRes = sp.getCertChain();
// IBM JDK is still buggy, even after fix for APAR IJ21985
@ -731,9 +731,9 @@ public class TestSignatureInfo {
si.confirmSignature();
boolean b = si.verifySignature();
assertTrue("Signature not correctly calculated for " + ha, b);
assertTrue(b, "Signature not correctly calculated for " + ha);
} catch (EncryptedDocumentException e) {
Assume.assumeTrue(e.getMessage().startsWith("Export Restrictions"));
assumeTrue(e.getMessage().startsWith("Export Restrictions"));
}
}
}
@ -758,7 +758,7 @@ public class TestSignatureInfo {
si.setOpcPackage(pkg);
si.setSignatureConfig(signatureConfig);
si.confirmSignature();
assertTrue("invalid signature", si.verifySignature());
assertTrue(si.verifySignature(), "invalid signature");
}
}
}
@ -1087,7 +1087,7 @@ public class TestSignatureInfo {
// in the Sonar Maven runs where we are at a different source directory
File buildDir = new File("build");
if(!buildDir.exists()) {
assertTrue("Failed to create " + buildDir.getAbsolutePath(), buildDir.mkdirs());
assertTrue(buildDir.mkdirs(), "Failed to create " + buildDir.getAbsolutePath());
}
File tmpFile = new File(buildDir, "sigtest"+extension);

View File

@ -1,35 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.poifs.crypt.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Tests for org.apache.poi.poifs.crypt
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestEncryptionInfo.class
, TestDecryptor.class
, TestEncryptor.class
, TestAgileEncryptionParameters.class
})
public final class AllPOIFSCryptoTests {
}

View File

@ -16,16 +16,17 @@
==================================================================== */
package org.apache.poi.poifs.crypt.tests;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
import javax.crypto.Cipher;
@ -39,55 +40,44 @@ import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class TestAgileEncryptionParameters {
static byte[] testData;
@Parameter(value = 0)
public CipherAlgorithm ca;
@Parameter(value = 1)
public HashAlgorithm ha;
@Parameter(value = 2)
public ChainingMode cm;
@Parameters(name="{0} {1} {2}")
public static Collection<Object[]> data() {
public static Stream<Arguments> data() {
CipherAlgorithm[] caList = {CipherAlgorithm.aes128, CipherAlgorithm.aes192, CipherAlgorithm.aes256, CipherAlgorithm.rc2, CipherAlgorithm.des, CipherAlgorithm.des3};
HashAlgorithm[] haList = {HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.md5};
ChainingMode[] cmList = {ChainingMode.cbc, ChainingMode.cfb};
List<Object[]> data = new ArrayList<>();
List<Arguments> data = new ArrayList<>();
for (CipherAlgorithm ca : caList) {
for (HashAlgorithm ha : haList) {
for (ChainingMode cm : cmList) {
data.add(new Object[]{ca,ha,cm});
data.add(Arguments.of(ca,ha,cm));
}
}
}
return data;
return data.stream();
}
@BeforeClass
@BeforeAll
public static void initTestData() throws Exception {
InputStream testFile = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.docx");
testData = IOUtils.toByteArray(testFile);
testFile.close();
}
@Test
public void testAgileEncryptionModes() throws Exception {
@ParameterizedTest
@MethodSource("data")
public void testAgileEncryptionModes(CipherAlgorithm ca, HashAlgorithm ha, ChainingMode cm) throws Exception {
int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId);
Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files", maxKeyLen >= ca.defaultKeySize);
assumeTrue(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@ -111,6 +101,6 @@ public class TestAgileEncryptionParameters {
byte[] actualData = IOUtils.toByteArray(is);
is.close();
fsDec.close();
assertArrayEquals("Failed roundtrip - "+ca+"-"+ha+"-"+cm, testData, actualData);
assertArrayEquals(testData, actualData, "Failed roundtrip - "+ca+"-"+ha+"-"+cm);
}
}

View File

@ -16,10 +16,10 @@
==================================================================== */
package org.apache.poi.poifs.crypt.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -27,7 +27,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.stream.IntStream;
import javax.crypto.Cipher;
@ -39,8 +38,7 @@ import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestDecryptor {
private static final POIDataSamples samples = POIDataSamples.getPOIFSInstance();
@ -94,7 +92,7 @@ public class TestDecryptor {
byte[] buf = new byte[10];
int readBytes = zin.read(buf);
// zin.available() doesn't work for entries
assertEquals("size failed for " + entry.getName(), 1, readBytes);
assertEquals(1, readBytes, "size failed for " + entry.getName());
}
}
}
@ -142,17 +140,14 @@ public class TestDecryptor {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
try (final ZipArchiveInputStream zis = new ZipArchiveInputStream(d.getDataStream(fs))) {
IntStream.of(3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910).forEach(size -> {
try {
final ZipArchiveEntry ze = zis.getNextZipEntry();
assertNotNull(ze);
IOUtils.copy(zis, bos);
assertEquals(size, bos.size());
bos.reset();
} catch (IOException e) {
fail(e.getMessage());
}
});
int[] sizes = { 3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910 };
for (int size : sizes) {
final ZipArchiveEntry ze = zis.getNextZipEntry();
assertNotNull(ze);
IOUtils.copy(zis, bos);
assertEquals(size, bos.size());
bos.reset();
}
}
}
}
@ -170,7 +165,7 @@ public class TestDecryptor {
@Test
public void bug60320() throws IOException, GeneralSecurityException {
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647);
assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");
try (InputStream is = samples.openResourceAsStream("60320-protected.xlsx");
POIFSFileSystem fs = new POIFSFileSystem(is)) {

View File

@ -16,7 +16,7 @@
==================================================================== */
package org.apache.poi.poifs.crypt.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
@ -26,8 +26,7 @@ import org.apache.poi.poifs.crypt.CipherProvider;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestEncryptionInfo {
@Test
@ -39,11 +38,11 @@ public class TestEncryptionInfo {
assertEquals(3, info.getVersionMajor());
assertEquals(2, info.getVersionMinor());
Assert.assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm());
Assert.assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm());
assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm());
assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm());
assertEquals(128, info.getHeader().getKeySize());
assertEquals(32, info.getVerifier().getEncryptedVerifierHash().length);
Assert.assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider());
assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider());
assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName());
fs.close();

View File

@ -17,11 +17,12 @@
package org.apache.poi.poifs.crypt.tests;
import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -62,9 +63,8 @@ import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.TempFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class TestEncryptor {
@Test
@ -146,7 +146,7 @@ public class TestEncryptor {
@Test
public void agileEncryption() throws Exception {
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647);
assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");
File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx");
String pass = "pass";
@ -162,7 +162,7 @@ public class TestEncryptor {
infoExpected = new EncryptionInfo(nfs);
decExpected = Decryptor.getInstance(infoExpected);
boolean passed = decExpected.verifyPassword(pass);
assertTrue("Unable to process: document is encrypted", passed);
assertTrue(passed, "Unable to process: document is encrypted");
// extract the payload
try (InputStream is = decExpected.getDataStream(nfs)) {
@ -217,7 +217,7 @@ public class TestEncryptor {
infoActual2 = new EncryptionInfo(nfs.getRoot());
Decryptor decActual = Decryptor.getInstance(infoActual2);
boolean passed = decActual.verifyPassword(pass);
assertTrue("Unable to process: document is encrypted", passed);
assertTrue(passed, "Unable to process: document is encrypted");
// extract the payload
try (InputStream is = decActual.getDataStream(nfs)) {
@ -256,7 +256,7 @@ public class TestEncryptor {
infoExpected = new EncryptionInfo(nfs);
d = Decryptor.getInstance(infoExpected);
boolean passed = d.verifyPassword(pass);
assertTrue("Unable to process: document is encrypted", passed);
assertTrue(passed, "Unable to process: document is encrypted");
// extract the payload
try (InputStream is = d.getDataStream(nfs)) {
@ -317,7 +317,7 @@ public class TestEncryptor {
try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) {
final EncryptionInfo ei = new EncryptionInfo(nfs);
Decryptor d2 = Decryptor.getInstance(ei);
assertTrue("Unable to process: document is encrypted", d2.verifyPassword(pass));
assertTrue(d2.verifyPassword(pass), "Unable to process: document is encrypted");
try (InputStream is = d2.getDataStream(nfs)) {
payloadActual = IOUtils.toByteArray(is);
@ -383,7 +383,7 @@ public class TestEncryptor {
}
@Test
@Ignore
@Disabled
public void inPlaceRewrite() throws Exception {
File f = TempFile.createTempFile("protected_agile", ".docx");
@ -462,7 +462,7 @@ public class TestEncryptor {
@Test
public void bug60320CustomEncrypt() throws Exception {
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647);
assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");
// --- src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (revision 1766745)
// +++ src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (working copy)

View File

@ -20,18 +20,17 @@ package org.apache.poi.poifs.crypt.tests;
import static org.apache.poi.POIDataSamples.getDocumentInstance;
import static org.apache.poi.POIDataSamples.getSlideShowInstance;
import static org.apache.poi.POIDataSamples.getSpreadSheetInstance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
@ -41,28 +40,12 @@ import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader;
import org.apache.poi.poifs.storage.RawDataUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class TestHxxFEncryption {
@Parameter
public POIDataSamples sampleDir;
@Parameter(value = 1)
public String file;
@Parameter(value = 2)
public String password;
@Parameter(value = 3)
public String expected;
@Parameters(name="{1}")
public static Collection<Object[]> data() throws IOException {
public static Stream<Arguments> data() throws IOException {
final String base64 =
"H4sIAAAAAAAAAF1Uu24bMRDs/RULVwkgCUhSpHaZwkDgpHJH8fZ0G/Nx4ZI6y13yG/mRfIb9R5mlZFlIpdPtcnZmdnjPf57/vvx6+f3h6obuv3"+
"ylbY5bEiVHe1fEpUp5pOgkrK0iabehm7FyoZi1ks8xcvHiQu8h5bLnorTlnUvkJ/YPOHKsLVInAqCs91KakuaxLq4w3g00SgCo9Xou1UnCmSBe"+
@ -74,22 +57,23 @@ public class TestHxxFEncryption {
"VZw8Pm6vn0afh4fvr0D5P/+cMuBAAA";
final String x = new String(RawDataUtil.decompress(base64), StandardCharsets.UTF_8);
return Arrays.asList(
return Stream.of(
// binary rc4
new Object[]{ getDocumentInstance(), "password_tika_binaryrc4.doc", "tika", "This is an encrypted Word 2007 File." },
Arguments.of( getDocumentInstance(), "password_tika_binaryrc4.doc", "tika", "This is an encrypted Word 2007 File." ),
// cryptoapi
new Object[]{ getDocumentInstance(), "password_password_cryptoapi.doc", "password", "This is a test" },
Arguments.of( getDocumentInstance(), "password_password_cryptoapi.doc", "password", "This is a test" ),
// binary rc4
new Object[]{ getSpreadSheetInstance(), "password.xls", "password", x },
Arguments.of( getSpreadSheetInstance(), "password.xls", "password", x ),
// cryptoapi
new Object[]{ getSpreadSheetInstance(), "35897-type4.xls", "freedom", "Sheet1\nhello there!" },
Arguments.of( getSpreadSheetInstance(), "35897-type4.xls", "freedom", "Sheet1\nhello there!" ),
// cryptoapi (PPT only supports cryptoapi...)
new Object[]{ getSlideShowInstance(), "cryptoapi-proc2356.ppt", "crypto", "Dominic Salemno" }
Arguments.of( getSlideShowInstance(), "cryptoapi-proc2356.ppt", "crypto", "Dominic Salemno" )
);
}
@Test
public void extract() throws IOException {
@ParameterizedTest
@MethodSource("data")
public void extract(POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
File f = sampleDir.getFile(file);
Biff8EncryptionKey.setCurrentUserPassword(password);
try (POITextExtractor te = ExtractorFactory.createExtractor(f)) {
@ -100,17 +84,19 @@ public class TestHxxFEncryption {
}
}
@Test
public void changePassword() throws IOException {
newPassword("test");
@ParameterizedTest
@MethodSource("data")
public void changePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
newPassword("test", sampleDir, file, password, expected);
}
@Test
public void removePassword() throws IOException {
newPassword(null);
@ParameterizedTest
@MethodSource("data")
public void removePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
newPassword(null, sampleDir, file, password, expected);
}
private void newPassword(String newPass) throws IOException {
private void newPassword(String newPass, POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
File f = sampleDir.getFile(file);
Biff8EncryptionKey.setCurrentUserPassword(password);
try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) {
@ -130,8 +116,9 @@ public class TestHxxFEncryption {
}
/** changing the encryption mode and key size in poor mans style - see comments below */
@Test
public void changeEncryption() throws IOException {
@ParameterizedTest
@MethodSource("data")
public void changeEncryption(POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
File f = sampleDir.getFile(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Biff8EncryptionKey.setCurrentUserPassword(password);
@ -156,11 +143,8 @@ public class TestHxxFEncryption {
// need to cache data (i.e. read all data) before changing the key size
Class<?> clazz = doc.getClass();
if ("HSLFSlideShow".equals(clazz.getSimpleName())) {
try {
clazz.getDeclaredMethod("getPictureData").invoke(doc);
} catch (ReflectiveOperationException e) {
fail("either scratchpad jar is included and this should work or the clazz should be != HSLFSlideShowImpl");
}
assertDoesNotThrow(() -> clazz.getDeclaredMethod("getPictureData").invoke(doc),
"either scratchpad jar is included and this should work or the clazz should be != HSLFSlideShowImpl");
doc.getDocumentSummaryInformation();
}
EncryptionInfo ei = doc.getEncryptionInfo();

View File

@ -17,8 +17,9 @@
package org.apache.poi.poifs.crypt.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.io.FileInputStream;
@ -40,8 +41,7 @@ import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor;
import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.XmlException;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestSecureTempZip {
@ -95,8 +95,7 @@ public class TestSecureTempZip {
//The test file requires that JCE unlimited be installed.
//If it isn't installed, skip this test.
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256",
maxKeyLen == 2147483647);
assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");
File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsb");
FileInputStream fis = new FileInputStream(tikaProt);

View File

@ -18,8 +18,8 @@
package org.apache.poi.sl.tests;
import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.Color;
import java.awt.Dimension;
@ -46,8 +46,8 @@ import org.apache.poi.sl.usermodel.TextBox;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
@ -69,7 +69,7 @@ public class TestFonts {
private static final String[] INIT_FONTS = {"mona.ttf"};
@BeforeClass
@BeforeAll
public static void initGE() throws FontFormatException, IOException {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
for (String s : INIT_FONTS) {

View File

@ -20,8 +20,8 @@
package org.apache.poi.sl.tests;
import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
@ -31,7 +31,7 @@ import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.TextShape;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestHeadersFooters {
@Test

View File

@ -23,10 +23,10 @@ import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.EXCEL_V8;
import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.PDF;
import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V12;
import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
@ -37,13 +37,11 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.storage.RawDataUtil;
import org.apache.poi.sl.usermodel.ObjectMetaData;
import org.apache.poi.sl.usermodel.ObjectShape;
@ -58,14 +56,11 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class TestOleShape {
private static final String PDF_SAMPLE =
"H4sIAAAAAAAAAJWUezRUWxzHe+o2FXncVtxLpxi3FPOeKYspjMdM5J1S4TTOaDIzxzpzJo9CUrnrSiUxIeT" +
@ -98,42 +93,35 @@ public class TestOleShape {
enum Api { HSLF, XSLF }
@Parameter(value = 0)
public Api api;
@Parameter(value = 1)
public ObjectMetaData.Application app;
private static File pictureFile;
@BeforeClass
@BeforeAll
public static void initPicture() {
pictureFile = POIDataSamples.getSlideShowInstance().getFile("wrench.emf");
}
@Parameters(name="{0} {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ Api.HSLF, EXCEL_V8 },
{ Api.HSLF, WORD_V8 },
{ Api.HSLF, PDF },
{ Api.XSLF, EXCEL_V12 },
{ Api.XSLF, WORD_V12 },
{ Api.XSLF, PDF },
});
public static Stream<Arguments> data() {
return Stream.of(
Arguments.of( Api.HSLF, EXCEL_V8 ),
Arguments.of( Api.HSLF, WORD_V8 ),
Arguments.of( Api.HSLF, PDF ),
Arguments.of( Api.XSLF, EXCEL_V12 ),
Arguments.of( Api.XSLF, WORD_V12 ),
Arguments.of( Api.XSLF, PDF )
);
}
@Test
public void embedData() throws IOException, InvalidFormatException, ReflectiveOperationException {
@ParameterizedTest
@MethodSource("data")
public void embedData(Api api, ObjectMetaData.Application app) throws IOException, ReflectiveOperationException {
final ByteArrayInputStream pptBytes;
try (SlideShow<?,?> ppt = createSlideShow()) {
try (SlideShow<?,?> ppt = createSlideShow(api)) {
final PictureData picData = ppt.addPicture(pictureFile, PictureType.EMF);
final Slide<?,?> slide = ppt.createSlide();
final ObjectShape<?,?> oleShape = slide.createOleShape(picData);
oleShape.setAnchor(new Rectangle2D.Double(100,100,100,100));
try (OutputStream os = oleShape.updateObjectData(app, null)) {
fillOleData(os);
fillOleData(app, os);
}
final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
ppt.write(bos);
@ -142,12 +130,12 @@ public class TestOleShape {
try (SlideShow<?,?> ppt = SlideShowFactory.create(pptBytes)) {
final ObjectShape<?,?> oleShape = (ObjectShape<?,?>)ppt.getSlides().get(0).getShapes().get(0);
try (InputStream bis = oleShape.readObjectData()) {
validateOleData(bis);
validateOleData(app, bis);
}
}
}
private SlideShow<?,?> createSlideShow() throws IOException {
private SlideShow<?,?> createSlideShow(Api api) throws IOException {
if (api == Api.XSLF) {
return new XMLSlideShow();
} else {
@ -157,7 +145,7 @@ public class TestOleShape {
}
private void fillOleData(final OutputStream out) throws IOException {
private void fillOleData(ObjectMetaData.Application app, final OutputStream out) throws IOException {
switch (app) {
case EXCEL_V8:
case EXCEL_V12:
@ -187,7 +175,7 @@ public class TestOleShape {
}
}
private void validateOleData(final InputStream in) throws IOException, ReflectiveOperationException {
private void validateOleData(ObjectMetaData.Application app, final InputStream in) throws IOException, ReflectiveOperationException {
switch (app) {
case EXCEL_V8:
case EXCEL_V12:

View File

@ -20,9 +20,9 @@
package org.apache.poi.sl.tests;
import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -33,7 +33,7 @@ import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestSlide {

View File

@ -21,12 +21,12 @@ package org.apache.poi.sl.tests;
import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow;
import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
@ -41,7 +41,7 @@ import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TableShape;
import org.apache.poi.sl.usermodel.TextShape.TextDirection;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestTable {
@ -80,17 +80,15 @@ public class TestTable {
int colsx = tableB.getNumberOfColumns();
int rowsx = tableB.getNumberOfRows();
assertEquals("tables should have same number of columns", cols, colsx);
assertEquals("tables should have same number of rows", rows, rowsx);
assertEquals(cols, colsx, "tables should have same number of columns");
assertEquals(rows, rowsx, "tables should have same number of rows");
for (int i=0; i<cols; i++) {
assertEquals("Width of column " + i + " should be equal",
tableA.getColumnWidth(i), tableB.getColumnWidth(i), 0.2);
assertEquals(tableA.getColumnWidth(i), tableB.getColumnWidth(i), 0.2, "Width of column " + i + " should be equal");
}
for (int i=0; i<rows; i++) {
assertEquals("Height of row " + i + " should be equal",
tableA.getRowHeight(i), tableB.getRowHeight(i), 0.3);
assertEquals(tableA.getRowHeight(i), tableB.getRowHeight(i), 0.3, "Height of row " + i + " should be equal");
}
}
@ -164,29 +162,29 @@ public class TestTable {
case 22:
case 51:
if (f.endsWith("ppt")) {
assertNull(msg, tc);
assertNull(tc, msg);
} else {
assertNotNull(msg, tc);
assertTrue(msg, tc.isMerged());
assertNotNull(tc, msg);
assertTrue(tc.isMerged(), msg);
}
break;
case 21:
assertNotNull(msg, tc);
assertEquals(msg, 1, tc.getRowSpan());
assertEquals(msg, 2, tc.getGridSpan());
assertFalse(msg, tc.isMerged());
assertNotNull(tc, msg);
assertEquals(1, tc.getRowSpan(), msg);
assertEquals(2, tc.getGridSpan(), msg);
assertFalse(tc.isMerged(), msg);
break;
case 41:
assertNotNull(msg, tc);
assertEquals(msg, 2, tc.getRowSpan());
assertEquals(msg, 1, tc.getGridSpan());
assertFalse(msg, tc.isMerged());
assertNotNull(tc, msg);
assertEquals(2, tc.getRowSpan(), msg);
assertEquals(1, tc.getGridSpan(), msg);
assertFalse(tc.isMerged(), msg);
break;
default:
assertNotNull(msg, tc);
assertEquals(msg, 1, tc.getRowSpan());
assertEquals(msg, 1, tc.getGridSpan());
assertFalse(msg, tc.isMerged());
assertNotNull(tc, msg);
assertEquals(1, tc.getRowSpan(), msg);
assertEquals(1, tc.getGridSpan(), msg);
assertFalse(tc.isMerged(), msg);
break;
}
}

View File

@ -18,9 +18,9 @@
*/
package org.apache.poi.sl.tests.draw;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.Dimension;
import java.awt.geom.Rectangle2D;
@ -37,15 +37,15 @@ import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.util.Units;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class TestDrawPictureShape {
final static POIDataSamples ssSamples = POIDataSamples.getSlideShowInstance();
private static boolean xslfOnly;
@BeforeClass
@BeforeAll
public static void checkHslf() {
try {
Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow");

View File

@ -17,11 +17,12 @@
package org.apache.poi.ss.tests;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -32,6 +33,7 @@ import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Stream;
import org.apache.poi.EmptyFileException;
import org.apache.poi.EncryptedDocumentException;
@ -43,18 +45,22 @@ import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.SuppressForbidden;
import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public final class TestWorkbookFactory {
private static final String xls = "SampleSS.xls";
private static final String xlsx = "SampleSS.xlsx";
private static final String[] xls_protected = new String[] {"password.xls", "password"};
private static final String[] xls_protected = new String[]{"password.xls", "password"};
private static final String[] xlsx_protected = new String[]{"protected_passtika.xlsx", "tika"};
private static final String txt = "SampleSS.txt";
@ -65,15 +71,14 @@ public final class TestWorkbookFactory {
* Throws an exception if closing the workbook results in the file on disk getting modified.
*
* @param filename the sample workbook to read in
* @param wb the workbook to close
* @param wb the workbook to close
*/
private static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException {
final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename);
// FIXME: replace with wb.close() when bug 58779 is resolved
closeOrRevert(wb);
final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename);
assertArrayEquals(filename + " sample file was modified as a result of closing the workbook",
before, after);
assertArrayEquals(before, after, filename + " sample file was modified as a result of closing the workbook");
}
/**
@ -85,16 +90,14 @@ public final class TestWorkbookFactory {
private static void closeOrRevert(Workbook wb) throws IOException {
if (wb instanceof HSSFWorkbook) {
wb.close();
}
else if (wb instanceof XSSFWorkbook) {
} else if (wb instanceof XSSFWorkbook) {
final XSSFWorkbook xwb = (XSSFWorkbook) wb;
if (PackageAccess.READ == xwb.getPackage().getPackageAccess()) {
xwb.close();
}
else {
} else {
// TODO: close() re-writes the sample-file?! Resort to revert() for now to close file handle...
LOGGER.log(POILogger.WARN,
"reverting XSSFWorkbook rather than closing it to avoid close() modifying the file on disk. Refer to bug 58779.");
"reverting XSSFWorkbook rather than closing it to avoid close() modifying the file on disk. Refer to bug 58779.");
xwb.getPackage().revert();
}
} else {
@ -104,298 +107,174 @@ public final class TestWorkbookFactory {
@Test
public void testCreateNative() throws Exception {
Workbook wb;
// POIFS -> hssf
wb = WorkbookFactory.create(
new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls))
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (Workbook wb = WorkbookFactory.create(
new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls))
)) {
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
}
wb = WorkbookFactory.create(
new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)).getRoot()
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (Workbook wb = WorkbookFactory.create(
new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)).getRoot()
)) {
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
}
// Package -> xssf
wb = XSSFWorkbookFactory.createWorkbook(
OPCPackage.open(
HSSFTestDataSamples.openSampleFileStream(xlsx))
);
assertNotNull(wb);
//noinspection ConstantConditions
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
try (Workbook wb = XSSFWorkbookFactory.createWorkbook(
OPCPackage.open(HSSFTestDataSamples.openSampleFileStream(xlsx))
)) {
assertNotNull(wb);
//noinspection ConstantConditions
assertTrue(wb instanceof XSSFWorkbook);
}
}
@Test
public void testCreateReadOnly() throws Exception {
Workbook wb;
// POIFS -> hssf
wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true)) {
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
}
// Package -> xssf
wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true)) {
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
}
}
/**
* Creates the appropriate kind of Workbook, but
* checking the mime magic at the start of the
* InputStream, then creating what's required.
* checking the mime magic at the start of the
* InputStream, then creating what's required.
*/
@Test
public void testCreateGeneric() throws Exception {
Workbook wb;
// InputStream -> either
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls)
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xls))) {
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
}
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx)
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xlsx))) {
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
}
// File -> either
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xls)
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls))) {
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
}
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx)
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx))) {
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
}
// Invalid type -> exception
final byte[] before = HSSFTestDataSamples.getTestDataFileContent(txt);
try {
try (InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt)) {
wb = WorkbookFactory.create(stream);
assertNotNull(wb);
}
fail();
} catch(IOException e) {
// Good
}
assertThrows(IOException.class, () -> WorkbookFactory.create(new File(txt)));
final byte[] after = HSSFTestDataSamples.getTestDataFileContent(txt);
assertArrayEquals("Invalid type file was modified after trying to open the file as a spreadsheet",
before, after);
assertArrayEquals(before, after, "Invalid type file was modified after trying to open the file as a spreadsheet");
}
public static Stream<Arguments> workbookPass() {
return Stream.of(
// Unprotected, no password given, opens normally
Arguments.of(xls, null, false, HSSFWorkbook.class),
Arguments.of(xlsx, null, false, XSSFWorkbook.class),
// Unprotected, wrong password, opens normally
Arguments.of(xls, "wrong", false, HSSFWorkbook.class),
Arguments.of(xlsx, "wrong", false, XSSFWorkbook.class),
// Protected, correct password, opens fine
Arguments.of(xls_protected[0], xls_protected[1], false, HSSFWorkbook.class),
Arguments.of(xlsx_protected[0], xlsx_protected[1], false, XSSFWorkbook.class),
// Protected, wrong password, throws Exception
Arguments.of(xls_protected[0], "wrong", true, HSSFWorkbook.class),
Arguments.of(xlsx_protected[0], "wrong", true, XSSFWorkbook.class)
);
}
/**
* Check that the overloaded stream methods which take passwords work properly
*/
@Test
public void testCreateWithPasswordFromStream() throws Exception {
Workbook wb;
// Unprotected, no password given, opens normally
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls), null
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx), null
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// Unprotected, wrong password, opens normally
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls), "wrong"
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx), "wrong"
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// Protected, correct password, opens fine
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), xls_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls_protected[0], wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), xlsx_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
// Protected, wrong password, throws Exception
try {
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), "wrong"
);
assertCloseDoesNotModifyFile(xls_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
}
try {
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), "wrong"
);
assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@ParameterizedTest
@MethodSource("workbookPass")
public void testCreateWithPasswordFromStream(String file, String pass, boolean fails, Class<? extends Workbook> clazz) throws Exception {
try (InputStream is = HSSFTestDataSamples.openSampleFileStream(file)) {
if (fails) {
assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(is, pass),
"Shouldn't be able to open with the wrong password");
} else {
try (Workbook wb = WorkbookFactory.create(is, pass)) {
assertNotNull(wb);
assertTrue(clazz.isInstance(wb));
}
}
}
}
/**
* Check that the overloaded file methods which take passwords work properly
*/
@Test
public void testCreateWithPasswordFromFile() throws Exception {
Workbook wb;
// Unprotected, no password given, opens normally
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xls), null
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx), null
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// Unprotected, wrong password, opens normally
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xls), "wrong"
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx), "wrong"
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// Protected, correct password, opens fine
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xls_protected[0]), xls_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls_protected[0], wb);
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), xlsx_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertTrue(wb.getNumberOfSheets() > 0);
assertNotNull(wb.getSheetAt(0));
assertNotNull(wb.getSheetAt(0).getRow(0));
assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
// Protected, wrong password, throws Exception
try {
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xls_protected[0]), "wrong"
);
assertCloseDoesNotModifyFile(xls_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
} finally {
wb.close();
}
try {
wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), "wrong"
);
assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@ParameterizedTest
@MethodSource("workbookPass")
public void testCreateWithPasswordFromFile(String fileName, String pass, boolean fails, Class<? extends Workbook> clazz) throws Exception {
File file = HSSFTestDataSamples.getSampleFile(fileName);
if (fails) {
assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(file, pass),
"Shouldn't be able to open with the wrong password");
} else {
try (Workbook wb = WorkbookFactory.create(file, pass)) {
assertNotNull(wb);
assertTrue(clazz.isInstance(wb));
assertCloseDoesNotModifyFile(fileName, wb);
}
}
}
/**
* Check that a helpful exception is given on an empty input stream
*/
@Test(expected = EmptyFileException.class)
public void testEmptyInputStream() throws Exception {
@Test
public void testEmptyInputStream() {
InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
WorkbookFactory.create(emptyStream);
assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyStream));
}
/**
* Check that a helpful exception is given on an empty file
*/
@Test(expected = EmptyFileException.class)
@Test
public void testEmptyFile() throws Exception {
File emptyFile = TempFile.createTempFile("empty", ".poi");
try {
WorkbookFactory.create(emptyFile);
fail("Shouldn't be able to create for an empty file");
} finally {
assertTrue(emptyFile.delete());
}
assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyFile),
"Shouldn't be able to create for an empty file");
assertTrue(emptyFile.delete());
}
/**
* Check that a helpful exception is raised on a non-existing file
*/
@Test(expected = FileNotFoundException.class)
public void testNonExistingFile() throws Exception {
* Check that a helpful exception is raised on a non-existing file
*/
@Test
public void testNonExistingFile() {
File nonExistingFile = new File("notExistingFile");
assertFalse(nonExistingFile.exists());
WorkbookFactory.create(nonExistingFile, "password", true);
assertThrows(FileNotFoundException.class, () -> WorkbookFactory.create(nonExistingFile, "password", true));
}
/**
* See Bugzilla bug #62831 - #WorkbookFactory.create(File) needs
* to work for sub-classes of File too, eg JFileChooser
* to work for sub-classes of File too, eg JFileChooser
*/
@Test
public void testFileSubclass() throws Exception {
@ -444,30 +323,32 @@ public final class TestWorkbookFactory {
public void testOpenManyHSSF() throws Exception {
final int size = 1000;
ExecutorService executorService = Executors.newFixedThreadPool(10);
ArrayList<Future<Boolean>> futures = new ArrayList(size);
ArrayList<Future<Boolean>> futures = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
futures.add(executorService.submit(() -> openHSSFFile()));
futures.add(executorService.submit(this::openHSSFFile));
}
for (Future<Boolean> future: futures) {
for (Future<Boolean> future : futures) {
assertTrue(future.get());
}
}
@Test(expected = IOException.class)
@Test
public void testInvalidFormatException() throws IOException {
String filename = "OPCCompliance_DerivedPartNameFAIL.docx";
WorkbookFactory.create(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename));
try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)) {
assertThrows(IOException.class, () -> WorkbookFactory.create(is));
}
}
private boolean openHSSFFile() {
try {
// POIFS -> hssf
Workbook wb = WorkbookFactory.create(
new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls))
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
try (InputStream is = HSSFTestDataSamples.openSampleFileStream(xls)) {
Workbook wb = WorkbookFactory.create(new POIFSFileSystem(is));
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
}
return true;
} catch (Exception e) {
return false;

View File

@ -17,8 +17,8 @@
package org.apache.poi.ss.tests.extractor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
@ -38,7 +38,7 @@ import org.apache.poi.ss.extractor.EmbeddedExtractor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestEmbeddedExtractor {
private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();

View File

@ -17,8 +17,8 @@
package org.apache.poi.ss.tests.format;
import static java.awt.Color.ORANGE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.awt.Color;
import java.io.IOException;
@ -39,9 +39,9 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* Class for spreadsheet-based tests, such as are used for cell formatting.
@ -63,13 +63,13 @@ public class TestCellFormatPart {
@BeforeClass
@BeforeAll
public static void setLocale() {
userLocale = LocaleUtil.getUserLocale();
LocaleUtil.setUserLocale(Locale.UK);
}
@AfterClass
@AfterAll
public static void unsetLocale() {
LocaleUtil.setUserLocale(userLocale);
}
@ -80,8 +80,7 @@ public class TestCellFormatPart {
Object getValue(Cell cell);
default void equivalent(String expected, String actual, CellFormatPart format) {
assertEquals("format \"" + format + "\"", '"' + expected + '"',
'"' + actual + '"');
assertEquals('"' + expected + '"', '"' + actual + '"', "format \"" + format + "\"");
}
}
@ -120,8 +119,7 @@ public class TestCellFormatPart {
double actualVal = extractNumber(actual);
// equal within 1%
double delta = expectedVal / 100;
assertEquals("format \"" + format + "\"," + expected + " ~= " +
actual, expectedVal, actualVal, delta);
assertEquals(expectedVal, actualVal, delta, "format \"" + format + "\"," + expected + " ~= " + actual);
}
});
}
@ -204,7 +202,7 @@ public class TestCellFormatPart {
String actualText = label.getText();
Color actualColor = label.getForeground();
valueGetter.equivalent(expectedText, actualText, cellFormatPart);
assertEquals("no color", expectedColor, actualColor);
assertEquals(expectedColor, actualColor, "no color");
}
}
}

View File

@ -18,10 +18,10 @@
*/
package org.apache.poi.ss.tests.formula;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -38,7 +38,7 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test {@link FormulaParser}'s handling of row numbers at the edge of the
@ -51,13 +51,8 @@ public class TestFormulaParser {
@Test
public void testHSSFFailsForOver65536() {
FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(new HSSFWorkbook());
try {
FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0);
fail("Expected exception");
}
catch (FormulaParseException expected) {
// expected here
}
assertThrows(FormulaParseException.class, () ->
FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0));
}
private static void checkHSSFFormula(String formula) {
@ -90,13 +85,8 @@ public class TestFormulaParser {
@Test
public void testXSSFFailCase() {
FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(new XSSFWorkbook());
try {
FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0); // one more than max rows.
fail("Expected exception");
}
catch (FormulaParseException expected) {
// expected here
}
assertThrows(FormulaParseException.class, () ->
FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0), "one more than max rows");
}
// copied from org.apache.poi.hssf.model.TestFormulaParser
@ -175,13 +165,9 @@ public class TestFormulaParser {
/** confirm formula has invalid syntax and parsing the formula results in FormulaParseException
*/
private static void parseExpectedException(String formula, FormulaParsingWorkbook wb) {
try {
FormulaParser.parse(formula, wb, FormulaType.CELL, -1);
fail("Expected FormulaParseException: " + formula);
} catch (final FormulaParseException e) {
// expected during successful test
assertNotNull(e.getMessage());
}
FormulaParseException e = assertThrows(FormulaParseException.class, () ->
FormulaParser.parse(formula, wb, FormulaType.CELL, -1));
assertNotNull(e.getMessage());
}
// trivial case for bug 60219: FormulaParser can't parse external references when sheet name is quoted
@ -191,13 +177,13 @@ public class TestFormulaParser {
XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb);
Ptg[] ptgs = FormulaParser.parse("[1]Sheet1!A1", fpwb, FormulaType.CELL, -1);
// org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1]
assertEquals("Ptgs length", 1, ptgs.length);
assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg);
assertEquals(1, ptgs.length, "Ptgs length");
assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class");
Ref3DPxg pxg = (Ref3DPxg) ptgs[0];
assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber());
assertEquals("Sheet name", "Sheet1", pxg.getSheetName());
assertEquals("Row", 0, pxg.getRow());
assertEquals("Column", 0, pxg.getColumn());
assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number");
assertEquals("Sheet1", pxg.getSheetName(), "Sheet name");
assertEquals(0, pxg.getRow(), "Row");
assertEquals(0, pxg.getColumn(), "Column");
wb.close();
}
@ -208,13 +194,13 @@ public class TestFormulaParser {
XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb);
Ptg[] ptgs = FormulaParser.parse("'[1]Sheet 1'!A1", fpwb, FormulaType.CELL, -1);
// org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1]
assertEquals("Ptgs length", 1, ptgs.length);
assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg);
assertEquals(1, ptgs.length, "Ptgs length");
assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class");
Ref3DPxg pxg = (Ref3DPxg) ptgs[0];
assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber());
assertEquals("Sheet name", "Sheet 1", pxg.getSheetName());
assertEquals("Row", 0, pxg.getRow());
assertEquals("Column", 0, pxg.getColumn());
assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number");
assertEquals("Sheet 1", pxg.getSheetName(), "Sheet name");
assertEquals(0, pxg.getRow(), "Row");
assertEquals(0, pxg.getColumn(), "Column");
wb.close();
}

View File

@ -17,10 +17,9 @@
package org.apache.poi.ss.tests.formula;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
@ -35,7 +34,7 @@ import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Tests Excel Table expressions (structured references)
@ -50,16 +49,16 @@ public class TestStructuredReferences {
*/
@Test
public void testTableExpressionSyntax() {
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("abc[col1]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_abc[col1]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_[col1]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[#This Row]").matches());
assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches());
assertTrue(Table.isStructuredReference.matcher("abc[col1]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("_abc[col1]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("_[col1]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("\\[#This Row]").matches(), "Valid structured reference syntax didn't match expression");
assertTrue(Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches(), "Valid structured reference syntax didn't match expression");
// can't have a space between the table name and open bracket
assertFalse("Invalid structured reference syntax didn't fail expression", Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches());
assertFalse(Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches(), "Invalid structured reference syntax didn't fail expression");
}
@Test
@ -109,18 +108,14 @@ public class TestStructuredReferences {
private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) {
fe.clearAllCachedResultValues();
CellValue cv = fe.evaluate(cell);
if (cv.getCellType() != CellType.NUMERIC) {
fail("expected numeric cell type but got " + cv.formatAsString());
}
assertEquals(CellType.NUMERIC, cv.getCellType(), "expected numeric cell type but got " + cv.formatAsString());
assertEquals(expectedResult, cv.getNumberValue(), 0.0);
}
private static void confirm(FormulaEvaluator fe, Cell cell, String expectedResult) {
fe.clearAllCachedResultValues();
CellValue cv = fe.evaluate(cell);
if (cv.getCellType() != CellType.STRING) {
fail("expected String cell type but got " + cv.formatAsString());
}
assertEquals(CellType.STRING, cv.getCellType(), "expected String cell type but got " + cv.formatAsString());
assertEquals(expectedResult, cv.getStringValue());
}
}

View File

@ -18,8 +18,8 @@
package org.apache.poi.ss.tests.formula.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
@ -32,9 +32,9 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test the COUNTIFS() function
@ -46,7 +46,7 @@ public class CountifsTests {
/**
* initialize a workbook
*/
@Before
@BeforeEach
public void before() {
// not sure why we allow this, COUNTIFS() is only available
// in OOXML, it was introduced with Office 2007
@ -56,7 +56,7 @@ public class CountifsTests {
/**
* Close the workbook if needed
*/
@After
@AfterEach
public void after() {
IOUtils.closeQuietly(workbook);
}
@ -108,14 +108,13 @@ public class CountifsTests {
/**
* the bug returned the wrong count, this verifies the fix
* @throws Exception if the file can't be read
*/
@Test
public void testBug56822() throws Exception {
public void testBug56822() {
workbook = XSSFTestDataSamples.openSampleWorkbook("56822-Countifs.xlsx");
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell cell = SheetUtil.getCell(workbook.getSheetAt(0), 0, 3);
assertNotNull("Test workbook missing cell D1", cell);
assertNotNull(cell, "Test workbook missing cell D1");
CellValue evaluate = evaluator.evaluate(cell);
assertEquals(2.0d, evaluate.getNumberValue(), 0.00000000000001);
}

View File

@ -17,8 +17,8 @@
package org.apache.poi.ss.tests.formula.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -33,7 +33,7 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public final class TestProper {
private Cell cell11;
@ -93,7 +93,7 @@ public final class TestProper {
cell11.setCellFormula(formulaText);
evaluator.clearAllCachedResultValues();
CellValue cv = evaluator.evaluate(cell11);
assertEquals("Wrong result type", CellType.STRING, cv.getCellType());
assertEquals(CellType.STRING, cv.getCellType(), "Wrong result type");
String actualValue = cv.getStringValue();
assertEquals(expectedResult, actualValue);
}
@ -120,7 +120,7 @@ public final class TestProper {
@Test
public void testMicroBenchmark() {
ValueEval strArg = new StringEval("some longer text that needs a number of replacements to check for runtime of different implementations");
long start = System.currentTimeMillis();
// long start = System.currentTimeMillis();
for(int i = 0;i < 300000;i++) {
final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0);
assertEquals("Some Longer Text That Needs A Number Of Replacements To Check For Runtime Of Different Implementations", ((StringEval)ret).getStringValue());

View File

@ -19,7 +19,7 @@
package org.apache.poi.ss.tests.formula.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
@ -28,7 +28,7 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
*

View File

@ -17,8 +17,8 @@
package org.apache.poi.ss.tests.formula.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.IOException;
@ -32,7 +32,7 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test the VLOOKUP function
@ -44,10 +44,10 @@ public class TestVlookup {
try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("VLookupFullColumn.xlsx")) {
FormulaEvaluator feval = wb.getCreationHelper().createFormulaEvaluator();
feval.evaluateAll();
assertEquals("Wrong lookup value", "Value1",
feval.evaluate(wb.getSheetAt(0).getRow(3).getCell(1)).getStringValue());
assertEquals("Lookup should return #N/A",
CellType.ERROR, feval.evaluate(wb.getSheetAt(0).getRow(4).getCell(1)).getCellType());
assertEquals("Value1", feval.evaluate(wb.getSheetAt(0).getRow(3).getCell(1)).getStringValue(),
"Wrong lookup value");
assertEquals(CellType.ERROR, feval.evaluate(wb.getSheetAt(0).getRow(4).getCell(1)).getCellType(),
"Lookup should return #N/A");
}
}

View File

@ -17,7 +17,7 @@
package org.apache.poi.ss.tests.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
@ -30,7 +30,7 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Class for combined testing of XML-specific functionality of

View File

@ -23,7 +23,7 @@ import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestRow;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Class for combined testing of XML-specific functionality of

View File

@ -18,11 +18,10 @@
package org.apache.poi.ss.tests.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.io.IOException;
import java.util.Date;
import java.util.List;
@ -32,13 +31,14 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ConditionalFormattingEvalTest {
@ -49,25 +49,20 @@ public class ConditionalFormattingEvalTest {
private CellReference ref;
private List<EvaluationConditionalFormatRule> rules;
@Before
@BeforeEach
public void openWB() {
wb = XSSFTestDataSamples.openSampleWorkbook("ConditionalFormattingSamples.xlsx");
formulaEval = new XSSFFormulaEvaluator(wb);
cfe = new ConditionalFormattingEvaluator(wb, formulaEval);
}
@After
@AfterEach
public void closeWB() {
formulaEval = null;
cfe = null;
ref = null;
rules = null;
try {
if (wb != null) wb.close();
} catch (IOException e) {
// keep going, this shouldn't cancel things
e.printStackTrace();
}
IOUtils.closeQuietly(wb);
}
@Test
@ -75,25 +70,25 @@ public class ConditionalFormattingEvalTest {
sheet = wb.getSheet("Products1");
getRulesFor(12, 1);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()));
assertFalse("should not be italic " + ref, rules.get(0).getRule().getFontFormatting().isItalic());
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref);
assertFalse(rules.get(0).getRule().getFontFormatting().isItalic(), "should not be italic " + ref);
getRulesFor(16, 3);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001);
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref);
getRulesFor(12, 3);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
sheet = wb.getSheet("Products2");
getRulesFor(15,1);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()));
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref);
getRulesFor(20,3);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
// now change a cell value that's an input for the rules
Cell cell = sheet.getRow(1).getCell(6);
@ -107,103 +102,103 @@ public class ConditionalFormattingEvalTest {
// test that the conditional validation evaluations changed
getRulesFor(15,1);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
getRulesFor(20,3);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001);
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref);
getRulesFor(20,1);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()));
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref);
sheet = wb.getSheet("Book tour");
getRulesFor(8,2);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
sheet = wb.getSheet("Compare to totals");
getRulesFor(3, 2);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong fg color for " + ref, "FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()));
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref);
getRulesFor(3, 3);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
getRulesFor(15, 4);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
getRulesFor(16, 1);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals("wrong fg color for " + ref, "FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()));
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref);
sheet = wb.getSheet("Products3");
sheet.getRow(8).getCell(0).setCellValue(new Date());
getRulesFor(8, 0);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
getRulesFor(8, 3);
assertEquals("wrong # of rules for " + ref, 1, rules.size());
assertEquals(1, rules.size(), "wrong # of rules for " + ref);
sheet = wb.getSheet("Customers2");
getRulesFor(3, 0);
assertEquals("wrong # of rules for " + ref, 0, rules.size());
assertEquals(0, rules.size(), "wrong # of rules for " + ref);
}
@Test
public void testFormattingOnUndefinedCell() throws Exception {
public void testFormattingOnUndefinedCell() {
wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_with_formula_on_second_sheet.xlsx");
formulaEval = new XSSFFormulaEvaluator(wb);
cfe = new ConditionalFormattingEvaluator(wb, formulaEval);
sheet = wb.getSheet("Sales Plan");
getRulesFor(9,2);
assertNotEquals("No rules for " + ref, 0, rules.size());
assertEquals("wrong bg color for " + ref, "FFFFFF00", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()));
assertNotEquals(0, rules.size(), "No rules for " + ref);
assertEquals("FFFFFF00", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref);
}
@Test
public void testRepeatedEval() throws Exception {
public void testRepeatedEval() {
wb = XSSFTestDataSamples.openSampleWorkbook("test_conditional_formatting.xlsx");
formulaEval = new XSSFFormulaEvaluator(wb);
cfe = new ConditionalFormattingEvaluator(wb, formulaEval);
sheet = wb.getSheetAt(0);
assertEquals("no rules should apply", 0, getRulesFor(2, 1).size());
assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply");
assertEquals("no rules should apply", 0, getRulesFor(2, 1).size());
assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply");
}
@Test
public void testCellValueIsWrongType() throws Exception {
public void testCellValueIsWrongType() {
wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_cell_is.xlsx");
formulaEval = new XSSFFormulaEvaluator(wb);
cfe = new ConditionalFormattingEvaluator(wb, formulaEval);
sheet = wb.getSheetAt(1);
assertEquals("wrong # of matching rules", 1, getRulesFor(3, 1).size());
assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules");
}
@Test
public void testRangeCondition() throws Exception {
public void testRangeCondition() {
wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_multiple_ranges.xlsx");
formulaEval = new XSSFFormulaEvaluator(wb);
cfe = new ConditionalFormattingEvaluator(wb, formulaEval);
sheet = wb.getSheetAt(0);
assertEquals("wrong # of matching rules", 0, getRulesFor(0, 0).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(1, 0).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(2, 0).size());
assertEquals("wrong # of matching rules", 1, getRulesFor(3, 0).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(0, 1).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(1, 1).size());
assertEquals("wrong # of matching rules", 1, getRulesFor(2, 1).size());
assertEquals("wrong # of matching rules", 1, getRulesFor(3, 1).size());
assertEquals("wrong # of matching rules", 1, getRulesFor(0, 3).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(1, 3).size());
assertEquals("wrong # of matching rules", 1, getRulesFor(2, 3).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(0, 6).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(3, 6).size());
assertEquals("wrong # of matching rules", 0, getRulesFor(2, 6).size());
assertEquals(0, getRulesFor(0, 0).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(1, 0).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(2, 0).size(), "wrong # of matching rules");
assertEquals(1, getRulesFor(3, 0).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(0, 1).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(1, 1).size(), "wrong # of matching rules");
assertEquals(1, getRulesFor(2, 1).size(), "wrong # of matching rules");
assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules");
assertEquals(1, getRulesFor(0, 3).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(1, 3).size(), "wrong # of matching rules");
assertEquals(1, getRulesFor(2, 3).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(0, 6).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(3, 6).size(), "wrong # of matching rules");
assertEquals(0, getRulesFor(2, 6).size(), "wrong # of matching rules");
}
private List<EvaluationConditionalFormatRule> getRulesFor(int row, int col) {

Some files were not shown because too many files have changed in this diff Show More