Migrate all junit tests to Junit 4

get rid of references to junit.framework
don't throw AssertionFailedErrors, but use Assert.fail instead
add try-with-resources where it was missing

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1872041 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2019-12-27 23:00:13 +00:00
parent 37282aae8f
commit c66575c1e7
331 changed files with 10391 additions and 14934 deletions

View File

@ -16,36 +16,42 @@
==================================================================== */
package org.apache.poi.ss.examples.formula;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
public class TestExcelAntUserDefinedFunction {
public class TestExcelAntUserDefinedFunction extends TestCase {
private ExcelAntUserDefinedFunctionTestHelper fixture ;
@Override
@Before
public void setUp() {
fixture = new ExcelAntUserDefinedFunctionTestHelper() ;
}
@Test
public void testSetClassName() {
String className = "simple.class.name" ;
fixture.setClassName( className ) ;
String value = fixture.getClassName() ;
assertNotNull( value ) ;
assertEquals( className, value ) ;
}
@Test
public void testSetFunction() {
String functionAlias = "alias" ;
fixture.setFunctionAlias( functionAlias ) ;
String alias = fixture.getFunctionAlias() ;
assertNotNull( alias ) ;
assertEquals( functionAlias, alias ) ;
}
}

View File

@ -1,593 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.poi.ss.excelant;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertNotContained;
import java.io.File;
import java.io.PrintStream;
import java.net.URL;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
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;
/**
* A BuildFileTest is a TestCase which executes targets from an Ant buildfile
* for testing.
* <p>
* This class provides a number of utility methods for particular build file
* tests which extend this class.
*
* @see <a href="http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java">
* http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java</a>
*/
public abstract class BuildFileTest extends TestCase {
protected Project project;
private StringBuilder logBuffer;
private StringBuilder fullLogBuffer;
private StringBuilder outBuffer;
private StringBuilder errBuffer;
private BuildException buildException;
/**
* Default constructor for the BuildFileTest object.
*/
public BuildFileTest() {
super();
}
/**
* Constructor for the BuildFileTest object.
*
* @param name string to pass up to TestCase constructor
*/
public BuildFileTest(String name) {
super(name);
}
/**
* Automatically calls the target called "tearDown"
* from the build file tested if it exits.
* <p>
* This allows to use Ant tasks directly in the build file
* to clean up after each test. Note that no "setUp" target
* is automatically called, since it's trivial to have a
* test target depend on it.
*/
@Override
protected void tearDown() throws Exception {
if (project == null) {
/*
* Maybe the BuildFileTest was subclassed and there is
* no initialized project. So we could avoid getting a
* NPE.
* If there is an initialized project getTargets() does
* not return null as it is initialized by an empty
* HashSet.
*/
return;
}
final String tearDown = "tearDown";
if (project.getTargets().containsKey(tearDown)) {
project.executeTarget(tearDown);
}
}
/**
* run a target, expect for any build exception
*
* @param target target to run
* @param cause information string to reader of report
*/
public void expectBuildException(String target, String cause) {
expectSpecificBuildException(target, cause, null);
}
/**
* Assert that only the given message has been logged with a
* priority &lt;= INFO when running the given target.
*/
public void expectLog(String target, String log) {
executeTarget(target);
String realLog = getLog();
assertEquals(log, realLog);
}
/**
* Assert that the given substring is in the log messages.
*/
public void assertLogContaining(String substring) {
assertContains(getLog(), substring);
}
/**
* Assert that the given substring is not in the log messages.
*/
public void assertLogNotContaining(String substring) {
assertNotContained(getLog(), substring);
}
/**
* Assert that the given substring is in the output messages.
*
* @since Ant1.7
*/
public void assertOutputContaining(String substring) {
assertOutputContaining(null, substring);
}
/**
* Assert that the given substring is in the output messages.
*
* @param message Print this message if the test fails. Defaults to
* a meaningful text if <tt>null</tt> is passed.
* @since Ant1.7
*/
public void assertOutputContaining(String message, String substring) {
assertContains("output: " + message, getOutput(), substring);
}
/**
* Assert that the given substring is not in the output messages.
*
* @param message Print this message if the test fails. Defaults to
* a meaningful text if <tt>null</tt> is passed.
* @since Ant1.7
*/
public void assertOutputNotContaining(String message, String substring) {
assertNotContained(getOutput(), substring);
}
/**
* Assert that the given message has been logged with a priority &lt;= INFO when running the
* given target.
*/
public void expectLogContaining(String target, String log) {
executeTarget(target);
assertLogContaining(log);
}
/**
* Assert that the given message has not been logged with a
* priority &lt;= INFO when running the given target.
*/
public void expectLogNotContaining(String target, String log) {
executeTarget(target);
assertLogNotContaining(log);
}
/**
* Gets the log the BuildFileTest object.
* Only valid if configureProject() has been called.
*
* @return The log value
* @pre logBuffer!=null
*/
public String getLog() {
return logBuffer.toString();
}
/**
* Assert that the given message has been logged with a priority
* &gt;= VERBOSE when running the given target.
*/
public void expectDebuglog(String target, String log) {
executeTarget(target);
String realLog = getFullLog();
assertEquals(log, realLog);
}
/**
* Assert that the given substring is in the log messages.
*/
public void assertDebuglogContaining(String substring) {
String realLog = getFullLog();
assertContains("expecting debug log to contain \"" + substring
+ "\" log was \""
+ realLog + "\"",
realLog, substring);
}
/**
* Gets the log the BuildFileTest object.
* <p>
* Only valid if configureProject() has been called.
*
* @return The log value
* @pre fullLogBuffer!=null
*/
public String getFullLog() {
return fullLogBuffer.toString();
}
/**
* execute the target, verify output matches expectations
*
* @param target target to execute
* @param output output to look for
*/
public void expectOutput(String target, String output) {
executeTarget(target);
String realOutput = getOutput();
assertEquals(output, realOutput.trim());
}
/**
* Executes the target, verify output matches expectations
* and that we got the named error at the end
*
* @param target target to execute
* @param output output to look for
* @param error Description of Parameter
*/
public void expectOutputAndError(String target, String output, String error) {
executeTarget(target);
String realOutput = getOutput();
assertEquals(output, realOutput);
String realError = getError();
assertEquals(error, realError);
}
public String getOutput() {
return cleanBuffer(outBuffer);
}
public String getError() {
return cleanBuffer(errBuffer);
}
public BuildException getBuildException() {
return buildException;
}
private String cleanBuffer(StringBuilder buffer) {
StringBuilder cleanedBuffer = new StringBuilder();
for (int i = 0; i < buffer.length(); i++) {
char ch = buffer.charAt(i);
if (ch != '\r') {
cleanedBuffer.append(ch);
}
}
return cleanedBuffer.toString();
}
/**
* Sets up to run the named project
*
* @param filename name of project file to run
*/
public void configureProject(String filename) throws BuildException {
configureProject(filename, Project.MSG_DEBUG);
}
/**
* Sets up to run the named project
*
* @param filename name of project file to run
*/
public void configureProject(String filename, int logLevel)
throws BuildException {
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
project = new Project();
project.init();
project.setNewProperty("data.dir.name", getDataDir());
File antFile = new File(System.getProperty("root"), filename);
project.setUserProperty("ant.file", antFile.getAbsolutePath());
project.addBuildListener(new AntTestListener(logLevel));
ProjectHelper.configureProject(project, antFile);
}
/**
* Executes a target we have set up
*
* @param targetName target to run
* @pre configureProject has been called
*/
public void executeTarget(String targetName) {
PrintStream sysOut = System.out;
PrintStream sysErr = System.err;
try {
sysOut.flush();
sysErr.flush();
outBuffer = new StringBuilder();
PrintStream out = new PrintStream(new AntOutputStream(outBuffer));
System.setOut(out);
errBuffer = new StringBuilder();
PrintStream err = new PrintStream(new AntOutputStream(errBuffer));
System.setErr(err);
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
buildException = null;
project.executeTarget(targetName);
} finally {
System.setOut(sysOut);
System.setErr(sysErr);
}
}
/**
* Get the project which has been configured for a test.
*
* @return the Project instance for this test.
*/
public Project getProject() {
return project;
}
/**
* Gets the directory of the project.
*
* @return the base dir of the project
*/
public File getProjectDir() {
return project.getBaseDir();
}
/**
* Runs a target, wait for a build exception.
*
* @param target target to run
* @param cause information string to reader of report
* @param msg the message value of the build exception we are waiting
* for set to null for any build exception to be valid
*/
public void expectSpecificBuildException(String target, String cause, String msg) {
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)");
}
return;
}
fail("Should throw BuildException because: " + cause);
}
/**
* run a target, expect an exception string
* containing the substring we look for (case sensitive match)
*
* @param target target to run
* @param cause information string to reader of report
* @param contains substring of the build exception to look for
*/
public void expectBuildExceptionContaining(String target, String cause, String contains) {
try {
executeTarget(target);
} catch (org.apache.tools.ant.BuildException ex) {
buildException = ex;
if ((null != contains) && (!ex.getMessage().contains(contains))) {
fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)");
}
return;
}
fail("Should throw BuildException because: " + cause);
}
/**
* call a target, verify property is as expected
*
* @param target build file target
* @param property property name
* @param value expected value
*/
public void expectPropertySet(String target, String property, String value) {
executeTarget(target);
assertPropertyEquals(property, value);
}
/**
* assert that a property equals a value; comparison is case sensitive.
*
* @param property property name
* @param value expected value
*/
public void assertPropertyEquals(String property, String value) {
String result = project.getProperty(property);
assertEquals("property " + property, value, result);
}
/**
* assert that a property equals "true".
*
* @param property property name
*/
public void assertPropertySet(String property) {
assertPropertyEquals(property, "true");
}
/**
* assert that a property is null.
*
* @param property property name
*/
public void assertPropertyUnset(String property) {
String result = project.getProperty(property);
if (result != null) {
fail("Expected property " + property
+ " to be unset, but it is set to the value: " + result);
}
}
/**
* call a target, verify named property is "true".
*
* @param target build file target
* @param property property name
*/
public void expectPropertySet(String target, String property) {
expectPropertySet(target, property, "true");
}
/**
* Call a target, verify property is null.
*
* @param target build file target
* @param property property name
*/
public void expectPropertyUnset(String target, String property) {
expectPropertySet(target, property, null);
}
/**
* Retrieve a resource from the caller classloader to avoid
* assuming a vm working directory. The resource path must be
* relative to the package name or absolute from the root path.
*
* @param resource the resource to retrieve its url.
* @throws junit.framework.AssertionFailedError
* if the resource is not found.
*/
public URL getResource(String resource) {
URL url = getClass().getResource(resource);
assertNotNull("Could not find resource :" + resource, url);
return url;
}
public static String getDataDir() {
String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY);
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;
/**
* Constructs a test listener which will ignore log events
* above the given level.
*/
public AntTestListener(int logLevel) {
this.logLevel = logLevel;
}
/**
* Fired before any targets are started.
*/
@Override
public void buildStarted(BuildEvent event) {
}
/**
* Fired after the last target has finished. This event
* will still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void buildFinished(BuildEvent event) {
}
/**
* Fired when a target is started.
*
* @see BuildEvent#getTarget()
*/
@Override
public void targetStarted(BuildEvent event) {
//System.out.println("targetStarted " + event.getTarget().getName());
}
/**
* Fired when a target has finished. This event will
* still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void targetFinished(BuildEvent event) {
//System.out.println("targetFinished " + event.getTarget().getName());
}
/**
* Fired when a task is started.
*
* @see BuildEvent#getTask()
*/
@Override
public void taskStarted(BuildEvent event) {
//System.out.println("taskStarted " + event.getTask().getTaskName());
}
/**
* Fired when a task has finished. This event will still
* be throw if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void taskFinished(BuildEvent event) {
//System.out.println("taskFinished " + event.getTask().getTaskName());
}
/**
* Fired whenever a message is logged.
*
* @see BuildEvent#getMessage()
* @see BuildEvent#getPriority()
*/
@Override
public void messageLogged(BuildEvent event) {
if (event.getPriority() > logLevel) {
// ignore event
return;
}
if (event.getPriority() == Project.MSG_INFO ||
event.getPriority() == Project.MSG_WARN ||
event.getPriority() == Project.MSG_ERR) {
logBuffer.append(event.getMessage());
}
fullLogBuffer.append(event.getMessage());
}
}
}

View File

@ -15,105 +15,384 @@
* limitations under the License.
*
*/
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 java.io.File;
import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
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;
/**
* JUnit test for the ExcelAnt tasks.
* Leverages Ant's test framework.
*
* @see <a href="http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java">
* http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java</a>
*/
public class TestBuildFile extends BuildFileTest {
public class TestBuildFile {
@Override
protected Project project;
private StringBuilder logBuffer;
private StringBuilder fullLogBuffer;
private BuildException buildException;
@Before
public void setUp() {
configureProject(BuildFileTest.getDataDir() + "/../src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml");
String filename = TestBuildFile.getDataDir() + "/../src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml";
int logLevel = Project.MSG_DEBUG;
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
project = new Project();
project.init();
project.setNewProperty("data.dir.name", getDataDir());
File antFile = new File(System.getProperty("root"), filename);
project.setUserProperty("ant.file", antFile.getAbsolutePath());
project.addBuildListener(new AntTestListener(logLevel));
ProjectHelper.configureProject(project, antFile);
}
/**
* Automatically calls the target called "tearDown"
* from the build file tested if it exits.
* <p>
* This allows to use Ant tasks directly in the build file
* to clean up after each test. Note that no "setUp" target
* is automatically called, since it's trivial to have a
* test target depend on it.
*/
@After
public void tearDown() {
if (project == null) {
/*
* Maybe the BuildFileTest was subclassed and there is
* no initialized project. So we could avoid getting a
* NPE.
* If there is an initialized project getTargets() does
* not return null as it is initialized by an empty
* HashSet.
*/
return;
}
final String tearDown = "tearDown";
if (project.getTargets().containsKey(tearDown)) {
project.executeTarget(tearDown);
}
}
/**
* run a target, expect for any build exception
*
* @param target target to run
* @param cause information string to reader of report
*/
public void expectBuildException(String target, String cause) {
expectSpecificBuildException(target, cause, null);
}
/**
* Assert that the given substring is in the log messages.
*/
public void assertLogContaining(String substring) {
assertContains(getLog(), substring);
}
/**
* Assert that the given substring is not in the log messages.
*/
public void assertLogNotContaining(String substring) {
assertNotContained(getLog(), substring);
}
/**
* Gets the log the BuildFileTest object.
* Only valid if configureProject() has been called.
*
* @return The log value
*/
public String getLog() {
return logBuffer.toString();
}
/**
* Executes a target we have set up
*
* @param targetName target to run
*/
public void executeTarget(String targetName) {
PrintStream sysOut = System.out;
PrintStream sysErr = System.err;
try {
sysOut.flush();
sysErr.flush();
StringBuilder outBuffer = new StringBuilder();
PrintStream out = new PrintStream(new AntOutputStream(outBuffer));
System.setOut(out);
StringBuilder errBuffer = new StringBuilder();
PrintStream err = new PrintStream(new AntOutputStream(errBuffer));
System.setErr(err);
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
buildException = null;
project.executeTarget(targetName);
} finally {
System.setOut(sysOut);
System.setErr(sysErr);
}
}
/**
* Runs a target, wait for a build exception.
*
* @param target target to run
* @param cause information string to reader of report
* @param msg the message value of the build exception we are waiting
* for set to null for any build exception to be valid
*/
public void expectSpecificBuildException(String target, String cause, String msg) {
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)");
}
return;
}
fail("Should throw BuildException because: " + cause);
}
public static String getDataDir() {
String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY);
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;
/**
* Constructs a test listener which will ignore log events
* above the given level.
*/
public AntTestListener(int logLevel) {
this.logLevel = logLevel;
}
/**
* Fired before any targets are started.
*/
@Override
public void buildStarted(BuildEvent event) {
}
/**
* Fired after the last target has finished. This event
* will still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void buildFinished(BuildEvent event) {
}
/**
* Fired when a target is started.
*
* @see BuildEvent#getTarget()
*/
@Override
public void targetStarted(BuildEvent event) {
//System.out.println("targetStarted " + event.getTarget().getName());
}
/**
* Fired when a target has finished. This event will
* still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void targetFinished(BuildEvent event) {
//System.out.println("targetFinished " + event.getTarget().getName());
}
/**
* Fired when a task is started.
*
* @see BuildEvent#getTask()
*/
@Override
public void taskStarted(BuildEvent event) {
//System.out.println("taskStarted " + event.getTask().getTaskName());
}
/**
* Fired when a task has finished. This event will still
* be throw if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
@Override
public void taskFinished(BuildEvent event) {
//System.out.println("taskFinished " + event.getTask().getTaskName());
}
/**
* Fired whenever a message is logged.
*
* @see BuildEvent#getMessage()
* @see BuildEvent#getPriority()
*/
@Override
public void messageLogged(BuildEvent event) {
if (event.getPriority() > logLevel) {
// ignore event
return;
}
if (event.getPriority() == Project.MSG_INFO ||
event.getPriority() == Project.MSG_WARN ||
event.getPriority() == Project.MSG_ERR) {
logBuffer.append(event.getMessage());
}
fullLogBuffer.append(event.getMessage());
}
}
@Test
public void testMissingFilename() {
expectSpecificBuildException("test-nofile", "required argument not specified",
"fileName attribute must be set!");
}
"fileName attribute must be set!");
}
@Test
public void testFileNotFound() {
expectSpecificBuildException("test-filenotfound", "required argument not specified",
"Cannot load file invalid.xls. Make sure the path and file permissions are correct.");
}
"Cannot load file invalid.xls. Make sure the path and file permissions are correct.");
}
@Test
public void testEvaluate() {
executeTarget("test-evaluate");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4.");
}
@Test
public void testEvaluateNoDetails() {
executeTarget("test-evaluate-nodetails");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogNotContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4.");
}
@Test
public void testPrecision() {
executeTarget("test-precision");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4. " +
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-4");
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-4");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4. " +
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-5");
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-5");
assertLogContaining("Failed to evaluate cell 'MortgageCalculator'!$B$4. " +
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected.");
"It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected.");
assertLogContaining("2/3 tests passed");
}
@Test
public void testPrecisionFail() {
expectSpecificBuildException("test-precision-fails", "precision not matched",
"\tFailed to evaluate cell 'MortgageCalculator'!$B$4. It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected.");
"\tFailed to evaluate cell 'MortgageCalculator'!$B$4. It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected.");
}
@Test
public void testPassOnError() {
executeTarget("test-passonerror");
}
@Test
public void testFailOnError() {
expectBuildException("test-failonerror", "fail on error");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogNotContaining("failed because 1 of 0 evaluations failed to evaluate correctly. Failed to evaluate cell 'MortageCalculatorFunction'!$D$3");
}
@Test
public void testFailOnErrorNoDetails() {
expectBuildException("test-failonerror-nodetails", "fail on error");
assertLogNotContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogNotContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogNotContaining("failed because 1 of 0 evaluations failed to evaluate correctly. Failed to evaluate cell 'MortageCalculatorFunction'!$D$3");
}
@Test
public void testUdf() {
executeTarget("test-udf");
assertLogContaining("1/1 tests passed");
}
@Test
public void testSetText() {
executeTarget("test-settext");
assertLogContaining("1/1 tests passed");
}
@Test
public void testAddHandler() {
executeTarget("test-addhandler");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
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);
}
@Test
public void testAddHandlerWrongClass() {
executeTarget("test-addhandler-wrongclass");
assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4.");
}
@Test
public void testAddHandlerFails() {
expectSpecificBuildException("test-addhandler-fails", "NullPointException", null);
}
}

View File

@ -16,32 +16,38 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestExcelAntPrecision {
public class TestExcelAntPrecision extends TestCase {
private ExcelAntPrecision fixture ;
@Override
@Before
public void setUp() {
fixture = new ExcelAntPrecision() ;
}
@Override
@After
public void tearDown() {
fixture = null ;
}
@Test
public void testVerifyPrecision() {
double value = 1.0E-1 ;
fixture.setValue( value ) ;
double result = fixture.getValue() ;
assertTrue( result > 0 ) ;
assertEquals( value, result, 0.0 ) ;
}

View File

@ -16,48 +16,54 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.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;
public class TestExcelAntSet extends TestCase {
public class TestExcelAntSet {
// This is abstract in nature, so we'll use a
// This is abstract in nature, so we'll use a
// concrete instance to test the set methods.
private ExcelAntSet fixture ;
private static final String mortgageCalculatorFileName =
BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@Override
TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@Before
public void setUp() {
fixture = new ExcelAntSetDoubleCell() ;
}
@Override
@After
public void tearDown() {
fixture = null ;
}
@Test
public void testSetter() {
String cell = "simpleCellRef!$F$1" ;
fixture.setCell( cell ) ;
String cellStr = fixture.getCell() ;
assertNotNull( cellStr ) ;
assertEquals( cell, cellStr ) ;
}
@Test
public void testSetWorkbookUtil() {
ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorFileName ) ;
assertNotNull( util ) ;
fixture.setWorkbookUtil( util ) ;
}
}

View File

@ -16,51 +16,55 @@
==================================================================== */
package org.apache.poi.ss.excelant;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.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;
public class TestExcelAntSetDoubleCell {
public class TestExcelAntSetDoubleCell extends TestCase {
private ExcelAntSetDoubleCell fixture ;
private ExcelAntWorkbookUtil util ;
private static final String mortgageCalculatorFileName =
BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@Override
@Before
public void setUp() {
fixture = new ExcelAntSetDoubleCell() ;
util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorFileName ) ;
util = ExcelAntWorkbookUtilFactory.getInstance(mortgageCalculatorFileName ) ;
fixture.setWorkbookUtil( util ) ;
}
@Override
@After
public void tearDown() {
fixture = null ;
}
@Test
public void testSetDouble() {
String cellId = "'Sheet3'!$A$1" ;
double testValue = 1.1 ;
fixture.setCell( cellId ) ;
fixture.setValue( testValue ) ;
double value = fixture.getCellValue() ;
assertTrue( value > 0 ) ;
assertEquals( testValue, value, 0.0 ) ;
fixture.execute() ;
double setValue = util.getCellAsDouble( cellId ) ;
assertEquals( setValue, testValue, 0.0 ) ;
}
}

View File

@ -16,6 +16,13 @@
==================================================================== */
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 java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -23,166 +30,178 @@ import java.util.Date;
import java.util.List;
import org.apache.poi.ss.examples.formula.CalculateMortgageFunction;
import org.apache.poi.ss.excelant.BuildFileTest;
import org.apache.poi.ss.excelant.TestBuildFile;
import org.apache.poi.ss.formula.udf.UDFFinder;
import org.apache.poi.ss.usermodel.DateUtil;
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 junit.framework.TestCase;
public class TestExcelAntWorkbookUtil {
public class TestExcelAntWorkbookUtil extends TestCase {
private static final String mortgageCalculatorFileName =
BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls" ;
TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls" ;
private ExcelAntWorkbookUtilTestHelper fixture ;
@Override
@After
public void tearDown() {
fixture = null ;
}
@Test
public void testStringConstructor() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture = new ExcelAntWorkbookUtilTestHelper(mortgageCalculatorFileName);
assertNotNull(fixture);
}
@Test
public void testLoadNotExistingFile() {
try {
new ExcelAntWorkbookUtilTestHelper("notexistingFile");
fail("Should catch exception here");
} catch (BuildException e) {
assertTrue(e.getMessage().contains("notexistingFile"));
assertTrue(e.getMessage().contains("notexistingFile"));
}
}
@Test
public void testWorkbookConstructor() throws IOException {
File workbookFile = new File(mortgageCalculatorFileName);
FileInputStream fis = new FileInputStream(workbookFile);
Workbook workbook = WorkbookFactory.create(fis);
fixture = new ExcelAntWorkbookUtilTestHelper(workbook);
assertNotNull(fixture);
}
@Test
public void testAddFunction() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
assertNotNull(fixture);
fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction());
UDFFinder functions = fixture.getFunctions();
assertNotNull(functions);
assertNotNull(functions.findFunction("h2_ZFactor"));
}
@Test
public void testAddFunctionClassName() throws Exception {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
assertNotNull(fixture);
fixture.addFunction("h2_ZFactor", CalculateMortgageFunction.class.getName());
UDFFinder functions = fixture.getFunctions();
assertNotNull(functions);
assertNotNull(functions.findFunction("h2_ZFactor"));
}
@Test
public void testAddFunctionInvalidClassName() throws Exception {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
assertNotNull(fixture);
fixture.addFunction("h2_ZFactor", String.class.getName());
UDFFinder functions = fixture.getFunctions();
assertNotNull(functions);
assertNull(functions.findFunction("h2_ZFactor"));
}
@Test
public void testGetWorkbook() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
assertNotNull(fixture);
Workbook workbook = fixture.getWorkbook();
assertNotNull(workbook);
}
@Test
public void testFileName() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
assertNotNull(fixture);
String fileName = fixture.getFileName();
assertNotNull(fileName);
assertEquals(mortgageCalculatorFileName, fileName);
}
@Test
public void testGetEvaluator() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
FormulaEvaluator evaluator = fixture.getEvaluator(
mortgageCalculatorFileName);
assertNotNull(evaluator);
}
@Test
public void testGetEvaluatorWithUDF() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction());
FormulaEvaluator evaluator = fixture.getEvaluator(
mortgageCalculatorFileName);
assertNotNull(evaluator);
}
@Test
public void testGetEvaluatorXLSX() {
fixture = new ExcelAntWorkbookUtilTestHelper(
BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx");
TestBuildFile.getDataDir() + "/spreadsheet/sample.xlsx");
FormulaEvaluator evaluator = fixture.getEvaluator(
BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx");
TestBuildFile.getDataDir() + "/spreadsheet/sample.xlsx");
assertNotNull(evaluator);
}
@Test
public void testGetEvaluatorXLSXWithFunction() {
fixture = new ExcelAntWorkbookUtilTestHelper(
BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx");
TestBuildFile.getDataDir() + "/spreadsheet/sample.xlsx");
fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction());
FormulaEvaluator evaluator = fixture.getEvaluator(
BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx");
TestBuildFile.getDataDir() + "/spreadsheet/sample.xlsx");
assertNotNull(evaluator);
}
@Test
public void testEvaluateCell() {
String cell = "'MortgageCalculator'!B4" ;
double expectedValue = 790.79 ;
@ -191,8 +210,8 @@ public class TestExcelAntWorkbookUtil extends TestCase {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
precision);
//System.out.println(result);
@ -204,7 +223,8 @@ public class TestExcelAntWorkbookUtil extends TestCase {
assertFalse(result.evaluationCompleteWithError());
assertTrue(result.didTestPass());
}
@Test
public void testEvaluateCellFailedPrecision() {
String cell = "'MortgageCalculator'!B4" ;
double expectedValue = 790.79 ;
@ -213,8 +233,8 @@ public class TestExcelAntWorkbookUtil extends TestCase {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
precision);
//System.out.println(result);
@ -226,7 +246,8 @@ public class TestExcelAntWorkbookUtil extends TestCase {
assertFalse(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
}
@Test
public void testEvaluateCellWithError() {
String cell = "'ErrorCell'!A1" ;
double expectedValue = 790.79 ;
@ -235,8 +256,8 @@ public class TestExcelAntWorkbookUtil extends TestCase {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
ExcelAntEvaluationResult result = fixture.evaluateCell(cell,
expectedValue,
precision);
System.out.println(result);
@ -248,35 +269,38 @@ public class TestExcelAntWorkbookUtil extends TestCase {
assertTrue(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
}
@Test
public void testGetSheets() {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
List<String> sheets = fixture.getSheets();
assertNotNull(sheets);
assertEquals(sheets.size(), 3);
assertEquals(sheets.size(), 3);
}
@Test
public void testSetString() {
String cell = "'MortgageCalculator'!C14" ;
String cellValue = "testString" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture.setStringValue(cell, cellValue);
String value = fixture.getCellAsString(cell);
assertNotNull(value);
assertEquals(cellValue, value);
}
@Test
public void testSetNotExistingSheet() {
String cell = "'NotexistingSheet'!C14" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
try {
@ -287,68 +311,72 @@ public class TestExcelAntWorkbookUtil extends TestCase {
}
}
@Test
public void testSetFormula() {
String cell = "'MortgageCalculator'!C14" ;
String cellValue = "SUM(B14:B18)" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture.setFormulaValue(cell, cellValue);
double value = fixture.getCellAsDouble(cell);
assertEquals(0.0, value);
assertEquals(0.0, value, 0);
}
@Test
public void testSetDoubleValue() {
String cell = "'MortgageCalculator'!C14" ;
double cellValue = 1.2;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture.setDoubleValue(cell, cellValue);
Double value = fixture.getCellAsDouble(cell);
assertNotNull(value);
assertEquals(cellValue, value);
double value = fixture.getCellAsDouble(cell);
assertEquals(cellValue, value, 0);
}
@Test
public void testSetDate() {
String cell = "'MortgageCalculator'!C14" ;
Date cellValue = new Date();
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
fixture.setDateValue(cell, cellValue);
double value = fixture.getCellAsDouble(cell);
assertEquals(DateUtil.getExcelDate(cellValue, false), value);
assertEquals(DateUtil.getExcelDate(cellValue, false), value, 0);
}
@Test
public void testGetNonexistingString() {
String cell = "'MortgageCalculator'!C33" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
String value = fixture.getCellAsString(cell);
assertEquals("", value);
}
@Test
public void testGetNonexistingDouble() {
String cell = "'MortgageCalculator'!C33" ;
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
double value = fixture.getCellAsDouble(cell);
assertEquals(0.0, value);
assertEquals(0.0, value, 0);
}
}

View File

@ -19,23 +19,19 @@ package org.apache.poi.ss.excelant.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.poi.ss.excelant.BuildFileTest;
import org.apache.poi.ss.excelant.TestBuildFile;
import org.junit.Test;
/**
* Tests for the ExcelAntWorbookUtilFactory.
*
* @author Jon Svede (jon [at] loquatic [dot] com)
* @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
*
*/
public class TestExcelAntWorkbookUtilFactory {
private static final String mortgageCalculatorWorkbookFile =
BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
/**
* Simple test to determine if the factory properly returns an non-null
* instance of the ExcelAntWorkbookUtil class.
@ -44,29 +40,29 @@ public class TestExcelAntWorkbookUtilFactory {
public void testGetNewWorkbookUtilInstance() {
ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorWorkbookFile) ;
assertNotNull(util) ;
}
/**
* Test whether or not the factory will properly return the same reference
* to an ExcelAnt WorkbookUtil when two different Strings, that point to
* the same resource, are passed in.
* the same resource, are passed in.
*/
@Test
public void testVerifyEquivalence() {
String sameFileName = BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
String sameFileName = TestBuildFile.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorWorkbookFile) ;
ExcelAntWorkbookUtil util2 = ExcelAntWorkbookUtilFactory.getInstance(
sameFileName) ;
assertNotNull(util) ;
assertNotNull(util2) ;
assertEquals(util, util2) ;
}
}

View File

@ -30,6 +30,7 @@ import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
import org.apache.poi.ss.formula.FormulaShifter;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.util.Removal;
/**
*
@ -357,6 +358,10 @@ public final class ValueRecordsAggregate implements Iterable<CellValueRecordInte
return new ValueIterator();
}
@Override
@SuppressWarnings("squid:S2975")
@Deprecated
@Removal(version = "5.0.0")
public Object clone() {
throw new RuntimeException("clone() should not be called. ValueRecordsAggregate should be copied via Sheet.cloneSheet()");
}

View File

@ -51,7 +51,6 @@ import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock;
import org.apache.poi.hssf.usermodel.helpers.HSSFColumnShifter;
import org.apache.poi.hssf.usermodel.helpers.HSSFRowShifter;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.FormulaShifter;
@ -76,6 +75,7 @@ import org.apache.poi.ss.util.SSCellRange;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.poi.util.Beta;
import org.apache.poi.util.Configurator;
import org.apache.poi.util.Internal;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
@ -95,7 +95,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
*/
private static final float PX_MODIFIED = 36.56f;
/**
* Used for compile-time optimization. This is the initial size for the collection of
* rows. It is currently set to 20. If you generate larger sheets you may benefit
@ -501,25 +501,25 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Set the width (in units of 1/256th of a character width)<p>
*
*
* The maximum column width for an individual cell is 255 characters.
* This value represents the number of characters that can be displayed
* in a cell that is formatted with the standard font (first font in the workbook).<p>
*
*
* Character width is defined as the maximum digit width
* of the numbers <code>0, 1, 2, ... 9</code> as rendered
* using the default font (first font in the workbook).<p>
*
*
* Unless you are using a very special font, the default character is '0' (zero),
* this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)<p>
*
*
* Please note, that the width set by this method includes 4 pixels of margin padding (two on each side),
* plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec).
* This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).<p>
*
*
* To compute the actual number of visible characters,
* Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):<p>
*
*
* <code>
* width = Truncate([{Number of Visible Characters} *
* {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
@ -561,7 +561,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
return cw/px;
}
/**
* get the default column width for the sheet (if the columns do not define their own width) in
* characters
@ -730,7 +730,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
// throw IllegalStateException if the argument CellRangeAddress intersects with
// a multi-cell array formula defined in this sheet
validateArrayFormulas(region);
// Throw IllegalStateException if the argument CellRangeAddress intersects with
// a merged region already in this sheet
validateMergedRegions(region);
@ -752,7 +752,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
HSSFRow row = getRow(rowIn);
if (row == null) continue;
for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
HSSFCell cell = row.getCell(colIn);
if (cell == null) continue;
@ -814,11 +814,11 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Control if Excel should be asked to recalculate all formulas on this sheet
* when the workbook is opened.<p>
*
*
* Calculating the formula values with {@link org.apache.poi.ss.usermodel.FormulaEvaluator} is the
* recommended solution, but this may be used for certain cases where
* evaluation in POI is not possible.<p>
*
*
* It is recommended to force recalcuation of formulas on workbook level using
* {@link org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)}
* to ensure that all cross-worksheet formuals and external dependencies are updated.
@ -909,7 +909,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public void removeMergedRegion(int index) {
_sheet.removeMergedRegion(index);
}
/**
* Removes a number of merged regions of cells (hence letting them free)
*
@ -981,7 +981,8 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
*
* @return Sheet - low level representation of this HSSFSheet.
*/
/*package*/ InternalSheet getSheet() {
@Internal
public InternalSheet getSheet() {
return _sheet;
}
@ -1222,7 +1223,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public void setPrintGridlines(boolean show) {
getSheet().getPrintGridlines().setPrintGridlines(show);
}
/**
* Returns whether row and column headings are printed.
*
@ -1408,7 +1409,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
sclRecord.setDenominator((short) denominator);
getSheet().setSCLRecord(sclRecord);
}
/**
* Window zoom magnification for current view representing percent values.
* Valid values range from 10 to 400. Horizontal &amp; Vertical scale together.
@ -1464,7 +1465,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public void showInPane(int topRow, int leftCol) {
int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
if (topRow > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
showInPane((short) topRow, (short) leftCol);
}
/**
@ -1478,10 +1479,10 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
_sheet.setTopRow(toprow);
_sheet.setLeftCol(leftcol);
}
/**
* Shifts, grows, or shrinks the merged regions due to a row shift
*
*
* @param startRow the start-index of the rows to shift, zero-based
* @param endRow the end-index of the rows to shift, zero-based
* @param n how far to shift, negative to shift up
@ -1497,9 +1498,9 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around.<p>
*
*
* Calls {@code shiftRows(startRow, endRow, n, false, false);}<p>
*
*
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).
*
@ -1516,11 +1517,11 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around<p>
*
*
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted). All merged regions that are
* completely overlaid by shifting will be deleted.<p>
*
*
* TODO Might want to add bounds checking here
*
* @param startRow the row to start shifting
@ -1533,7 +1534,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight, true);
}
/**
* bound a row number between 0 and last row index (65535)
*
@ -1549,10 +1550,10 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around<p>
*
*
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).<p>
*
*
* TODO Might want to add bounds checking here
*
* @param startRow the row to start shifting
@ -1578,9 +1579,9 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
// Nothing to do
return;
}
final RowShifter rowShifter = new HSSFRowShifter(this);
// Move comments from the source row to the
// destination row. Note that comments can
// exist for cells which are null
@ -1594,10 +1595,10 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
// Shift Merged Regions
rowShifter.shiftMergedRegions(startRow, endRow, n);
// Shift Row Breaks
_sheet.getPageSettings().shiftRowBreaks(startRow, endRow, n);
// Delete overwritten hyperlinks
deleteOverwrittenHyperlinksForRowShift(startRow, endRow, n);
@ -1747,30 +1748,30 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
}
}
/**
* Shifts columns in range [startColumn, endColumn] for n places to the right.
* For n < 0, it will shift columns left.
* Additionally adjusts formulas.
* Probably should also process other features (hyperlinks, comments...) in the way analog to shiftRows method
* Probably should also process other features (hyperlinks, comments...) in the way analog to shiftRows method
* @param startColumn the column to start shifting
* @param endColumn the column to end shifting
* @param n the number of columns to shift
*/
@Beta
@Override
public void shiftColumns(int startColumn, int endColumn, int n){
HSSFColumnShifter columnShifter = new HSSFColumnShifter(this);
columnShifter.shiftColumns(startColumn, endColumn, n);
public void shiftColumns(int startColumn, int endColumn, int n){
HSSFColumnShifter columnShifter = new HSSFColumnShifter(this);
columnShifter.shiftColumns(startColumn, endColumn, n);
int sheetIndex = _workbook.getSheetIndex(this);
short externSheetIndex = _book.checkExternSheet(sheetIndex);
String sheetName = _workbook.getSheetName(sheetIndex);
FormulaShifter formulaShifter = FormulaShifter.createForColumnShift(
externSheetIndex, sheetName, startColumn, endColumn, n, SpreadsheetVersion.EXCEL97);
updateFormulasForShift(formulaShifter);
// add logic for hyperlinks etc, like in shiftRows()
}
updateFormulasForShift(formulaShifter);
// add logic for hyperlinks etc, like in shiftRows()
}
protected void insertChartRecords(List<Record> records) {
int window2Loc = _sheet.findFirstRecordLocBySid(WindowTwoRecord.sid);
@ -1790,7 +1791,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Creates a split (freezepane). Any existing freezepane or split pane is overwritten.<p>
*
*
* If both colSplit and rowSplit are zero then the existing freeze pane is removed
*
* @param colSplit Horizonatal position of split.
@ -1811,7 +1812,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Creates a split (freezepane). Any existing freezepane or split pane is overwritten.<p>
*
*
* If both colSplit and rowSplit are zero then the existing freeze pane is removed
*
* @param colSplit Horizonatal position of split.
@ -1914,7 +1915,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Sets a page break at the indicated row
* Breaks occur above the specified row and left of the specified column inclusive.<p>
*
*
* For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
* with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
@ -1966,7 +1967,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Sets a page break at the indicated column.
* Breaks occur above the specified row and left of the specified column inclusive.<p>
*
*
* For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
* with columns A,B,C in the first and D,E,... in the second. Simuilar, {@code sheet.setRowBreak(2);}
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
@ -2079,9 +2080,9 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
/**
* Creates the top-level drawing patriarch.
* Creates the top-level drawing patriarch.
* <p>This may then be used to add graphics or charts.</p>
* <p>Note that this will normally have the effect of removing
* <p>Note that this will normally have the effect of removing
* any existing drawings on this sheet.</p>
*
* @return The new patriarch.
@ -2189,7 +2190,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Adjusts the column width to fit the contents.<p>
*
*
* This process can be relatively slow on large sheets, so this should
* normally only be called once per column, at the end of your
* processing.
@ -2203,11 +2204,11 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
/**
* Adjusts the column width to fit the contents.<p>
*
*
* This process can be relatively slow on large sheets, so this should
* normally only be called once per column, at the end of your
* processing.<p>
*
*
* You can specify whether the content of merged cells should be considered or ignored.
* Default is to ignore merged cells.
*
@ -2227,7 +2228,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
setColumnWidth(column, (int) (width));
}
}
/**
* Returns cell comment for the specified row and column
*
@ -2237,7 +2238,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public HSSFComment getCellComment(CellAddress ref) {
return findCellComment(ref.getRow(), ref.getColumn());
}
/**
* Get a Hyperlink in this sheet anchored at row, column
*
@ -2257,7 +2258,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
return null;
}
/**
* Get a Hyperlink in this sheet located in a cell specified by {code addr}
*
@ -2269,7 +2270,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public HSSFHyperlink getHyperlink(CellAddress addr) {
return getHyperlink(addr.getRow(), addr.getColumn());
}
/**
* Get a list of Hyperlinks in this sheet
*
@ -2286,7 +2287,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
return hyperlinkList;
}
/**
* Remove the underlying HyperlinkRecord from this sheet.
* If multiple HSSFHyperlinks refer to the same HyperlinkRecord, all HSSFHyperlinks will be removed.
@ -2296,7 +2297,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
protected void removeHyperlink(HSSFHyperlink link) {
removeHyperlink(link.record);
}
/**
* Remove the underlying HyperlinkRecord from this sheet
*
@ -2415,7 +2416,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
int firstRow = range.getFirstRow();
// if row was not given when constructing the range...
if(firstRow == -1) {
firstRow = 0;
@ -2485,7 +2486,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
if (null == patriarch) {
patriarch = createDrawingPatriarch();
}
Map<CellAddress, HSSFComment> locations = new TreeMap<>();
findCellCommentLocations(patriarch, locations);
return locations;
@ -2663,7 +2664,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
}
return _workbook.getNameRecord(recIndex);
}
/**
* Returns the column outline level. Increased as you
* put it into more groups (outlines), reduced as

View File

@ -15,26 +15,28 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
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.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Class to test that we handle embeded bits in
* OOXML files properly
* Class to test that we handle embeded bits in OOXML files properly
*/
public class TestEmbedded extends TestCase
{
public class TestEmbedded {
@Test
public void testExcel() throws Exception {
POIXMLDocument doc = new XSSFWorkbook(
POIDataSamples.getSpreadSheetInstance().openResourceAsStream("ExcelWithAttachments.xlsm")
@ -42,6 +44,7 @@ public class TestEmbedded extends TestCase
test(doc, 4);
}
@Test
public void testWord() throws Exception {
POIXMLDocument doc = new XWPFDocument(
POIDataSamples.getDocumentInstance().openResourceAsStream("WordWithAttachments.docx")
@ -49,13 +52,14 @@ public class TestEmbedded extends TestCase
test(doc, 5);
}
@Test
public void testPowerPoint() throws Exception {
POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open(
POIDataSamples.getSlideShowInstance().openResourceAsStream("PPTWithAttachments.pptm"))
);
test(doc, 4);
}
private void test(POIXMLDocument doc, int expectedCount) throws Exception {
assertNotNull(doc.getAllEmbeddedParts());
assertEquals(expectedCount, doc.getAllEmbeddedParts().size());
@ -63,7 +67,7 @@ public class TestEmbedded extends TestCase
for(int i=0; i<doc.getAllEmbeddedParts().size(); i++) {
PackagePart pp = doc.getAllEmbeddedParts().get(i);
assertNotNull(pp);
byte[] b = IOUtils.toByteArray(pp.getInputStream());
assertTrue(b.length > 0);
}

View File

@ -17,20 +17,23 @@
package org.apache.poi;
import static org.apache.poi.POITestCase.assertContains;
import junit.framework.TestCase;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.poi.ooxml.extractor.POIXMLPropertiesTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ooxml.util.PackageHelper;
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;
public final class TestXMLPropertiesTextExtractor extends TestCase {
public final class TestXMLPropertiesTextExtractor {
private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance();
private static final POIDataSamples _slSamples = POIDataSamples.getSlideShowInstance();
@Test
public void testGetFromMainExtractor() throws Exception {
OPCPackage pkg = PackageHelper.open(_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm"));
@ -49,11 +52,12 @@ public final class TestXMLPropertiesTextExtractor extends TestCase {
assertContains(text, "LastModifiedBy = Yury Batrakov");
assertContains(cText, "LastModifiedBy = Yury Batrakov");
textExt.close();
ext.close();
}
@Test
public void testCore() throws Exception {
OPCPackage pkg = PackageHelper.open(
_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")
@ -69,10 +73,11 @@ public final class TestXMLPropertiesTextExtractor extends TestCase {
assertContains(text, "LastModifiedBy = Yury Batrakov");
assertContains(cText, "LastModifiedBy = Yury Batrakov");
ext.close();
}
@Test
public void testExtended() throws Exception {
OPCPackage pkg = OPCPackage.open(
_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")
@ -94,6 +99,7 @@ public final class TestXMLPropertiesTextExtractor extends TestCase {
ext.close();
}
@Test
public void testCustom() throws Exception {
OPCPackage pkg = OPCPackage.open(
_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")
@ -106,31 +112,32 @@ public final class TestXMLPropertiesTextExtractor extends TestCase {
// Now check
String text = ext.getText();
String cText = ext.getCustomPropertiesText();
assertContains(text, "description = another value");
assertContains(cText, "description = another value");
ext.close();
}
/**
* Bug #49386 - some properties, especially
* dates can be null
*/
@Test
public void testWithSomeNulls() throws Exception {
OPCPackage pkg = OPCPackage.open(
_slSamples.openResourceAsStream("49386-null_dates.pptx")
);
XSLFSlideShow sl = new XSLFSlideShow(pkg);
POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(sl);
ext.getText();
String text = ext.getText();
assertFalse(text.contains("Created =")); // With date is null
assertContains(text, "CreatedString = "); // Via string is blank
assertContains(text, "LastModifiedBy = IT Client Services");
ext.close();
}
}

View File

@ -17,26 +17,29 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.TreeMap;
import junit.framework.TestCase;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.junit.Before;
import org.junit.Test;
public final class TestListParts extends TestCase {
public final class TestListParts {
private static final POILogger logger = POILogFactory.getLogger(TestListParts.class);
private TreeMap<PackagePartName, String> expectedValues;
private TreeMap<PackagePartName, String> values;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
values = new TreeMap<>();
// Expected values
@ -81,21 +84,21 @@ public final class TestListParts extends TestCase {
/**
* List all parts of a package.
*/
@Test
public void testListParts() throws InvalidFormatException, IOException {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx");
try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx");
OPCPackage p = OPCPackage.open(is)) {
OPCPackage p = OPCPackage.open(is);
for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType());
logger.log(POILogger.DEBUG, part.getPartName());
for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType());
logger.log(POILogger.DEBUG, part.getPartName());
}
// Compare expected values with values return by the package
for (PackagePartName partName : expectedValues.keySet()) {
assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName));
}
}
// Compare expected values with values return by the package
for (PackagePartName partName : expectedValues.keySet()) {
assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName));
}
p.close();
}
}

View File

@ -17,13 +17,16 @@
package org.apache.poi.openxml4j.opc;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
public final class TestPackagePartName extends TestCase {
import org.junit.Test;
public final class TestPackagePartName {
/**
* Test method getExtension().
*/
@Test
public void testGetExtension() throws Exception{
PackagePartName name1 = PackagingURIHelper.createPartName("/doc/props/document.xml");
PackagePartName name2 = PackagingURIHelper.createPartName("/root/document");

View File

@ -17,22 +17,23 @@
package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import junit.framework.TestCase;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.junit.Test;
/**
* Test the addition of thumbnail in a package.
*
* @author Julien Chable
*/
public final class TestPackageThumbnail extends TestCase {
public final class TestPackageThumbnail {
/**
* Test package addThumbnail() method.
*/
@Test
public void testSetProperties() throws Exception {
String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx");
@ -46,7 +47,7 @@ public final class TestPackageThumbnail extends TestCase {
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 {
@ -59,7 +60,7 @@ public final class TestPackageThumbnail extends TestCase {
}
} finally {
p.revert();
outputFile.delete();
assertTrue(outputFile.delete());
}
}
}

View File

@ -16,18 +16,20 @@
==================================================================== */
package org.apache.poi.openxml4j.opc;
import java.net.URI;
import java.net.URISyntaxException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import junit.framework.TestCase;
import java.net.URI;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.junit.Test;
public class TestPackagingURIHelper extends TestCase {
public class TestPackagingURIHelper {
/**
* Test relativizePartName() method.
*/
@Test
public void testRelativizeURI() throws Exception {
URI uri1 = new URI("/word/document.xml");
URI uri2 = new URI("/word/media/image1.gif");
@ -60,18 +62,23 @@ public class TestPackagingURIHelper extends TestCase {
//URI compatible with MS Office and OpenOffice: leading slash is removed
uriRes = PackagingURIHelper.relativizeURI(root, uri1, true);
assertNotNull(uriRes);
assertEquals("word/document.xml", uriRes.toString());
//preserve URI fragments
uriRes = PackagingURIHelper.relativizeURI(uri1, uri3, true);
assertNotNull(uriRes);
assertEquals("media/image1.gif#Sheet1!A1", uriRes.toString());
assertNotNull(uriRes);
uriRes = PackagingURIHelper.relativizeURI(root, uri4, true);
assertNotNull(uriRes);
assertEquals("#'My%20Sheet1'!A1", uriRes.toString());
}
/**
* Test createPartName(String, y)
*/
@Test
public void testCreatePartNameRelativeString()
throws InvalidFormatException {
PackagePartName partNameToValid = PackagingURIHelper
@ -93,6 +100,7 @@ public class TestPackagingURIHelper extends TestCase {
/**
* Test createPartName(URI, y)
*/
@Test
public void testCreatePartNameRelativeURI() throws Exception {
PackagePartName partNameToValid = PackagingURIHelper
.createPartName("/word/media/image1.gif");
@ -110,6 +118,7 @@ public class TestPackagingURIHelper extends TestCase {
pkg.revert();
}
@Test
public void testCreateURIFromString() throws Exception {
String[] href = {
"..\\\\\\cygwin\\home\\yegor\\.vim\\filetype.vim",
@ -120,15 +129,14 @@ public class TestPackagingURIHelper extends TestCase {
"#'性'!B21",
"javascript://"
};
for(String s : href){
try {
URI uri = PackagingURIHelper.toURI(s);
} catch (URISyntaxException e){
fail("Failed to create URI from " + s);
}
URI uri = PackagingURIHelper.toURI(s);
assertNotNull(uri);
}
}
@Test
public void test53734() throws Exception {
URI uri = PackagingURIHelper.toURI("javascript://");
// POI appends a trailing slash tpo avoid "Expected authority at index 13: javascript://"

View File

@ -17,7 +17,12 @@
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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -25,14 +30,13 @@ import java.io.InputStream;
import java.net.URI;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.junit.Test;
public class TestRelationships extends TestCase {
public class TestRelationships {
private static final String HYPERLINK_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
private static final String COMMENTS_REL_TYPE =
@ -48,8 +52,9 @@ public class TestRelationships extends TestCase {
* The code in this case assumes there are no relationships defined, but it should
* really look also for not yet loaded parts.
*/
@Test
public void testLoadRelationships() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx");
InputStream is = openSampleStream("sample.xlsx");
try (OPCPackage pkg = OPCPackage.open(is)) {
logger.log(POILogger.DEBUG, "1: " + pkg);
PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
@ -65,13 +70,14 @@ public class TestRelationships extends TestCase {
}
}
}
/**
* Checks that we can fetch a collection of relations by
* type, then grab from within there by id
*/
@Test
public void testFetchFromCollection() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx");
InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx");
try (OPCPackage pkg = OPCPackage.open(is)) {
PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
@ -107,13 +113,14 @@ public class TestRelationships extends TestCase {
assertNotNull(sheet.getRelationship("rId6"));
}
}
/**
* Excel uses relations on sheets to store the details of
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can load these ok.
*/
@Test
public void testLoadExcelHyperlinkRelations() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx");
InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx");
try (OPCPackage pkg = OPCPackage.open(is)) {
PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
@ -141,21 +148,22 @@ public class TestRelationships extends TestCase {
assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString());
}
}
/*
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can create these OK,
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can create these OK,
* then still read them later
*/
@Test
public void testCreateExcelHyperlinkRelations() throws Exception {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
assertNotNull(sheet);
assertEquals(3, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size());
// Add three new ones
PackageRelationship openxml4j =
sheet.addExternalRelationship("http://www.openxml4j.org/", HYPERLINK_REL_TYPE);
@ -163,53 +171,53 @@ public class TestRelationships extends TestCase {
sheet.addExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE);
PackageRelationship file =
sheet.addExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE);
// Check they were added properly
assertNotNull(openxml4j);
assertNotNull(sf);
assertNotNull(file);
assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size());
assertEquals("http://www.openxml4j.org/", openxml4j.getTargetURI().toString());
assertEquals("/xl/worksheets/sheet1.xml", openxml4j.getSourceURI().toString());
assertEquals(HYPERLINK_REL_TYPE, openxml4j.getRelationshipType());
assertEquals("http://openxml4j.sf.net/", sf.getTargetURI().toString());
assertEquals("/xl/worksheets/sheet1.xml", sf.getSourceURI().toString());
assertEquals(HYPERLINK_REL_TYPE, sf.getRelationshipType());
assertEquals("MyDocument.docx", file.getTargetURI().toString());
assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString());
assertEquals(HYPERLINK_REL_TYPE, file.getRelationshipType());
// Will get ids 7, 8 and 9, as we already have 1-6
assertEquals("rId7", openxml4j.getId());
assertEquals("rId8", sf.getId());
assertEquals("rId9", file.getId());
// Write out and re-load
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pkg.save(baos);
// use revert to not re-write the input file
pkg.revert();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
pkg = OPCPackage.open(bais);
// Check again
sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size());
assertEquals("http://poi.apache.org/",
sheet.getRelationship("rId1").getTargetURI().toString());
assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks",
sheet.getRelationship("rId3").getTargetURI().toString());
assertEquals("http://www.openxml4j.org/",
sheet.getRelationship("rId7").getTargetURI().toString());
assertEquals("http://openxml4j.sf.net/",
@ -218,6 +226,7 @@ public class TestRelationships extends TestCase {
sheet.getRelationship("rId9").getTargetURI().toString());
}
@Test
public void testCreateRelationsFromScratch() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.create(baos);
@ -286,6 +295,7 @@ public class TestRelationships extends TestCase {
partB.getRelationship("rId3").getTargetURI().toString());
}
@Test
public void testTargetWithSpecialChars() throws Exception{
OPCPackage pkg;
@ -305,7 +315,7 @@ public class TestRelationships extends TestCase {
assert_50154(pkg);
}
public void assert_50154(OPCPackage pkg) throws Exception {
private void assert_50154(OPCPackage pkg) throws Exception {
URI drawingURI = new URI("/xl/drawings/drawing1.xml");
PackagePart drawingPart = pkg.getPart(PackagingURIHelper.createPartName(drawingURI));
PackageRelationshipCollection drawingRels = drawingPart.getRelationships();
@ -347,83 +357,89 @@ public class TestRelationships extends TestCase {
assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", rel6.getFragment());
}
@Test
public void testSelfRelations_bug51187() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.create(baos);
PackageRelationship rel1;
try (OPCPackage pkg = OPCPackage.create(baos)) {
PackagePart partA =
pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain");
assertNotNull(partA);
PackagePart partA =
pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain");
assertNotNull(partA);
// reference itself
PackageRelationship rel1 = partA.addRelationship(partA.getPartName(), TargetMode.INTERNAL, "partA");
// Save, and re-load
pkg.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
pkg = OPCPackage.open(bais);
partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
// reference itself
rel1 = partA.addRelationship(partA.getPartName(), TargetMode.INTERNAL, "partA");
// Check the relations
assertEquals(1, partA.getRelationships().size());
PackageRelationship rel2 = partA.getRelationships().getRelationship(0);
assertNotNull(rel2);
assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType());
assertEquals(rel1.getId(), rel2.getId());
assertEquals(rel1.getSourceURI(), rel2.getSourceURI());
assertEquals(rel1.getTargetURI(), rel2.getTargetURI());
assertEquals(rel1.getTargetMode(), rel2.getTargetMode());
}
public void testTrailingSpacesInURI_53282() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("53282.xlsx");
OPCPackage pkg = OPCPackage.open(is);
is.close();
PackageRelationshipCollection sheetRels = pkg.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
assertEquals(3, sheetRels.size());
PackageRelationship rId1 = sheetRels.getRelationshipByID("rId1");
assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
URI targetUri = rId1.getTargetURI();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
ByteArrayOutputStream out = new ByteArrayOutputStream();
pkg.save(out);
out.close();
pkg = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()));
sheetRels = pkg.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
assertEquals(3, sheetRels.size());
rId1 = sheetRels.getRelationshipByID("rId1");
assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
targetUri = rId1.getTargetURI();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
}
public void testEntitiesInRels_56164() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("PackageRelsHasEntities.ooxml");
OPCPackage p = OPCPackage.open(is);
is.close();
// 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;
// Save, and re-load
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try (OPCPackage pkg = OPCPackage.open(bais)) {
PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
// Check the relations
assertEquals(1, partA.getRelationships().size());
PackageRelationship rel2 = partA.getRelationships().getRelationship(0);
assertNotNull(rel2);
assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType());
assertEquals(rel1.getId(), rel2.getId());
assertEquals(rel1.getSourceURI(), rel2.getSourceURI());
assertEquals(rel1.getTargetURI(), rel2.getTargetURI());
assertEquals(rel1.getTargetMode(), rel2.getTargetMode());
}
}
@Test
public void testTrailingSpacesInURI_53282() throws Exception {
try (InputStream is = openSampleStream("53282.xlsx");
OPCPackage pkg1 = OPCPackage.open(is)) {
PackageRelationshipCollection sheetRels = pkg1.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
assertEquals(3, sheetRels.size());
PackageRelationship rId1 = sheetRels.getRelationshipByID("rId1");
assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
URI targetUri = rId1.getTargetURI();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
ByteArrayOutputStream out = new ByteArrayOutputStream();
pkg1.save(out);
out.close();
try (OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()))) {
sheetRels = pkg2.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
assertEquals(3, sheetRels.size());
rId1 = sheetRels.getRelationshipByID("rId1");
assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
targetUri = rId1.getTargetURI();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
}
}
}
@Test
public void testEntitiesInRels_56164() throws Exception {
try (InputStream is = openSampleStream("PackageRelsHasEntities.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;
}
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("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);
}
}

View File

@ -21,6 +21,7 @@ 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 java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
@ -43,8 +44,6 @@ import org.xmlunit.diff.Diff;
import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.ElementSelectors;
import junit.framework.AssertionFailedError;
/**
* Compare the contents of 2 zip files.
*/
@ -140,7 +139,7 @@ public final class ZipFileAssert {
TreeMap<String, ByteArrayOutputStream> file2 = decompress(actual);
equals(file1, file2);
} catch (IOException e) {
throw new AssertionFailedError(e.toString());
fail(e.toString());
}
}

View File

@ -17,6 +17,14 @@
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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -27,7 +35,6 @@ import java.net.URI;
import java.net.URISyntaxException;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.ContentTypes;
@ -39,41 +46,35 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
import org.junit.Test;
import junit.framework.AssertionFailedError;
import static org.junit.Assert.*;
/**
* Test core properties Open Packaging Convention compliance.
*
*
* M4.1: The format designer shall specify and the format producer shall create
* at most one core properties relationship for a package. A format consumer
* shall consider more than one core properties relationship for a package to be
* an error. If present, the relationship shall target the Core Properties part.
* (POI relaxes this on reading, as Office sometimes breaks this)
*
*
* M4.2: The format designer shall not specify and the format producer shall not
* create Core Properties that use the Markup Compatibility namespace as defined
* in Annex F, "Standard Namespaces and Content Types". A format consumer shall
* consider the use of the Markup Compatibility namespace to be an 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.
*
*
* 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.
*
*
* M4.5: Producers shall not create a document element that contains the
* xsi:type attribute, except for a <dcterms:created> or <dcterms:modified>
* element where the xsi:type attribute shall be present and shall hold the
* value dcterms:W3CDTF, where dcterms is the namespace prefix of the Dublin
* Core namespace. Consumers shall consider a document element that violates
* this constraint to be an error.
*
* @author Julien Chable
*/
public final class TestOPCComplianceCoreProperties {
@ -81,7 +82,7 @@ public final class TestOPCComplianceCoreProperties {
public void testCorePropertiesPart() {
OPCPackage pkg;
try {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
pkg = OPCPackage.open(is);
} catch (InvalidFormatException | IOException e) {
throw new RuntimeException(e);
@ -90,7 +91,7 @@ public final class TestOPCComplianceCoreProperties {
}
private static String extractInvalidFormatMessage(String sampleNameSuffix) {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
OPCPackage pkg;
try {
pkg = OPCPackage.open(is);
@ -101,25 +102,27 @@ public final class TestOPCComplianceCoreProperties {
throw new RuntimeException(e);
}
pkg.revert();
throw new AssertionFailedError("expected OPC compliance exception was not thrown");
fail("expected OPC compliance exception was not thrown");
return null;
}
/**
* Test M4.1 rule.
*/
@Test
public void testOnlyOneCorePropertiesPart() throws Exception {
// We have relaxed this check, so we can read the file anyway
try {
extractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx");
fail("M4.1 should be being relaxed");
} catch (AssertionFailedError e) {
// expected here
}
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");
}
// We will use the first core properties, and ignore the others
InputStream is = OpenXML4JTestDataSamples.openSampleStream("MultipleCoreProperties.docx");
try (OPCPackage pkg = OPCPackage.open(is)) {
try (InputStream is = openSampleStream("MultipleCoreProperties.docx");
OPCPackage pkg = OPCPackage.open(is)) {
// We can see 2 by type
assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
@ -132,7 +135,7 @@ public final class TestOPCComplianceCoreProperties {
);
}
}
private static URI createURI(String text) {
try {
return new URI(text);
@ -146,7 +149,7 @@ public final class TestOPCComplianceCoreProperties {
*/
@Test
public void testOnlyOneCorePropertiesPart_AddRelationship() {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
OPCPackage pkg;
try {
pkg = OPCPackage.open(is);
@ -233,7 +236,7 @@ public final class TestOPCComplianceCoreProperties {
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);
}
/**
* Document with no core properties - testing at the OPC level,
* saving into a new stream
@ -263,10 +266,10 @@ public final class TestOPCComplianceCoreProperties {
assertNotNull(pkg.getPackageProperties().getLanguageProperty());
assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
pkg.close();
// Open a new copy of it
pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath());
// Save and re-load, without having touched the properties yet
baos = new ByteArrayOutputStream();
pkg.save(baos);
@ -274,7 +277,7 @@ public final class TestOPCComplianceCoreProperties {
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());

View File

@ -17,6 +17,9 @@
package org.apache.poi.ss.formula.functions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.eval.StringEval;
@ -29,13 +32,8 @@ 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 junit.framework.AssertionFailedError;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class TestProper {
private Cell cell11;
private FormulaEvaluator evaluator;
@ -70,16 +68,16 @@ public final class TestProper {
confirm("PROPER(\"/&%\")", "/&%"); //nothing happens with ascii punctuation that is not upper or lower case
confirm("PROPER(\"Apache POI\")", "Apache Poi"); //acronyms are not special
confirm("PROPER(\" hello world\")", " Hello World"); //leading whitespace is ignored
final String scharfes = "\u00df"; //German lowercase eszett, scharfes s, sharp s
confirm("PROPER(\"stra"+scharfes+"e\")", "Stra"+scharfes+"e");
assertTrue(Character.isLetter(scharfes.charAt(0)));
// CURRENTLY FAILS: result: "SSUnd"+scharfes
// LibreOffice 5.0.3.2 behavior: "Sund"+scharfes
// Excel 2013 behavior: ???
confirm("PROPER(\""+scharfes+"und"+scharfes+"\")", "SSund"+scharfes);
// also test longer string
StringBuilder builder = new StringBuilder("A");
StringBuilder expected = new StringBuilder("A");
@ -94,9 +92,7 @@ public final class TestProper {
cell11.setCellFormula(formulaText);
evaluator.clearAllCachedResultValues();
CellValue cv = evaluator.evaluate(cell11);
if (cv.getCellType() != CellType.STRING) {
throw new AssertionFailedError("Wrong result type: " + cv.formatAsString());
}
assertEquals("Wrong result type", CellType.STRING, cv.getCellType());
String actualValue = cv.getStringValue();
assertEquals(expectedResult, actualValue);
}

View File

@ -16,11 +16,18 @@
==================================================================== */
package org.apache.poi.util;
import junit.framework.TestCase;
import org.apache.poi.ooxml.util.IdentifierManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TestIdentifierManager extends TestCase
{
import org.apache.poi.ooxml.util.IdentifierManager;
import org.junit.Test;
public class TestIdentifierManager {
@Test
public void testBasic()
{
IdentifierManager manager = new IdentifierManager(0L,100L);
@ -31,8 +38,8 @@ public class TestIdentifierManager extends TestCase
assertEquals(99L,manager.getRemainingIdentifiers());
}
public void testLongLimits()
{
@Test
public void testLongLimits() {
long min = IdentifierManager.MIN_ID;
long max = IdentifierManager.MAX_ID;
IdentifierManager manager = new IdentifierManager(min,max);
@ -44,53 +51,44 @@ public class TestIdentifierManager extends TestCase
manager.release(max);
manager.release(min);
}
public void testReserve()
{
@Test
public void testReserve() {
IdentifierManager manager = new IdentifierManager(10L,30L);
assertEquals(12L,manager.reserve(12L));
long reserve = manager.reserve(12L);
assertFalse("Same id must be reserved twice!",reserve == 12L);
assertNotEquals("Same id must be reserved twice!", 12L, reserve);
assertTrue(manager.release(12L));
assertTrue(manager.release(reserve));
assertFalse(manager.release(12L));
assertFalse(manager.release(reserve));
manager = new IdentifierManager(0L,2L);
assertEquals(0L,manager.reserve(0L));
assertEquals(1L,manager.reserve(1L));
assertEquals(2L,manager.reserve(2L));
try
{
try {
manager.reserve(0L);
fail("Exception expected");
}
catch(IllegalStateException e)
{
} catch(IllegalStateException e) {
// expected
}
try
{
try {
manager.reserve(1L);
fail("Exception expected");
}
catch(IllegalStateException e)
{
} catch(IllegalStateException e) {
// expected
}
try
{
try {
manager.reserve(2L);
fail("Exception expected");
}
catch(IllegalStateException e)
{
} catch(IllegalStateException e) {
// expected
}
}
public void testReserveNew()
{
@Test
public void testReserveNew() {
IdentifierManager manager = new IdentifierManager(10L,12L);
assertSame(10L,manager.reserveNew());
assertSame(11L,manager.reserveNew());
@ -98,13 +96,12 @@ public class TestIdentifierManager extends TestCase
try {
manager.reserveNew();
fail("IllegalStateException expected");
}
catch (IllegalStateException e)
{
} catch (IllegalStateException e) {
// expected
}
}
@Test
public void testRelease() {
IdentifierManager manager = new IdentifierManager(10L,20L);
assertEquals(10L,manager.reserve(10L));
@ -112,11 +109,11 @@ public class TestIdentifierManager extends TestCase
assertEquals(12L,manager.reserve(12L));
assertEquals(13L,manager.reserve(13L));
assertEquals(14L,manager.reserve(14L));
assertTrue(manager.release(10L));
assertEquals(10L,manager.reserve(10L));
assertTrue(manager.release(10L));
assertTrue(manager.release(11L));
assertEquals(11L,manager.reserve(11L));
assertTrue(manager.release(11L));

View File

@ -16,17 +16,22 @@
==================================================================== */
package org.apache.poi.xddf.usermodel.chart;
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 org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.SheetBuilder;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests for {@link XDDFDataSourcesFactory}.
*/
public class TestXDDFDataSourcesFactory extends TestCase {
public class TestXDDFDataSourcesFactory {
private static final Object[][] numericCells = {
{0.0, 1.0, 2.0, 3.0, 4.0},
@ -42,6 +47,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
{1.0, "2.0", 3.0, "4.0", 5.0, "6.0"}
};
@Test
public void testNumericArrayDataSource() {
Double[] doubles = new Double[]{1.0, 2.0, 3.0, 4.0, 5.0};
XDDFDataSource<Double> doubleDataSource = XDDFDataSourcesFactory.fromArray(doubles, null);
@ -50,6 +56,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
assertDataSourceIsEqualToArray(doubleDataSource, doubles);
}
@Test
public void testStringArrayDataSource() {
String[] strings = new String[]{"one", "two", "three", "four", "five"};
XDDFDataSource<String> stringDataSource = XDDFDataSourcesFactory.fromArray(strings, null);
@ -58,6 +65,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
assertDataSourceIsEqualToArray(stringDataSource, strings);
}
@Test
public void testNumericCellDataSource() {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, numericCells).build();
@ -72,6 +80,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
}
}
@Test
public void testStringCellDataSource() {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, stringCells).build();
@ -85,6 +94,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
}
}
@Test
public void testMixedCellDataSource() {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, mixedCells).build();
@ -103,6 +113,7 @@ public class TestXDDFDataSourcesFactory extends TestCase {
}
}
@Test
public void testIOBExceptionOnInvalidIndex() {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, numericCells).build();

View File

@ -19,25 +19,30 @@
package org.apache.poi.xssf.eventusermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import org.xml.sax.SAXException;
/**
* Tests for {@link org.apache.poi.xssf.eventusermodel.XSSFReader}
*/
public final class TestReadOnlySharedStringsTable extends TestCase {
@SuppressWarnings("deprecation")
public final class TestReadOnlySharedStringsTable {
private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance();
@Test
public void testParse() throws Exception {
try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) {
List<PackagePart> parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml"));
@ -60,6 +65,7 @@ public final class TestReadOnlySharedStringsTable extends TestCase {
}
//51519
@Test
public void testPhoneticRuns() throws Exception {
try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx"))) {
List < PackagePart > parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml"));
@ -82,13 +88,15 @@ public final class TestReadOnlySharedStringsTable extends TestCase {
}
}
@Test
public void testEmptySSTOnPackageObtainedViaWorkbook() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook(_ssTests.openResourceAsStream("noSharedStringTable.xlsx"));
OPCPackage pkg = wb.getPackage();
assertEmptySST(pkg);
wb.close();
}
@Test
public void testEmptySSTOnPackageDirect() throws Exception {
try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("noSharedStringTable.xlsx"))) {
assertEmptySST(pkg);

View File

@ -17,28 +17,30 @@
package org.apache.poi.xssf.extractor;
import static org.apache.poi.POITestCase.assertStartsWith;
import static org.apache.poi.POITestCase.assertEndsWith;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertEndsWith;
import static org.apache.poi.POITestCase.assertNotContained;
import static org.apache.poi.POITestCase.assertStartsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
/**
* Tests for {@link XSSFExcelExtractor}
*/
public class TestXSSFExcelExtractor extends TestCase {
public class TestXSSFExcelExtractor {
protected XSSFExcelExtractor getExtractor(String sampleName) {
return new XSSFExcelExtractor(XSSFTestDataSamples.openSampleWorkbook(sampleName));
}
@ -46,29 +48,30 @@ public class TestXSSFExcelExtractor extends TestCase {
/**
* Get text out of the simple file
*/
@Test
public void testGetSimpleText() throws IOException {
// a very simple file
XSSFExcelExtractor extractor = getExtractor("sample.xlsx");
String text = extractor.getText();
assertTrue(text.length() > 0);
// Check sheet names
assertStartsWith(text, "Sheet1");
assertEndsWith(text, "Sheet3\n");
// Now without, will have text
extractor.setIncludeSheetNames(false);
text = extractor.getText();
String CHUNK1 =
"Lorem\t111\n" +
"ipsum\t222\n" +
"dolor\t333\n" +
"sit\t444\n" +
"amet\t555\n" +
"consectetuer\t666\n" +
"adipiscing\t777\n" +
"elit\t888\n" +
"Lorem\t111\n" +
"ipsum\t222\n" +
"dolor\t333\n" +
"sit\t444\n" +
"amet\t555\n" +
"consectetuer\t666\n" +
"adipiscing\t777\n" +
"elit\t888\n" +
"Nunc\t999\n";
String CHUNK2 =
"The quick brown fox jumps over the lazy dog\n" +
@ -77,66 +80,68 @@ public class TestXSSFExcelExtractor extends TestCase {
"hello, xssf hello, xssf\n" +
"hello, xssf hello, xssf\n";
assertEquals(
CHUNK1 +
"at\t4995\n" +
CHUNK1 +
"at\t4995\n" +
CHUNK2
, text);
// Now get formulas not their values
extractor.setFormulasNotResults(true);
text = extractor.getText();
assertEquals(
CHUNK1 +
"at\tSUM(B1:B9)\n" +
"at\tSUM(B1:B9)\n" +
CHUNK2, text);
// With sheet names too
extractor.setIncludeSheetNames(true);
text = extractor.getText();
assertEquals(
"Sheet1\n" +
CHUNK1 +
"at\tSUM(B1:B9)\n" +
"at\tSUM(B1:B9)\n" +
"rich test\n" +
CHUNK2 +
"Sheet3\n"
, text);
extractor.close();
}
@Test
public void testGetComplexText() throws IOException {
// A fairly complex file
XSSFExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx");
String text = extractor.getText();
assertTrue(text.length() > 0);
// Might not have all formatting it should do!
assertStartsWith(text,
"Avgtxfull\n" +
"\t(iii) AVERAGE TAX RATES ON ANNUAL"
);
extractor.close();
}
/**
* Test that we return pretty much the same as
* ExcelExtractor does, when we're both passed
* the same file, just saved as xls and xlsx
*/
@Test
public void testComparedToOLE2() throws IOException {
// A fairly simple file - ooxml
XSSFExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx");
ExcelExtractor ole2Extractor =
new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls"));
Map<String, POITextExtractor> extractors = new HashMap<>();
extractors.put("SampleSS.xlsx", ooxmlExtractor);
extractors.put("SampleSS.xls", ole2Extractor);
for (final Entry<String, POITextExtractor> e : extractors.entrySet()) {
String filename = e.getKey();
POITextExtractor extractor = e.getValue();
@ -150,10 +155,11 @@ public class TestXSSFExcelExtractor extends TestCase {
ole2Extractor.close();
ooxmlExtractor.close();
}
/**
* From bug #45540
*/
@Test
public void testHeaderFooter() throws IOException {
String[] files = new String[] {
"45540_classic_Header.xlsx", "45540_form_Header.xlsx",
@ -162,10 +168,10 @@ public class TestXSSFExcelExtractor extends TestCase {
for(String sampleName : files) {
XSSFExcelExtractor extractor = getExtractor(sampleName);
String text = extractor.getText();
assertContains(sampleName, text, "testdoc");
assertContains(sampleName, text, "test phrase");
extractor.close();
}
}
@ -173,6 +179,7 @@ public class TestXSSFExcelExtractor extends TestCase {
/**
* From bug #45544
*/
@Test
public void testComments() throws IOException {
XSSFExcelExtractor extractor = getExtractor("45544.xlsx");
String text = extractor.getText();
@ -186,10 +193,11 @@ public class TestXSSFExcelExtractor extends TestCase {
text = extractor.getText();
assertContains(text, "testdoc");
assertContains(text, "test phrase");
extractor.close();
}
@Test
public void testInlineStrings() throws IOException {
XSSFExcelExtractor extractor = getExtractor("InlineStrings.xlsx");
extractor.setFormulasNotResults(true);
@ -198,24 +206,26 @@ public class TestXSSFExcelExtractor extends TestCase {
// Numbers
assertContains(text, "43");
assertContains(text, "22");
// Strings
assertContains(text, "ABCDE");
assertContains(text, "Long Text");
// Inline Strings
assertContains(text, "1st Inline String");
assertContains(text, "And More");
// Formulas
assertContains(text, "A2");
assertContains(text, "A5-A$2");
extractor.close();
}
/**
* Simple test for text box text
*/
@Test
public void testTextBoxes() throws IOException {
try (XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx")) {
extractor.setFormulasNotResults(true);
@ -226,6 +236,7 @@ public class TestXSSFExcelExtractor extends TestCase {
}
}
@Test
public void testPhoneticRuns() throws Exception {
try (XSSFExcelExtractor extractor = getExtractor("51519.xlsx")) {
String text = extractor.getText();

View File

@ -17,8 +17,9 @@
package org.apache.poi.xssf.extractor;
import org.apache.poi.ooxml.extractor.ExtractorFactory;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ooxml.extractor.ExtractorFactory;
import org.junit.After;
/**
* Tests for {@link XSSFExcelExtractor}
@ -34,8 +35,8 @@ public final class TestXSSFExcelExtractorUsingFactory extends TestXSSFExcelExtra
throw new RuntimeException(e);
}
}
@Override
@After
public void tearDown() {
// reset setting to not affect other tests
ExtractorFactory.setAllThreadsPreferEventExtractors(null);

View File

@ -17,22 +17,25 @@
package org.apache.poi.xssf.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.POIDataSamples;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
public class TestLoadSaveXSSF extends TestCase {
public class TestLoadSaveXSSF {
private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance();
@Test
public void testLoadSample() throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("sample.xlsx"))) {
assertEquals(3, workbook.getNumberOfSheets());
@ -47,6 +50,7 @@ public class TestLoadSaveXSSF extends TestCase {
}
}
@Test
public void testLoadStyles() throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("styles.xlsx"))) {
Sheet sheet = workbook.getSheetAt(0);
@ -57,6 +61,7 @@ public class TestLoadSaveXSSF extends TestCase {
}
}
@Test
public void testLoadPictures() throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("picture.xlsx"))) {
List<XSSFPictureData> pictures = workbook.getAllPictures();

View File

@ -17,19 +17,21 @@
package org.apache.poi.xssf.model;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
import junit.framework.TestCase;
import java.io.IOException;
public final class TestCalculationChain extends TestCase {
public final class TestCalculationChain {
@Test
public void test46535() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("46535.xlsx")) {

View File

@ -17,35 +17,35 @@
package org.apache.poi.xssf.model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.poi.POIDataSamples;
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.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPhoneticRun;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import junit.framework.TestCase;
/**
* Test {@link SharedStringsTable}, the cache of strings in a workbook
*
* @author Yegor Kozlov
*/
public final class TestSharedStringsTable extends TestCase {
public final class TestSharedStringsTable {
@SuppressWarnings("deprecation")
@Test
public void testCreateNew() {
SharedStringsTable sst = new SharedStringsTable();
@ -117,6 +117,7 @@ public final class TestSharedStringsTable extends TestCase {
assertEquals("Second string", new XSSFRichTextString(sst.getEntryAt(2)).toString());
}
@Test
public void testCreateUsingRichTextStrings() {
SharedStringsTable sst = new SharedStringsTable();
@ -183,6 +184,7 @@ public final class TestSharedStringsTable extends TestCase {
assertEquals("Second string", sst.getItemAt(2).toString());
}
@Test
@SuppressWarnings("deprecation")
public void testReadWrite() throws IOException {
XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
@ -222,14 +224,21 @@ public final class TestSharedStringsTable extends TestCase {
* Test for Bugzilla 48936
*
* A specific sequence of strings can result in broken CDATA section in sharedStrings.xml file.
*
* @author Philippe Laflamme
*/
@Test
public void testBug48936() throws IOException {
Workbook w1 = new XSSFWorkbook();
Sheet s = w1.createSheet();
int i = 0;
List<String> lst = readStrings("48936-strings.txt");
Path path = XSSFTestDataSamples.getSampleFile("48936-strings.txt").toPath();
List<String> lst = Files
.lines(path, StandardCharsets.UTF_8)
.map(String::trim)
.filter(((Predicate<String>)String::isEmpty).negate())
.collect(Collectors.toList());
for (String str : lst) {
s.createRow(i++).createCell(0).setCellValue(str);
}
@ -242,26 +251,10 @@ public final class TestSharedStringsTable extends TestCase {
String val = s.getRow(i++).getCell(0).getStringCellValue();
assertEquals(str, val);
}
Workbook w3 = XSSFTestDataSamples.writeOutAndReadBack(w2);
w2.close();
assertNotNull(w3);
w3.close();
}
private List<String> readStrings(String filename) throws IOException {
List<String> strs = new ArrayList<>();
POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
BufferedReader br = new BufferedReader(
new InputStreamReader(samples.openResourceAsStream(filename), StandardCharsets.UTF_8));
String s;
while ((s = br.readLine()) != null) {
if (s.trim().length() > 0) {
strs.add(s.trim());
}
}
br.close();
return strs;
}
}

View File

@ -20,7 +20,6 @@ package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.formula.eval.forked.TestForkedEvaluator;
import org.apache.poi.xssf.usermodel.extensions.TestXSSFBorder;
import org.apache.poi.xssf.usermodel.extensions.TestXSSFCellFill;
import org.apache.poi.xssf.usermodel.extensions.TestXSSFSheetComments;
import org.apache.poi.xssf.usermodel.helpers.TestColumnHelper;
import org.apache.poi.xssf.usermodel.helpers.TestHeaderFooterHelper;
import org.junit.runner.RunWith;
@ -56,7 +55,6 @@ import org.junit.runners.Suite;
TestXSSFWorkbook.class,
TestXSSFBorder.class,
TestXSSFCellFill.class,
TestXSSFSheetComments.class,
TestColumnHelper.class,
TestHeaderFooterHelper.class,
//TestXSSFPivotTable.class, //converted to junit4

View File

@ -16,7 +16,9 @@
==================================================================== */
package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
@ -41,14 +43,13 @@ public abstract class BaseTestXSSFPivotTable {
protected XSSFPivotTable pivotTable;
protected XSSFPivotTable offsetPivotTable;
protected Cell offsetOuterCell;
/**
* required to set up the test pivot tables and cell reference, either by name or reference.
* @see junit.framework.TestCase#setUp()
*/
@Before
public abstract void setUp();
@After
public void tearDown() throws IOException {
if (wb != null) {
@ -67,18 +68,18 @@ public abstract class BaseTestXSSFPivotTable {
int columnIndex = 0;
assertEquals(0, pivotTable.getRowLabelColumns().size());
pivotTable.addRowLabel(columnIndex);
CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition();
assertEquals(defintion.getRowFields().getFieldArray(0).getX(), columnIndex);
assertEquals(defintion.getRowFields().getCount(), 1);
assertEquals(1, pivotTable.getRowLabelColumns().size());
columnIndex = 1;
pivotTable.addRowLabel(columnIndex);
assertEquals(2, pivotTable.getRowLabelColumns().size());
assertEquals(0, (int)pivotTable.getRowLabelColumns().get(0));
assertEquals(1, (int)pivotTable.getRowLabelColumns().get(1));
}
@ -120,8 +121,8 @@ public abstract class BaseTestXSSFPivotTable {
assertEquals(defintion.getDataFields().getDataFieldList().size(), 3);
}
/**
* Verify that it's possible to create three column labels with the same DataConsolidateFunction
*/
@ -138,7 +139,7 @@ public abstract class BaseTestXSSFPivotTable {
assertEquals(defintion.getDataFields().getDataFieldList().size(), 3);
}
/**
* Verify that when creating two column labels, a col field is being created and X is set to -2.
*/
@ -169,7 +170,7 @@ public abstract class BaseTestXSSFPivotTable {
assertEquals(defintion.getDataFields().getDataFieldArray(0).getSubtotal(),
STDataConsolidateFunction.Enum.forInt(DataConsolidateFunction.SUM.getValue()));
}
/**
* Verify that it's possible to set a custom name when creating a data column
*/
@ -178,7 +179,7 @@ public abstract class BaseTestXSSFPivotTable {
int columnIndex = 0;
String customName = "Custom Name";
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex, customName);
CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition();
@ -186,7 +187,7 @@ public abstract class BaseTestXSSFPivotTable {
assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex);
assertEquals(defintion.getDataFields().getDataFieldArray(0).getName(), customName);
}
/**
* Verify that it's possible to set the format to the data column
*/
@ -195,7 +196,7 @@ public abstract class BaseTestXSSFPivotTable {
int columnIndex = 0;
String format = "#,##0.0";
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex, null, format);
CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition();
@ -256,7 +257,7 @@ public abstract class BaseTestXSSFPivotTable {
public void testAddReportFilterOutOfRangeThrowsException() {
pivotTable.addReportFilter(5);
}
/**
* Verify that the Pivot Table operates only within the referenced area, even when the
* first column of the referenced area is not index 0.
@ -265,10 +266,10 @@ public abstract class BaseTestXSSFPivotTable {
public void testAddDataColumnWithOffsetData() {
offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
assertEquals(CellType.NUMERIC, offsetOuterCell.getCellType());
offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 0);
}
@Test
public void testPivotTableSheetNamesAreCaseInsensitive() {
wb.setSheetName(0, "original");
@ -278,7 +279,7 @@ public abstract class BaseTestXSSFPivotTable {
// assume sheets are accessible via case-insensitive name
assertNotNull(original);
assertNotNull(offset);
AreaReference source = wb.getCreationHelper().createAreaReference("ORIGinal!A1:C2");
// create a pivot table on the same sheet, case insensitive
original.createPivotTable(source, new CellReference("W1"));
@ -296,18 +297,18 @@ public abstract class BaseTestXSSFPivotTable {
int columnIndex = 0;
assertEquals(0, pivotTable.getColLabelColumns().size());
pivotTable.addColLabel(columnIndex);
CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition();
assertEquals(defintion.getColFields().getFieldArray(0).getX(), columnIndex);
assertEquals(defintion.getColFields().getCount(), 1);
assertEquals(1, pivotTable.getColLabelColumns().size());
columnIndex = 1;
pivotTable.addColLabel(columnIndex);
assertEquals(2, pivotTable.getColLabelColumns().size());
assertEquals(0, (int)pivotTable.getColLabelColumns().get(0));
assertEquals(1, (int)pivotTable.getColLabelColumns().get(1));
}

View File

@ -26,8 +26,6 @@ import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.apache.poi.poifs.crypt.TestSignatureInfo;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.functions.TestMathX;
import org.apache.poi.ss.usermodel.Cell;
@ -47,8 +45,6 @@ import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import junit.framework.AssertionFailedError;
@RunWith(Parameterized.class)
public final class TestMatrixFormulasFromXMLSpreadsheet {
@ -58,17 +54,17 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
private static Sheet sheet;
private static FormulaEvaluator evaluator;
private static Locale userLocale;
/*
* Unlike TestFormulaFromSpreadsheet which this class is modified from, there is no
* differentiation between operators and functions, if more functionality is implemented with
* array formulas then it might be worth it to separate operators from functions
*
*
* Also, output matrices are statically 3x3, if larger matrices wanted to be tested
* then adding matrix size parameter would be useful and parsing would be based off that.
*/
private static interface Navigator {
private interface Navigator {
/**
* Name of the test spreadsheet (found in the standard test data folder)
*/
@ -97,21 +93,21 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
* Used to indicate when there are no more operations left
*/
String END_OF_TESTS = "<END>";
}
/* Parameters for test case */
@Parameter(0)
public String targetFunctionName;
@Parameter(1)
public int formulasRowIdx;
@AfterClass
public static void closeResource() throws Exception {
LocaleUtil.setUserLocale(userLocale);
workbook.close();
}
/* generating parameter instances */
@Parameters(name="{0}")
public static Collection<Object[]> data() throws Exception {
@ -120,18 +116,18 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
// already set, when we would try to change the locale by then
userLocale = LocaleUtil.getUserLocale();
LocaleUtil.setUserLocale(Locale.ROOT);
workbook = XSSFTestDataSamples.openSampleWorkbook(Navigator.FILENAME);
sheet = workbook.getSheetAt(0);
evaluator = new XSSFFormulaEvaluator(workbook);
List<Object[]> data = new ArrayList<Object[]>();
processFunctionGroup(data, Navigator.START_OPERATORS_ROW_INDEX, null);
return data;
}
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
* @param testFocusFunctionName name of a single function/operator to test alone.
@ -153,7 +149,7 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
}
}
}
@Test
public void processFunctionRow() {
@ -162,27 +158,27 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
for (int rowNum = formulasRowIdx; rowNum < formulasRowIdx + Navigator.ROW_OFF_NEXT_OP - 1; rowNum++) {
for (int colNum = Navigator.START_RESULT_COL_INDEX; colNum < endColNum; colNum++) {
Row r = sheet.getRow(rowNum);
/* mainly to escape row failures on MDETERM which only returns a scalar */
if (r == null) {
continue;
}
Cell c = sheet.getRow(rowNum).getCell(colNum);
if (c == null || c.getCellType() != CellType.FORMULA) {
continue;
}
CellValue actValue = evaluator.evaluate(c);
Cell expValue = sheet.getRow(rowNum).getCell(colNum + Navigator.COL_OFF_EXPECTED_RESULT);
String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d"
, targetFunctionName, c.getCellFormula(), rowNum, colNum);
assertNotNull(msg + " - Bad setup data expected value is null", expValue);
assertNotNull(msg + " - actual value was null", actValue);
final CellType cellType = expValue.getCellType();
switch (cellType) {
case BLANK:
@ -212,7 +208,7 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
}
}
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
@ -234,13 +230,8 @@ public final class TestMatrixFormulasFromXMLSpreadsheet {
return cell.getRichStringCellValue().getString();
}
throw new AssertionFailedError("Bad cell type for 'function name' column: ("
fail("Bad cell type for 'function name' column: ("
+ cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")");
return null;
}
}

View File

@ -17,14 +17,17 @@
package org.apache.poi.xssf.usermodel;
import org.apache.poi.xssf.XSSFTestDataSamples;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
public final class TestXSSFChart extends TestCase {
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
public final class TestXSSFChart {
@Test
public void testGetAccessors() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) {
XSSFSheet s1 = wb.getSheetAt(0);
@ -39,6 +42,7 @@ public final class TestXSSFChart extends TestCase {
}
}
@Test
public void testGetCharts() throws Exception {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) {
XSSFSheet s1 = wb.getSheetAt(0);
@ -67,6 +71,7 @@ public final class TestXSSFChart extends TestCase {
}
}
@Test
public void testAddChartsToNewWorkbook() throws Exception {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet s1 = wb.createSheet();

View File

@ -17,27 +17,34 @@
package org.apache.poi.xssf.usermodel;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.TreeMap;
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.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.StylesTable;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXstring;
import java.io.IOException;
import java.util.TreeMap;
/**
* Tests functionality of the XSSFRichTextRun object
*
* @author Yegor Kozlov
*/
public final class TestXSSFRichTextString extends TestCase {
public final class TestXSSFRichTextString {
@Test
public void testCreate() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
assertEquals("Apache POI", rt.getString());
@ -56,6 +63,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertFalse(rt.hasFormatting());
}
@Test
public void testEmpty() {
XSSFRichTextString rt = new XSSFRichTextString();
assertEquals(0, rt.getIndexOfFormattingRun(9999));
@ -63,6 +71,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertNull(rt.getFontAtIndex(9999));
}
@Test
public void testApplyFont() {
XSSFRichTextString rt = new XSSFRichTextString();
rt.append("123");
@ -92,43 +101,46 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals(7, rt.getIndexOfFormattingRun(3));
assertEquals(2, rt.getLengthOfFormattingRun(3));
assertEquals("89", rt.getCTRst().getRArray(3).getT());
assertEquals(-1, rt.getIndexOfFormattingRun(9999));
assertEquals(-1, rt.getLengthOfFormattingRun(9999));
assertNull(rt.getFontAtIndex(9999));
}
@Test
public void testApplyFontIndex() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
rt.applyFont(0, 10, (short)1);
rt.applyFont((short)1);
assertNotNull(rt.getFontAtIndex(0));
}
@Test
public void testApplyFontWithStyles() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
StylesTable tbl = new StylesTable();
rt.setStylesTableReference(tbl);
try {
rt.applyFont(0, 10, (short)1);
fail("Fails without styles in the table");
} catch (IndexOutOfBoundsException e) {
// expected
}
tbl.putFont(new XSSFFont());
rt.applyFont(0, 10, (short)1);
rt.applyFont((short)1);
}
@Test
public void testApplyFontException() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
rt.applyFont(0, 0, (short)1);
try {
@ -153,6 +165,7 @@ public final class TestXSSFRichTextString extends TestCase {
}
}
@Test
public void testClearFormatting() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
@ -173,14 +186,15 @@ public final class TestXSSFRichTextString extends TestCase {
rt.applyFont(7, 10, font);
assertEquals(2, rt.numFormattingRuns());
assertTrue(rt.hasFormatting());
rt.clearFormatting();
assertEquals("Apache POI", rt.getString());
assertEquals(0, rt.numFormattingRuns());
assertFalse(rt.hasFormatting());
}
@Test
public void testGetFonts() {
XSSFRichTextString rt = new XSSFRichTextString();
@ -208,6 +222,7 @@ public final class TestXSSFRichTextString extends TestCase {
* make sure we insert xml:space="preserve" attribute
* if a string has leading or trailing white spaces
*/
@Test
public void testPreserveSpaces() {
XSSFRichTextString rt = new XSSFRichTextString("Apache");
CTRst ct = rt.getCTRst();
@ -227,6 +242,7 @@ public final class TestXSSFRichTextString extends TestCase {
/**
* test that unicode representation_ xHHHH_ is properly processed
*/
@Test
public void testUtfDecode() {
CTRst st = CTRst.Factory.newInstance();
st.setT("abc_x000D_2ef_x000D_");
@ -241,6 +257,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals("abc\r2ef\r", rt2.getString());
}
@Test
public void testApplyFont_lowlevel(){
CTRst st = CTRst.Factory.newInstance();
String text = "Apache Software Foundation";
@ -355,6 +372,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertSame(fmt5, runs12[4]);
}
@Test
public void testApplyFont_usermodel(){
String text = "Apache Software Foundation";
XSSFRichTextString str = new XSSFRichTextString(text);
@ -382,6 +400,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals(" Software Foundation", str.getCTRst().getRArray(1).getT());
}
@Test
public void testLineBreaks_bug48877() {
XSSFFont font = new XSSFFont();
@ -441,6 +460,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals("<xml-fragment xml:space=\"preserve\">\n\n</xml-fragment>", t3.xmlText());
}
@Test
public void testBug56511() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx")) {
for (Sheet sheet : wb) {
@ -471,6 +491,7 @@ public final class TestXSSFRichTextString extends TestCase {
}
}
@Test
public void testBug56511_values() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
@ -510,6 +531,7 @@ public final class TestXSSFRichTextString extends TestCase {
}
}
@Test
public void testToString() {
XSSFRichTextString rt = new XSSFRichTextString("Apache POI");
assertNotNull(rt.toString());
@ -518,6 +540,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals("", rt.toString());
}
@Test
public void test59008Font() {
XSSFFont font = new XSSFFont(CTFont.Factory.newInstance());
@ -534,6 +557,7 @@ public final class TestXSSFRichTextString extends TestCase {
assertEquals("<xml-fragment/>", rts.getFontAtIndex(s3-1).toString());
}
@Test
public void test60289UtfDecode() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60289.xlsx");
assertEquals("Rich Text\r\nTest", wb.getSheetAt(0).getRow(1).getCell(1).getRichStringCellValue().getString());

View File

@ -17,23 +17,24 @@
package org.apache.poi.xssf.usermodel;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import junit.framework.TestCase;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
public final class TestXSSFSheetRowGrouping extends TestCase {
public final class TestXSSFSheetRowGrouping {
private static final int ROWS_NUMBER = 200;
private static final int GROUP_SIZE = 5;
//private int o_groupsNumber = 0;
@Test
public void test55640() {
//long startTime = System.currentTimeMillis();
Workbook wb = new XSSFWorkbook();
@ -88,6 +89,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(p_wb));
}
@Test
public void test55640reduce1() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -106,7 +108,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
while (start < end) { // natural order
sheet.groupRow(start, end);
//o_groupsNumber++;
boolean collapsed = start % 2 == 0 ? false : true;
boolean collapsed = (start % 2) != 0;
//System.out.println("Set group " + start + "->" + end + " to " + collapsed);
sheet.setRowGroupCollapsed(start, collapsed);
start++; // natural order
@ -116,29 +118,29 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
writeToFile(wb);
}
@Test
public void test55640_VerifyCases() {
// NOTE: This is currently based on current behavior of POI, somehow
// what POI returns in the calls to collapsed/hidden is not fully matching
// what POI returns in the calls to collapsed/hidden is not fully matching
// the examples in the spec or I did not fully understand how POI stores the data internally...
// all expanded
verifyGroupCollapsed(
// level1, level2, level3
false, false, false,
false, false, false,
// collapsed:
new Boolean[] { false, false, false, false, false},
new Boolean[] { false, false, false, false, false},
// hidden:
new boolean[] { false, false, false, false, false},
// outlineLevel
new int[] { 1, 2, 3, 3, 3 }
);
// Level 1 collapsed, others expanded, should only have 4 rows, all hidden:
// Level 1 collapsed, others expanded, should only have 4 rows, all hidden:
verifyGroupCollapsed(
// level1, level2, level3
true, false, false,
true, false, false,
// collapsed:
new Boolean[] { false, false, false, false, false},
// hidden:
@ -147,10 +149,10 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
new int[] { 1, 2, 3, 3, 3 }
);
// Level 1 and 2 collapsed, Level 3 expanded,
// Level 1 and 2 collapsed, Level 3 expanded,
verifyGroupCollapsed(
// level1, level2, level3
true, true, false,
true, true, false,
// collapsed:
new Boolean[] { false, false, false, false, true, false},
// hidden:
@ -159,10 +161,10 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
new int[] { 1, 2, 3, 3, 3, 0 }
);
// Level 1 collapsed, Level 2 expanded, Level 3 collapsed
// Level 1 collapsed, Level 2 expanded, Level 3 collapsed
verifyGroupCollapsed(
// level1, level2, level3
true, false, true,
true, false, true,
// collapsed:
new Boolean[] { false, false, false, false, false, true},
// hidden:
@ -174,7 +176,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
// Level 2 collapsed, others expanded:
verifyGroupCollapsed(
// level1, level2, level3
false, true, false,
false, true, false,
// collapsed:
new Boolean[] { false, false, false, false, false, false},
// hidden:
@ -183,10 +185,10 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
new int[] { 1, 2, 3, 3, 3, 0 }
);
// Level 3 collapsed, others expanded
// Level 3 collapsed, others expanded
verifyGroupCollapsed(
// level1, level2, level3
false, false, true,
false, false, true,
// collapsed:
new Boolean[] { false, false, false, false, false, true},
// hidden:
@ -195,10 +197,10 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
new int[] { 1, 2, 3, 3, 3, 0 }
);
// All collapsed
// All collapsed
verifyGroupCollapsed(
// level1, level2, level3
true, true, true,
true, true, true,
// collapsed:
new Boolean[] { false, false, false, false, true, true},
// hidden:
@ -207,9 +209,9 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
new int[] { 1, 2, 3, 3, 3, 0 }
);
}
private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3,
private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3,
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -217,11 +219,11 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
for (int i = 0; i < 4; i++) {
sheet.createRow(i);
}
sheet.groupRow(0, 4);
sheet.groupRow(1, 4);
sheet.groupRow(2, 4);
sheet.setRowGroupCollapsed(0, level1);
sheet.setRowGroupCollapsed(1, level2);
sheet.setRowGroupCollapsed(2, level3);
@ -229,27 +231,28 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel);
}
public void test55640_VerifyCasesSpec() throws IOException {
@Test
public void test55640_VerifyCasesSpec() {
// NOTE: This is currently based on current behavior of POI, somehow
// what POI returns in the calls to collapsed/hidden is not fully matching
// what POI returns in the calls to collapsed/hidden is not fully matching
// the examples in the spec or I did not fully understand how POI stores the data internally...
// all expanded
verifyGroupCollapsedSpec(
// level3, level2, level1
false, false, false,
false, false, false,
// collapsed:
new Boolean[] { false, false, false, false},
new Boolean[] { false, false, false, false},
// hidden:
new boolean[] { false, false, false, false},
// outlineLevel
new int[] { 3, 3, 2, 1 }
);
verifyGroupCollapsedSpec(
// level3, level2, level1
false, false, true,
false, false, true,
// collapsed:
new Boolean[] { false, false, false, true},
// hidden:
@ -260,7 +263,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
verifyGroupCollapsedSpec(
// level3, level2, level1
false, true, false,
false, true, false,
// collapsed:
new Boolean[] { false, false, true, false},
// hidden:
@ -268,10 +271,10 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
// outlineLevel
new int[] { 3, 3, 2, 1 }
);
verifyGroupCollapsedSpec(
// level3, level2, level1
false, true, true,
false, true, true,
// collapsed:
new Boolean[] { false, false, true, true},
// hidden:
@ -281,34 +284,34 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
);
}
private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3,
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
@SuppressWarnings("SameParameterValue")
private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3,
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
for (int i = 5; i < 9; i++) {
sheet.createRow(i);
}
sheet.groupRow(5, 6);
sheet.groupRow(5, 7);
sheet.groupRow(5, 8);
sheet.setRowGroupCollapsed(6, level1);
sheet.setRowGroupCollapsed(7, level2);
sheet.setRowGroupCollapsed(8, level3);
checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel);
}
private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
printWorkbook(wb);
Sheet sheet = wb.getSheetAt(0);
assertEquals(collapsed.length, hidden.length);
assertEquals(collapsed.length, outlineLevel.length);
assertEquals("Expected " + collapsed.length + " rows with collapsed state, but had " + (sheet.getLastRowNum()-sheet.getFirstRowNum()+1) + " rows ("
+ sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")",
+ sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")",
collapsed.length, sheet.getLastRowNum()-sheet.getFirstRowNum()+1);
for(int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum();i++) {
if(collapsed[i-sheet.getFirstRowNum()] == null) {
@ -317,16 +320,16 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
XSSFRow row = (XSSFRow) sheet.getRow(i);
assertNotNull("Could not read row " + i, row);
assertNotNull("Could not read row " + i, row.getCTRow());
assertEquals("Row: " + i + ": collapsed", collapsed[i-sheet.getFirstRowNum()].booleanValue(), row.getCTRow().getCollapsed());
assertEquals("Row: " + i + ": collapsed", collapsed[i - sheet.getFirstRowNum()], row.getCTRow().getCollapsed());
assertEquals("Row: " + i + ": hidden", hidden[i-sheet.getFirstRowNum()], row.getCTRow().getHidden());
assertEquals("Row: " + i + ": level", outlineLevel[i-sheet.getFirstRowNum()], row.getCTRow().getOutlineLevel());
}
writeToFile(wb);
}
@Test
public void test55640working() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -334,7 +337,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
sheet.groupRow(1, 4);
sheet.groupRow(2, 5);
sheet.groupRow(3, 6);
sheet.setRowGroupCollapsed(1, true);
sheet.setRowGroupCollapsed(2, false);
sheet.setRowGroupCollapsed(3, false);
@ -342,29 +345,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
writeToFile(wb);
}
// just used for printing out contents of spreadsheets
public void notRuntest55640printSample() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55640.xlsx");
printWorkbook(wb);
wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx");
printWorkbook(wb);
}
private void printWorkbook(Workbook wb) {
// disable all output for now...
// Sheet sheet = wb.getSheetAt(0);
//
// for(Iterator<Row> it = sheet.rowIterator();it.hasNext();) {
// XSSFRow row = (XSSFRow) it.next();
// boolean collapsed = row.getCTRow().getCollapsed();
// boolean hidden = row.getCTRow().getHidden();
// short level = row.getCTRow().getOutlineLevel();
//
// System.out.println("Row: " + row.getRowNum() + ": Level: " + level + " Collapsed: " + collapsed + " Hidden: " + hidden);
// }
}
@Test
public void testGroupingTest() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx")) {

View File

@ -19,6 +19,7 @@ package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
@ -33,12 +34,8 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
import junit.framework.AssertionFailedError;
/**
* Test array formulas in XSSF
*
* @author Yegor Kozlov
* @author Josh Micich
*/
public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas {
@ -67,7 +64,7 @@ public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateA
//retrieve the range and check it is the same
assertEquals(range.formatAsString(), firstCell.getArrayFormulaRange().formatAsString());
confirmArrayFormulaCell(firstCell, "C3", formula1, "C3");
workbook.close();
}
@ -103,9 +100,7 @@ public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateA
confirmArrayFormulaCell(c, cellRef, null, null);
}
private static void confirmArrayFormulaCell(XSSFCell c, String cellRef, String formulaText, String arrayRangeRef) {
if (c == null) {
throw new AssertionFailedError("Cell should not be null.");
}
assertNotNull("Cell should not be null.", c);
CTCell ctCell = c.getCTCell();
assertEquals(cellRef, ctCell.getR());
if (formulaText == null) {

View File

@ -17,6 +17,8 @@
package org.apache.poi.xssf.usermodel.charts;
import static org.junit.Assert.assertEquals;
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis;
@ -25,24 +27,22 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import junit.framework.TestCase;
public final class TestXSSFCategoryAxis extends TestCase {
public final class TestXSSFCategoryAxis {
@Test
public void testAccessMethods() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
assertEquals(chart.getAxes().size(), 1);
wb.close();
assertEquals(chart.getAxes().size(), 1);
}
}
}

View File

@ -17,6 +17,11 @@
package org.apache.poi.xssf.usermodel.charts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
@ -29,17 +34,19 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
public final class TestXSSFChartAxis extends TestCase {
public final class TestXSSFChartAxis {
private static final double EPSILON = 1E-7;
private final XDDFChartAxis axis;
private XSSFWorkbook wb;
private XDDFChartAxis axis;
public TestXSSFChartAxis() {
super();
XSSFWorkbook wb = new XSSFWorkbook();
@Before
public void setup() {
wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
@ -47,6 +54,14 @@ public final class TestXSSFChartAxis extends TestCase {
axis = chart.createValueAxis(AxisPosition.BOTTOM);
}
@After
public void teardown() throws IOException {
wb.close();
wb = null;
axis = null;
}
@Test
public void testLogBaseIllegalArgument() {
IllegalArgumentException iae = null;
try {
@ -65,17 +80,20 @@ public final class TestXSSFChartAxis extends TestCase {
assertNotNull(iae);
}
@Test
public void testLogBaseLegalArgument() {
axis.setLogBase(Math.E);
assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON);
}
@Test
public void testNumberFormat() {
final String numberFormat = "General";
axis.setNumberFormat(numberFormat);
assertEquals(numberFormat, axis.getNumberFormat());
}
@Test
public void testMaxAndMinAccessMethods() {
final double newValue = 10.0;
@ -86,6 +104,7 @@ public final class TestXSSFChartAxis extends TestCase {
assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON);
}
@Test
public void testVisibleAccessMethods() {
axis.setVisible(true);
assertTrue(axis.isVisible());
@ -94,6 +113,7 @@ public final class TestXSSFChartAxis extends TestCase {
assertFalse(axis.isVisible());
}
@Test
public void testMajorTickMarkAccessMethods() {
axis.setMajorTickMark(AxisTickMark.NONE);
assertEquals(AxisTickMark.NONE, axis.getMajorTickMark());
@ -108,6 +128,7 @@ public final class TestXSSFChartAxis extends TestCase {
assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark());
}
@Test
public void testMinorTickMarkAccessMethods() {
axis.setMinorTickMark(AxisTickMark.NONE);
assertEquals(AxisTickMark.NONE, axis.getMinorTickMark());
@ -122,6 +143,7 @@ public final class TestXSSFChartAxis extends TestCase {
assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark());
}
@Test
public void testGetChartAxisBug57362() throws IOException {
//Load existing excel with some chart on it having primary and secondary axis.
try (final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx")) {

View File

@ -17,6 +17,8 @@
package org.apache.poi.xssf.usermodel.charts;
import static org.junit.Assert.assertEquals;
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.XDDFDateAxis;
@ -25,24 +27,23 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import junit.framework.TestCase;
public final class TestXSSFDateAxis extends TestCase {
public final class TestXSSFDateAxis {
@Test
public void testAccessMethods() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
assertEquals(chart.getAxes().size(), 1);
wb.close();
assertEquals(chart.getAxes().size(), 1);
}
}
}

View File

@ -17,6 +17,8 @@
package org.apache.poi.xssf.usermodel.charts;
import static org.junit.Assert.assertEquals;
import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween;
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
@ -26,27 +28,26 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import junit.framework.TestCase;
public final class TestXSSFValueAxis extends TestCase {
public final class TestXSSFValueAxis {
@Test
public void testAccessMethods() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart chart = drawing.createChart(anchor);
XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM);
axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY);
assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY);
axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY);
assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
axis.setCrosses(AxisCrosses.AUTO_ZERO);
assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO);
assertEquals(chart.getAxes().size(), 1);
wb.close();
assertEquals(chart.getAxes().size(), 1);
}
}
}

View File

@ -17,38 +17,40 @@
package org.apache.poi.xssf.usermodel.extensions;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle;
public class TestXSSFBorder extends TestCase {
public class TestXSSFBorder {
@Test
public void testGetBorderStyle() {
CTStylesheet stylesheet = CTStylesheet.Factory.newInstance();
CTBorder border = stylesheet.addNewBorders().addNewBorder();
CTBorderPr top = border.addNewTop();
CTBorderPr right = border.addNewRight();
CTBorderPr bottom = border.addNewBottom();
top.setStyle(STBorderStyle.DASH_DOT);
right.setStyle(STBorderStyle.NONE);
bottom.setStyle(STBorderStyle.THIN);
XSSFCellBorder cellBorderStyle = new XSSFCellBorder(border);
assertEquals("DASH_DOT", cellBorderStyle.getBorderStyle(BorderSide.TOP).toString());
assertEquals("NONE", cellBorderStyle.getBorderStyle(BorderSide.RIGHT).toString());
assertEquals(BorderStyle.NONE.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.RIGHT).ordinal());
assertEquals("THIN", cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).toString());
assertEquals(BorderStyle.THIN.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).ordinal());
}
}

View File

@ -1,26 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel.extensions;
import junit.framework.TestCase;
public class TestXSSFSheetComments extends TestCase {
// So eclipse doesn't moan
public void testTODO() {
}
}

View File

@ -17,27 +17,31 @@
package org.apache.poi.xssf.usermodel.helpers;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Test the header and footer helper.
* As we go through XmlBeans, should always use &,
* and not &amp;
*/
public class TestHeaderFooterHelper extends TestCase {
public class TestHeaderFooterHelper {
@Test
public void testGetCenterLeftRightSection() {
HeaderFooterHelper helper = new HeaderFooterHelper();
String headerFooter = "&CTest the center section";
assertEquals("Test the center section", helper.getCenterSection(headerFooter));
headerFooter = "&CTest the center section&LThe left one&RAnd the right one";
assertEquals("Test the center section", helper.getCenterSection(headerFooter));
assertEquals("The left one", helper.getLeftSection(headerFooter));
assertEquals("And the right one", helper.getRightSection(headerFooter));
}
@Test
public void testSetCenterLeftRightSection() {
HeaderFooterHelper helper = new HeaderFooterHelper();
String headerFooter = "";
@ -53,10 +57,10 @@ public class TestHeaderFooterHelper extends TestCase {
headerFooter = helper.setRightSection(headerFooter, "First right&F");
assertEquals("First right&F", helper.getRightSection(headerFooter));
assertEquals("&CFirst added center section&LFirst left&RFirst right&F", headerFooter);
headerFooter = helper.setRightSection(headerFooter, "First right&");
assertEquals("First right&", helper.getRightSection(headerFooter));
assertEquals("&CFirst added center section&LFirst left&RFirst right&", headerFooter);
}
}

View File

@ -27,21 +27,18 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
import junit.framework.TestCase;
/**
* Mixed utilities for testing memory usage in XSSF
*
* @author Yegor Kozlov
*/
@SuppressWarnings("InfiniteLoopStatement")
public class MemoryUsage extends TestCase {
public class MemoryUsage {
private static final int NUM_COLUMNS = 255;
private static void printMemoryUsage(String msg) {
@ -159,6 +156,7 @@ public class MemoryUsage extends TestCase {
*
* @see #testXmlAttached()
*/
@Test
public void testXmlDetached() {
System.out.println();
System.out.println("Testing detached");
@ -187,6 +185,7 @@ public class MemoryUsage extends TestCase {
*
* @see #testXmlAttached()
*/
@Test
public void testXmlAttached() {
System.out.println();
System.out.println("Testing attached");
@ -212,18 +211,22 @@ public class MemoryUsage extends TestCase {
printMemoryUsage("after");
}
@Test
public void testMixedHSSF() {
mixedSpreadsheet(new HSSFWorkbook(), NUM_COLUMNS);
}
@Test
public void testMixedXSSF() {
mixedSpreadsheet(new XSSFWorkbook(), NUM_COLUMNS);
}
@Test
public void testNumberHSSF() {
numberSpreadsheet(new HSSFWorkbook(), NUM_COLUMNS);
}
@Test
public void testNumberXSSF() {
numberSpreadsheet(new XSSFWorkbook(), NUM_COLUMNS);
}

View File

@ -17,15 +17,17 @@
package org.apache.poi.xssf.util;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
public final class TestCTColComparator extends TestCase {
public final class TestCTColComparator {
@Test
public void testCompare() {
CTCol o1 = CTCol.Factory.newInstance();
o1.setMin(1);
@ -43,6 +45,7 @@ public final class TestCTColComparator extends TestCase {
assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o3, o4));
}
@Test
public void testArraysSort() {
CTCol o1 = CTCol.Factory.newInstance();
o1.setMin(1);

View File

@ -17,11 +17,14 @@
package org.apache.poi.xssf.util;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestNumericRanges extends TestCase {
public class TestNumericRanges {
@Test
public void testGetOverlappingType() {
long[] r1 = {3, 8};
long[] r2 = {6, 11};
@ -35,7 +38,8 @@ public class TestNumericRanges extends TestCase {
assertEquals(NumericRanges.OVERLAPS_1_WRAPS, NumericRanges.getOverlappingType(r1, r5));
assertEquals(NumericRanges.NO_OVERLAPS, NumericRanges.getOverlappingType(r1, r6));
}
@Test
public void testGetOverlappingRange() {
long[] r1 = {3, 8};
long[] r2 = {6, 11};
@ -54,5 +58,5 @@ public class TestNumericRanges extends TestCase {
assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[0]);
assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[1]);
}
}

View File

@ -17,12 +17,14 @@
package org.apache.poi.xwpf;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.ooxml.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
/**
* Tests if the {@link CoreProperties#getKeywords()} method. This test has been
@ -33,10 +35,9 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
* The author of this has added {@link CoreProperties#getKeywords()} and
* {@link CoreProperties#setKeywords(String)} and this test is supposed to test
* them.
*
* @author Antoni Mylka
*/
public final class TestPackageCorePropertiesGetKeywords extends TestCase {
public final class TestPackageCorePropertiesGetKeywords {
@Test
public void testGetSetKeywords() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx")) {
String keywords = doc.getProperties().getCoreProperties().getKeywords();

View File

@ -17,31 +17,32 @@
package org.apache.poi.xwpf.extractor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
public class TestExternalEntities extends TestCase {
public class TestExternalEntities {
/**
* Get text out of the simple file
*
* @throws IOException
*/
@Test
public void testFile() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
String text = extractor.getText();
assertTrue(text.length() > 0);
assertTrue(text.length() > 0);
// Check contents, they should not contain the text from POI web site after colon!
assertEquals("Here should not be the POI web site: \"\"", text.trim());
extractor.close();
// Check contents, they should not contain the text from POI web site after colon!
assertEquals("Here should not be the POI web site: \"\"", text.trim());
}
}
}

View File

@ -17,32 +17,36 @@
package org.apache.poi.xwpf.extractor;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertEndsWith;
import static org.apache.poi.POITestCase.assertNotContained;
import static org.apache.poi.POITestCase.assertStartsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertEndsWith;
import static org.apache.poi.POITestCase.assertNotContained;
import static org.apache.poi.POITestCase.assertStartsWith;
import org.junit.Test;
/**
* Tests for HXFWordExtractor
*/
public class TestXWPFWordExtractor extends TestCase {
public class TestXWPFWordExtractor {
/**
* Get text out of the simple file
*/
@Test
public void testGetSimpleText() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertTrue(text.length() > 0);
@ -58,23 +62,21 @@ public class TestXWPFWordExtractor extends TestCase {
// Check number of paragraphs by counting number of newlines
int numberOfParagraphs = StringUtil.countMatches(text, '\n');
assertEquals(3, numberOfParagraphs);
extractor.close();
}
}
/**
* Tests getting the text out of a complex file
*/
@Test
public void testGetComplexText() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertTrue(text.length() > 0);
char euro = '\u20ac';
// System.err.println("'"+text.substring(text.length() - 40) + "'");
// Check contents
assertStartsWith(text,
@ -90,14 +92,13 @@ public class TestXWPFWordExtractor extends TestCase {
// Check number of paragraphs by counting number of newlines
int numberOfParagraphs = StringUtil.countMatches(text, '\n');
assertEquals(134, numberOfParagraphs);
extractor.close();
}
}
@Test
public void testGetWithHyperlinks() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
// Now check contents
extractor.setFetchHyperlinks(false);
@ -118,126 +119,117 @@ public class TestXWPFWordExtractor extends TestCase {
"We have a hyperlink <http://poi.apache.org/> here, and another.\n",
extractor.getText()
);
extractor.close();
}
}
@Test
public void testHeadersFooters() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertEquals(
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.getText()
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.getText()
);
}
// Now another file, expect multiple headers
// and multiple footers
XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
extractor.close();
// Now another file, expect multiple headers
// and multiple footers
try (XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx")) {
extractor = new XWPFWordExtractor(doc2);
extractor.close();
new XWPFWordExtractor(doc2).close();
extractor =
new XWPFWordExtractor(doc2);
extractor.getText();
try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc2)) {
extractor.getText();
assertEquals(
assertEquals(
"I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" +
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"The footer of the first page\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"The footer of the first page\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.getText()
);
);
extractor.close();
}
}
}
@Test
public void testFootnotes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertContains(text, "snoska");
assertContains(text, "Eto ochen prostoy[footnoteRef:1] text so snoskoy");
extractor.close();
}
}
@Test
public void testTableFootnotes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertContains(extractor.getText(), "snoska");
extractor.close();
}
}
@Test
public void testFormFootnotes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertContains(text, "testdoc");
assertContains(text, "test phrase");
extractor.close();
}
}
@Test
public void testEndnotes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertContains(text, "XXX");
assertContains(text, "tilaka [endnoteRef:2]or 'tika'");
extractor.close();
}
}
@Test
public void testInsertedDeletedText() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertContains(extractor.getText(), "pendant worn");
assertContains(extractor.getText(), "extremely well");
extractor.close();
}
}
@Test
public void testParagraphHeader() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertContains(extractor.getText(), "Section 1");
assertContains(extractor.getText(), "Section 2");
assertContains(extractor.getText(), "Section 3");
extractor.close();
}
}
@ -245,15 +237,14 @@ public class TestXWPFWordExtractor extends TestCase {
* Test that we can open and process .docm
* (macro enabled) docx files (bug #45690)
*/
@Test
public void testDOCMFiles() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertContains(extractor.getText(), "2004");
assertContains(extractor.getText(), "2008");
assertContains(extractor.getText(), "(120 ");
extractor.close();
}
}
@ -262,9 +253,10 @@ public class TestXWPFWordExtractor extends TestCase {
* carriage returns properly in the text that
* we're extracting (bug #49189)
*/
@Test
public void testDocTabs() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
// Check bits
assertContains(extractor.getText(), "a");
@ -273,8 +265,6 @@ public class TestXWPFWordExtractor extends TestCase {
// Now check the first paragraph in total
assertContains(extractor.getText(), "a\tb\n");
extractor.close();
}
}
@ -282,15 +272,14 @@ public class TestXWPFWordExtractor extends TestCase {
* The output should not contain field codes, e.g. those specified in the
* w:instrText tag (spec sec. 17.16.23)
*/
@Test
public void testNoFieldCodes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertTrue(text.length() > 0);
assertFalse(text.contains("AUTHOR"));
assertFalse(text.contains("CREATEDATE"));
extractor.close();
}
}
@ -298,14 +287,13 @@ public class TestXWPFWordExtractor extends TestCase {
* The output should contain the values of simple fields, those specified
* with the fldSimple element (spec sec. 17.16.19)
*/
@Test
public void testFldSimpleContent() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertTrue(text.length() > 0);
assertContains(text, "FldSimple.docx");
extractor.close();
}
}
@ -313,38 +301,38 @@ public class TestXWPFWordExtractor extends TestCase {
* Test for parsing document with drawings to prevent
* NoClassDefFoundError for CTAnchor in XWPFRun
*/
@Test
public void testDrawings() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String text = extractor.getText();
assertTrue(text.length() > 0);
extractor.close();
}
}
/**
* Test for basic extraction of SDT content
*/
@Test
public void testSimpleControlContent() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
XWPFWordExtractor ex = new XWPFWordExtractor(doc)) {
String[] targs = new String[]{
"header_rich_text",
"rich_text",
"rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table",
"plain_text_no_newlines",
"plain_text_with_newlines1\nplain_text_with_newlines2\n",
"watermelon\n",
"dirt\n",
"4/16/2013\n",
"rich_text_in_cell",
"abc",
"rich_text_in_paragraph_in_cell",
"footer_rich_text",
"footnote_sdt",
"endnote_sdt"
"header_rich_text",
"rich_text",
"rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table",
"plain_text_no_newlines",
"plain_text_with_newlines1\nplain_text_with_newlines2\n",
"watermelon\n",
"dirt\n",
"4/16/2013\n",
"rich_text_in_cell",
"abc",
"rich_text_in_paragraph_in_cell",
"footer_rich_text",
"footnote_sdt",
"endnote_sdt"
};
XWPFWordExtractor ex = new XWPFWordExtractor(doc);
String s = ex.getText().toLowerCase(Locale.ROOT);
int hits = 0;
@ -357,17 +345,17 @@ public class TestXWPFWordExtractor extends TestCase {
assertTrue("controlled content loading-" + targ, hit);
}
assertEquals("controlled content loading hit count", targs.length, hits);
ex.close();
}
try (XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
XWPFWordExtractor ex = new XWPFWordExtractor(doc2)) {
String s = ex.getText().toLowerCase(Locale.ROOT);
XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
targs = new String[]{
"bb",
"test subtitle\n",
"test user\n",
String[] targs = {
"bb",
"test subtitle\n",
"test user\n",
};
ex = new XWPFWordExtractor(doc2);
s = ex.getText().toLowerCase(Locale.ROOT);
//At one point in development there were three copies of the text.
//This ensures that there is only one copy.
@ -387,69 +375,71 @@ public class TestXWPFWordExtractor extends TestCase {
hit++;
}
assertEquals("test<N>", 2, hit);
ex.close();
}
}
/**
* No Header or Footer in document
*/
@Test
public void testBug55733() throws Exception {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
// Check it gives text without error
extractor.getText();
extractor.close();
}
}
@Test
public void testCheckboxes() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" +
"Or checked: |X|\n\n\n\n\n" +
"Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
"In Table:\n|_|\t|X|\n\n\n" +
"In Sequence:\n|X||_||X|\n", extractor.getText());
extractor.close();
}
}
public void testMultipleBodyBug() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("MultipleBodyBug.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
assertEquals("START BODY 1 The quick, brown fox jumps over a lazy dog. END BODY 1.\n"
+ "START BODY 2 The quick, brown fox jumps over a lazy dog. END BODY 2.\n"
+ "START BODY 3 The quick, brown fox jumps over a lazy dog. END BODY 3.\n",
extractor.getText());
extractor.close();
"Or checked: |X|\n\n\n\n\n" +
"Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
"In Table:\n|_|\t|X|\n\n\n" +
"In Sequence:\n|X||_||X|\n", extractor.getText());
}
}
@Test
public void testMultipleBodyBug() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("MultipleBodyBug.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
assertEquals("START BODY 1 The quick, brown fox jumps over a lazy dog. END BODY 1.\n"
+ "START BODY 2 The quick, brown fox jumps over a lazy dog. END BODY 2.\n"
+ "START BODY 3 The quick, brown fox jumps over a lazy dog. END BODY 3.\n",
extractor.getText());
}
}
@Test
public void testPhonetic() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61470.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
//expect: baseText (phoneticText)
assertEquals("\u6771\u4EAC (\u3068\u3046\u304D\u3087\u3046)", extractor.getText().trim());
extractor.close();
extractor = new XWPFWordExtractor(doc);
extractor.setConcatenatePhoneticRuns(false);
assertEquals("\u6771\u4EAC", extractor.getText().trim());
try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
//expect: baseText (phoneticText)
assertEquals("\u6771\u4EAC (\u3068\u3046\u304D\u3087\u3046)", extractor.getText().trim());
}
try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
extractor.setConcatenatePhoneticRuns(false);
assertEquals("\u6771\u4EAC", extractor.getText().trim());
}
}
}
@Test
public void testCTPictureBase() throws IOException {
//This forces ctpicturebase to be included in the poi-ooxml-schemas jar
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61991.docx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61991.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
String txt = extractor.getText();
assertContains(txt, "Sequencing data");
extractor.close();
}
}
@Test
public void testGlossary() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316.dotx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
@ -461,6 +451,7 @@ public class TestXWPFWordExtractor extends TestCase {
}
}
@Test
public void testPartsInTemplate() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316b.dotx")) {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);

View File

@ -17,45 +17,46 @@
package org.apache.poi.xwpf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.math.BigInteger;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.junit.Test;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn;
import junit.framework.TestCase;
public class TestXWPFEndnotes {
public class TestXWPFEndnotes extends TestCase {
@Test
public void testCreateEndnotes() throws IOException{
XWPFDocument docOut = new XWPFDocument();
try (XWPFDocument docOut = new XWPFDocument()) {
XWPFEndnotes footnotes = docOut.createEndnotes();
assertNotNull(footnotes);
XWPFEndnotes footnotes = docOut.createEndnotes();
assertNotNull(footnotes);
XWPFEndnotes secondFootnotes = docOut.createEndnotes();
assertSame(footnotes, secondFootnotes);
docOut.close();
XWPFEndnotes secondFootnotes = docOut.createEndnotes();
assertSame(footnotes, secondFootnotes);
}
}
@Test
public void testAddEndnotesToDocument() throws IOException {
XWPFDocument docOut = new XWPFDocument();
try (XWPFDocument docOut = new XWPFDocument()) {
// NOTE: XWPFDocument.createEndnote() delegates directly
// to XWPFFootnotes.createEndnote() so this tests
// both creation of new XWPFFootnotes in document
// and XWPFFootnotes.createEndnote();
XWPFEndnote endnote = docOut.createEndnote();
BigInteger noteId = endnote.getId();
// NOTE: XWPFDocument.createEndnote() delegates directly
// to XWPFFootnotes.createEndnote() so this tests
// both creation of new XWPFFootnotes in document
// and XWPFFootnotes.createEndnote();
XWPFEndnote endnote = docOut.createEndnote();
BigInteger noteId = endnote.getId();
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
XWPFEndnote note = docIn.getEndnoteByID(noteId.intValue());
assertNotNull(note);
assertEquals(STFtnEdn.NORMAL, note.getCTFtnEdn().getType());
XWPFEndnote note = docIn.getEndnoteByID(noteId.intValue());
assertNotNull(note);
assertEquals(STFtnEdn.NORMAL, note.getCTFtnEdn().getType());
}
}
}

View File

@ -17,16 +17,21 @@
package org.apache.poi.xwpf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.math.BigInteger;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.junit.Test;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;
public class TestXWPFNumbering extends TestCase {
public class TestXWPFNumbering {
@Test
public void testCompareAbstractNum() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) {
XWPFNumbering numbering = doc.getNumbering();
@ -40,6 +45,7 @@ public class TestXWPFNumbering extends TestCase {
}
}
@Test
public void testAddNumberingToDoc() throws IOException {
BigInteger abstractNumId = BigInteger.valueOf(1);
BigInteger numId = BigInteger.valueOf(1);
@ -58,6 +64,7 @@ public class TestXWPFNumbering extends TestCase {
assertEquals(abstractNumId, compareAbstractNum);
}
@Test
public void testGetNumIlvl() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) {
BigInteger numIlvl = BigInteger.valueOf(0);
@ -67,6 +74,7 @@ public class TestXWPFNumbering extends TestCase {
}
}
@Test
public void testGetNumFmt() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) {
assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt());
@ -79,6 +87,7 @@ public class TestXWPFNumbering extends TestCase {
}
}
@Test
public void testLvlText() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) {
@ -93,6 +102,7 @@ public class TestXWPFNumbering extends TestCase {
}
}
@Test
public void testOverrideList() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx")) {
XWPFParagraph p = doc.getParagraphs().get(4);

View File

@ -18,21 +18,26 @@
package org.apache.poi.xwpf.usermodel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.junit.Assert;
import org.junit.Test;
public class TestXWPFPictureData extends TestCase {
public class TestXWPFPictureData {
@Test
public void testRead() throws InvalidFormatException, IOException {
try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx")) {
List<XWPFPictureData> pictures = sampleDoc.getAllPictures();
@ -57,6 +62,7 @@ public class TestXWPFPictureData extends TestCase {
}
}
@Test
public void testPictureInHeader() throws IOException {
try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx")) {
verifyOneHeaderPicture(sampleDoc);
@ -65,7 +71,8 @@ public class TestXWPFPictureData extends TestCase {
verifyOneHeaderPicture(readBack);
}
}
@Test
public void testCreateHeaderPicture() throws Exception {
try (XWPFDocument doc = new XWPFDocument()) {
@ -104,6 +111,7 @@ public class TestXWPFPictureData extends TestCase {
assertEquals(1, pictures.size());
}
@Test
public void testNew() throws InvalidFormatException, IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx")) {
byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
@ -165,22 +173,19 @@ public class TestXWPFPictureData extends TestCase {
}
}
@Test
public void testBug51770() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx")) {
XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
XWPFHeader header = policy.getDefaultHeader();
for (XWPFParagraph paragraph : header.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
for (XWPFPicture picture : run.getEmbeddedPictures()) {
if (paragraph.getDocument() != null) {
XWPFPictureData data = picture.getPictureData();
if (data != null) {
fail("Should have returned null: " + data.getFileName());
}
}
}
}
}
header.getParagraphs().stream()
.map(XWPFParagraph::getRuns)
.flatMap(List::stream)
.map(XWPFRun::getEmbeddedPictures)
.flatMap(List::stream)
.map(XWPFPicture::getPictureData)
.forEach(Assert::assertNull);
}
}
}

View File

@ -16,19 +16,18 @@
==================================================================== */
package org.apache.poi.xwpf.usermodel;
import static org.apache.poi.POITestCase.assertContains;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import static org.apache.poi.POITestCase.assertContains;
import org.junit.Test;
/**
* Tests for reading SmartTags from Word docx.
*
* @author Fabian Lange
*/
public final class TestXWPFSmartTag extends TestCase {
public final class TestXWPFSmartTag {
@Test
public void testSmartTags() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("smarttag-snippet.docx")) {
XWPFParagraph p = doc.getParagraphArray(0);

View File

@ -17,36 +17,41 @@
package org.apache.poi.hdgf;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hdgf.extractor.VisioTextExtractor;
import org.apache.poi.hdgf.streams.PointerContainingStream;
import org.apache.poi.hdgf.streams.TrailerStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public final class TestHDGFCore extends TestCase {
public final class TestHDGFCore {
private static POIDataSamples _dgTests = POIDataSamples.getDiagramInstance();
private POIFSFileSystem fs;
private HDGFDiagram hdgf;
private VisioTextExtractor textExtractor;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd"));
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
if (textExtractor != null) textExtractor.close();
if (hdgf != null) hdgf.close();
}
@Test
public void testCreate() throws Exception {
hdgf = new HDGFDiagram(fs);
}
@Test
public void testTrailer() throws Exception {
hdgf = new HDGFDiagram(fs);
assertNotNull(hdgf);
@ -74,6 +79,7 @@ public final class TestHDGFCore extends TestCase {
* Tests that we can open a problematic file, that used to
* break with a negative chunk length
*/
@Test
public void testNegativeChunkLength() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("NegativeChunkLength.vsd"));
@ -90,8 +96,8 @@ public final class TestHDGFCore extends TestCase {
* Tests that we can open a problematic file that triggers
* an ArrayIndexOutOfBoundsException when processing the
* chunk commands.
* @throws Exception
*/
@Test
public void DISABLEDtestAIOOB() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("44501.vsd"));
@ -99,6 +105,7 @@ public final class TestHDGFCore extends TestCase {
assertNotNull(hdgf);
}
@Test
public void testV5() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("v5_Connection_Types.vsd"));
@ -111,6 +118,7 @@ public final class TestHDGFCore extends TestCase {
assertEquals("Static to Static\nDynamic to Static\nDynamic to Dynamic", text);
}
@Test
public void testV6NonUtf16LE() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("v6-non-utf16le.vsd"));
@ -123,6 +131,7 @@ public final class TestHDGFCore extends TestCase {
assertEquals("Table\n\n\nPropertySheet\n\n\n\nPropertySheetField", text);
}
@Test
public void testUtf16LE() throws Exception {
fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd"));

View File

@ -17,12 +17,15 @@
package org.apache.poi.hdgf;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
import org.junit.Ignore;
import org.junit.Test;
public final class TestHDGFLZW extends TestCase {
public static final byte[] testTrailerComp = new byte[] {
public final class TestHDGFLZW {
public static final byte[] testTrailerComp = {
123, // *mask bit*
-60, 2,
-21, -16, // 3 @ 4093
@ -38,7 +41,7 @@ public final class TestHDGFLZW extends TestCase {
21, // *mask bit* 1,3,5
9,
-21, -16, // 3 @ 4093
103,
103,
-21, -16, // 3 @ 4093
34,
-36, -1, // 18 @ 4078
@ -72,7 +75,7 @@ public final class TestHDGFLZW extends TestCase {
1, 67, 85, 1, 81, -127, 0, -41, 0, 14, 6, 4, 17, 63, -63, 17, 68,
85, -65, 1, 30, -120, 0, 0, 42, 79, 18, 68, 126, -21, -16, -76, 69,
85, 1, 102, -119, 72, 37, 0, 97, 33 };
public static final byte[] testTrailerDecomp = new byte[] {
public static final byte[] testTrailerDecomp = {
-60, 2, 0, 0, 0, 1, 0, 0, -72, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0,
0, 9, 0, 0, 0, 103, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@ -108,6 +111,7 @@ public final class TestHDGFLZW extends TestCase {
0, 0, 42, 1, 0, 0, 84, 0, 0, 0, 0, 0
};
@Test
public void testFromToInt() {
byte b255 = -1;
assertEquals(255, HDGFLZW.fromByte(b255));
@ -135,6 +139,7 @@ public final class TestHDGFLZW extends TestCase {
assertEquals(-128, HDGFLZW.fromInt( 128 ));
}
@Test
public void testCounts() throws Exception {
assertEquals(339, testTrailerComp.length);
assertEquals(632, testTrailerDecomp.length);
@ -155,6 +160,7 @@ public final class TestHDGFLZW extends TestCase {
*/
}
@Test
public void testDecompress() throws Exception {
assertEquals(339, testTrailerComp.length);
assertEquals(632, testTrailerDecomp.length);
@ -176,6 +182,7 @@ public final class TestHDGFLZW extends TestCase {
* Uses a part short enough that we agree with visio
* on the best way to compress it
*/
@Test
public void testCompressMini() throws Exception {
// first 11 bytes compressed = 12 bytes uncompressed
byte[] sourceComp = new byte[11];
@ -186,7 +193,7 @@ public final class TestHDGFLZW extends TestCase {
// Compress it using our engine
HDGFLZW lzw = new HDGFLZW();
byte[] comp = lzw.compress(new ByteArrayInputStream(sourceDecomp));
// Now decompress it again
byte[] decomp = lzw.decompress(new ByteArrayInputStream(comp));
@ -206,6 +213,7 @@ public final class TestHDGFLZW extends TestCase {
/**
* Tests that we can do several mask pages
*/
@Test
public void testCompressMidi() throws Exception {
// First 12 -> 11
// Next 32 -> 13
@ -217,11 +225,11 @@ public final class TestHDGFLZW extends TestCase {
// Compress it using our engine
HDGFLZW lzw = new HDGFLZW();
byte[] comp = lzw.compress(new ByteArrayInputStream(sourceDecomp));
// We should be 3 characters bigger, as
// we split one compressed bit into two
assertEquals(27, comp.length);
// Now decompress it again
byte[] decomp = lzw.decompress(new ByteArrayInputStream(comp));
@ -237,28 +245,30 @@ public final class TestHDGFLZW extends TestCase {
* Gets 160 bytes through then starts going wrong...
* TODO Fix this
*/
public void DISABLEDtestCompressFull() throws Exception {
@Test
@Ignore
public void testCompressFull() throws Exception {
assertEquals(339, testTrailerComp.length);
assertEquals(632, testTrailerDecomp.length);
// Compress it using our engine
HDGFLZW lzw = new HDGFLZW();
byte[] comp = lzw.compress(new ByteArrayInputStream(testTrailerDecomp));
// Now decompress it again
byte[] decomp = lzw.decompress(new ByteArrayInputStream(comp));
// for(int i=0; i<comp.length; i++) {
// System.err.println(i + "\t" + comp[i] + "\t" + testTrailerComp[i]);
// }
// First up, check the round tripping
// assertEquals(632, decomp.length);
for(int i=0; i<decomp.length; i++) {
assertEquals("Wrong at " + i, decomp[i], testTrailerDecomp[i]);
}
// Now check the compressed intermediate version
assertEquals(339, comp.length);
for(int i=0; i<comp.length; i++) {

View File

@ -17,48 +17,49 @@
package org.apache.poi.hdgf.pointers;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Tests for the pointer factory, and the pointers themselves
*/
public final class TestPointerFactory extends TestCase {
public final class TestPointerFactory {
// Type: 14 Addr: 011eb2ac Offset: 1dd4 Len: 14d Format: 52 From: 24
private static byte[] vp5_a = new byte[] {
private static byte[] vp5_a = {
0x14, 0, 0x52, 0, (byte)0xac, (byte)0xb2, 0x1e, 1, (byte)0xd4, 0x1d, 0, 0,
0x4d, 1, 0, 0
};
// Type: 16 Addr: 0143aff4 Offset: 80 Len: 54 Format: 46 From: 8a94
private static byte[] vp6_a = new byte[] {
private static byte[] vp6_a = {
22, 0, 0, 0, -12, -81, 67, 1, -128, 0, 0, 0, 84, 0, 0, 0, 70, 0
};
// Type: 17 Addr: 014fd84c Offset: d4 Len: 20 Format: 54 From: 8a94
private static byte[] vp6_b = new byte[] {
private static byte[] vp6_b = {
23, 0, 0, 0, 76, -40, 79, 1, -44, 0, 0, 0, 32, 0, 0, 0, 84, 0
};
// Type: 17 Addr: 014fd8bc Offset: f8 Len: 20 Format: 54 From: 8a94
private static byte[] vp6_c = new byte[] {
private static byte[] vp6_c = {
23, 0, 0, 0, -68, -40, 79, 1, -8, 0, 0, 0, 32, 0, 0, 0, 84, 0
};
// Type: ff Addr: 014fffac Offset: 0 Len: 0 Format: 60 From: 8a94
private static byte[] vp6_d = new byte[] {
private static byte[] vp6_d = {
-1, 0, 0, 0, -84, -1, 79, 1, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0
};
@Test(expected = IllegalArgumentException.class)
public void testCreateV4() {
PointerFactory pf = new PointerFactory(4);
try {
pf.createPointer(new byte[]{}, 0);
fail();
} catch(IllegalArgumentException e) {
// As expected
}
pf.createPointer(new byte[]{}, 0);
}
@Test
public void testCreateV5() {
PointerFactory pf = new PointerFactory(5);
Pointer a = pf.createPointer(vp5_a, 0);
assertEquals(0x14, a.getType());
assertEquals(0x011eb2ac, a.getAddress());
@ -75,6 +76,7 @@ public final class TestPointerFactory extends TestCase {
assertEquals(16, a.getSizeInBytes());
}
@Test
public void testCreateV6() {
PointerFactory pf = new PointerFactory(6);
@ -131,6 +133,7 @@ public final class TestPointerFactory extends TestCase {
assertFalse(d.destinationHasPointers());
}
@Test
public void testCreateV6FromMid() {
PointerFactory pf = new PointerFactory(11);

View File

@ -18,27 +18,33 @@
package org.apache.poi.hslf;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.apache.poi.hslf.record.*;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.record.Notes;
import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.Slide;
import org.apache.poi.hslf.record.SlideListWithText;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that HSLFSlideShow returns the right numbers of key records when
* it parses the test file
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestRecordCounts extends TestCase {
// HSLFSlideShow primed on the test data
private final HSLFSlideShowImpl ss;
public final class TestRecordCounts {
public TestRecordCounts() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
// HSLFSlideShow primed on the test data
private HSLFSlideShowImpl ss;
@Before
public void setup() throws Exception {
ss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
}
@Test
public void testSheetsCount() {
// Top level
Record[] r = ss.getRecords();
@ -53,13 +59,14 @@ public final class TestRecordCounts extends TestCase {
assertEquals(3,count);
}
@Test
public void testNotesCount() {
// Top level
Record[] r = ss.getRecords();
int count = 0;
for (final Record rec : r) {
if (rec instanceof Notes && rec.getRecordType() == 1008l) {
if (rec instanceof Notes && rec.getRecordType() == 1008L) {
count++;
}
}
@ -67,6 +74,7 @@ public final class TestRecordCounts extends TestCase {
assertEquals(3,count);
}
@Test
public void testSlideListWithTextCount() {
// Second level
Record[] rt = ss.getRecords();
@ -74,7 +82,7 @@ public final class TestRecordCounts extends TestCase {
int count = 0;
for (final Record rec : r) {
if (rec instanceof SlideListWithText && rec.getRecordType() == 4080l) {
if (rec instanceof SlideListWithText && rec.getRecordType() == 4080L) {
count++;
}
}

View File

@ -18,21 +18,24 @@
package org.apache.poi.hslf.extractor;
import java.util.List;
import static org.junit.Assert.assertEquals;
import junit.framework.TestCase;
import java.util.List;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.StringUtil;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that the QuickButCruddyTextExtractor works correctly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestCruddyExtractor extends TestCase {
public final class TestCruddyExtractor {
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
// Extractor primed on the test data
private final QuickButCruddyTextExtractor te;
private QuickButCruddyTextExtractor te;
// All the text to be found in the file
String[] allTheText = new String[] {
"This is a test title",
@ -59,11 +62,12 @@ public final class TestCruddyExtractor extends TestCase {
"This is page two\nIt has several blocks of text\nNone of them have formatting",
};
public TestCruddyExtractor() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
@Before
public void setup() throws Exception {
te = new QuickButCruddyTextExtractor(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
}
@Test
public void testReadAsVector() {
// Extract the text from the file as a vector
List<String> foundTextV = te.getTextAsVector();
@ -76,6 +80,7 @@ public final class TestCruddyExtractor extends TestCase {
}
}
@Test
public void testReadAsString() {
// Extract the text as a String
String foundText = te.getTextAsString();

View File

@ -19,17 +19,18 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link HeadersFootersAtom} works properly
*
* @author Yegor Kozlov
*/
public final class TestAnimationInfoAtom extends TestCase {
public final class TestAnimationInfoAtom {
// From a real file
/*
<AnimationInfoAtom info="1" type="4081" size="28" offset="4015" header="01 00 F1 0F 1C 00 00 00 ">
@ -37,12 +38,13 @@ public final class TestAnimationInfoAtom extends TestCase {
00 00 00
</AnimationInfoAtom>
*/
private final byte[] data = new byte[] {
private final byte[] data = {
0x01, 0x00, (byte)0xF1, 0x0F, 0x1C, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x07, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@Test
public void testRead() {
AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length);
assertEquals(RecordTypes.AnimationInfoAtom.typeID, record.getRecordType());
@ -61,6 +63,7 @@ public final class TestAnimationInfoAtom extends TestCase {
assertEquals(0, record.getSlideCount());
}
@Test
public void testWrite() throws Exception {
AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -70,6 +73,7 @@ public final class TestAnimationInfoAtom extends TestCase {
assertArrayEquals(data, b);
}
@Test
public void testNewRecord() throws Exception {
AnimationInfoAtom record = new AnimationInfoAtom();
record.setDimColor(0x07000000);

View File

@ -18,29 +18,34 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that CString works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestCString extends TestCase {
public final class TestCString {
// From a real file
private final byte[] data_a = new byte[] { 0, 0, 0xBA-256, 0x0f, 0x10, 0, 0, 0,
0x48, 00, 0x6F, 00, 0x67, 00, 0x77, 00,
0x61, 00, 0x72, 00, 0x74, 00, 0x73, 00 };
private final byte[] data_a = { 0, 0, 0xBA-256, 0x0f, 0x10, 0, 0, 0,
0x48, 0, 0x6F, 0, 0x67, 0, 0x77, 0,
0x61, 0, 0x72, 0, 0x74, 0, 0x73, 0 };
private final byte[] data_b = new byte[] { 0x10, 0, 0xBA-256, 0x0f, 0x10, 0, 0, 0,
0x43, 00, 0x6F, 00, 0x6D, 00, 0x6D, 00,
0x65, 00, 0x6E, 00, 0x74, 00, 0x73, 00 };
0x43, 0, 0x6F, 0, 0x6D, 0, 0x6D, 0,
0x65, 0, 0x6E, 0, 0x74, 0, 0x73, 0 };
@Test
public void testRecordType() {
CString ca = new CString(data_a, 0, data_a.length);
assertEquals(4026l, ca.getRecordType());
assertEquals(4026L, ca.getRecordType());
CString cb = new CString(data_b, 0, data_a.length);
assertEquals(4026l, cb.getRecordType());
assertEquals(4026L, cb.getRecordType());
}
@Test
public void testCount() {
CString ca = new CString(data_a, 0, data_a.length);
assertEquals(0, ca.getOptions());
@ -51,6 +56,7 @@ public final class TestCString extends TestCase {
assertEquals(28, ca.getOptions());
}
@Test
public void testText() {
CString ca = new CString(data_a, 0, data_a.length);
assertEquals("Hogwarts", ca.getText());
@ -61,6 +67,7 @@ public final class TestCString extends TestCase {
assertEquals("FooBar", ca.getText());
}
@Test
public void testWrite() throws Exception {
CString ca = new CString(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -84,6 +91,7 @@ public final class TestCString extends TestCase {
}
// Turn data_a into data_b
@Test
public void testChange() throws Exception {
CString ca = new CString(data_a, 0, data_a.length);
ca.setText("Comments");

View File

@ -18,28 +18,31 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that ColorSchemAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestColorSchemeAtom extends TestCase {
public final class TestColorSchemeAtom {
// From a real file
private final byte[] data_a = new byte[] { 60, 0, 0xF0-256, 0x07, 0x20, 0, 0, 0,
0xFF-256, 0xFF-256, 0xFF-256, 00, 00, 00, 00, 00,
0x80-256, 0x80-256, 0x80-256, 00, 00, 00, 00, 00,
0xBB-256, 0xE0-256, 0xE3-256, 00, 0x33, 0x33, 0x99-256, 00,
00, 0x99-256, 0x99-256, 00, 0x99-256, 0xCC-256, 00, 00
private final byte[] data_a = { 60, 0, 0xF0-256, 0x07, 0x20, 0, 0, 0,
0xFF-256, 0xFF-256, 0xFF-256, 0, 0, 0, 0, 0,
0x80-256, 0x80-256, 0x80-256, 0, 0, 0, 0, 0,
0xBB-256, 0xE0-256, 0xE3-256, 0, 0x33, 0x33, 0x99-256, 0,
0, 0x99-256, 0x99-256, 0, 0x99-256, 0xCC-256, 0, 0
};
@Test
public void testRecordType() {
ColorSchemeAtom csa = new ColorSchemeAtom(data_a,0,data_a.length);
assertEquals(2032l, csa.getRecordType());
assertEquals(2032L, csa.getRecordType());
}
@Test
public void testToRGB() {
byte[] rgb = ColorSchemeAtom.splitRGB(3669760);
@ -49,6 +52,7 @@ public final class TestColorSchemeAtom extends TestCase {
assertEquals(55, rgb[2]);
}
@Test
public void testFromRGB() {
byte[] rgb_a = new byte[] { 0, 255-256, 55 };
byte[] rgb_b = new byte[] { 255-256, 127, 79 };
@ -60,6 +64,7 @@ public final class TestColorSchemeAtom extends TestCase {
assertEquals( 5210111, ColorSchemeAtom.joinRGB( rgb_b[0], rgb_b[1], rgb_b[2] ) );
}
@Test
public void testRGBs() {
ColorSchemeAtom csa = new ColorSchemeAtom(data_a,0,data_a.length);
@ -73,6 +78,7 @@ public final class TestColorSchemeAtom extends TestCase {
assertEquals( 52377 , csa.getAccentAndFollowingHyperlinkColourRGB() );
}
@Test
public void testWrite() throws Exception {
ColorSchemeAtom csa = new ColorSchemeAtom(data_a,0,data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

View File

@ -17,25 +17,28 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that Document works properly (Also tests Environment while we're at it)
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestDocument extends TestCase {
// HSLFSlideShow primed on the test data
private final HSLFSlideShowImpl ss;
// POIFS primed on the test data
private final POIFSFileSystem pfs;
public final class TestDocument {
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
public TestDocument() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
// HSLFSlideShow primed on the test data
private HSLFSlideShowImpl ss;
// POIFS primed on the test data
private POIFSFileSystem pfs;
@Before
public void setup() throws Exception {
pfs = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
ss = new HSLFSlideShowImpl(pfs);
}
@ -50,11 +53,13 @@ public final class TestDocument extends TestCase {
throw new IllegalStateException("No Document record found");
}
@Test
public void testRecordType() {
Document dr = getDocRecord();
assertEquals(1000, dr.getRecordType());
}
@Test
public void testChildRecords() {
Document dr = getDocRecord();
assertNotNull(dr.getDocumentAtom());
@ -68,6 +73,7 @@ public final class TestDocument extends TestCase {
assertNotNull(dr.getSlideListWithTexts()[2]);
}
@Test
public void testEnvironment() {
Document dr = getDocRecord();
Environment env = dr.getEnvironment();

View File

@ -18,46 +18,59 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that DocumentAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestDocumentAtom extends TestCase {
public final class TestDocumentAtom {
// From a real file
private final byte[] data_a = new byte[] { 1, 0, 0xE9-256, 3, 0x28, 0, 0, 0,
private final byte[] data_a = { 1, 0, 0xE9-256, 3, 0x28, 0, 0, 0,
0x80-256, 0x16, 0, 0, 0xE0-256, 0x10, 0, 0,
0xE0-256, 0x10, 0, 0, 0x80-256, 0x16, 0, 0,
0x05, 0, 0, 0, 0x0A, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 1 };
@Test
public void testRecordType() {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
assertEquals(1001l, da.getRecordType());
}
@Test
public void testSizeAndZoom() {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
assertEquals(5760l, da.getSlideSizeX());
assertEquals(4320l, da.getSlideSizeY());
assertEquals(4320l, da.getNotesSizeX());
assertEquals(5760l, da.getNotesSizeY());
assertEquals(5760L, da.getSlideSizeX());
assertEquals(4320L, da.getSlideSizeY());
assertEquals(4320L, da.getNotesSizeX());
assertEquals(5760L, da.getNotesSizeY());
assertEquals(5l, da.getServerZoomFrom());
assertEquals(10l, da.getServerZoomTo());
assertEquals(5L, da.getServerZoomFrom());
assertEquals(10L, da.getServerZoomTo());
}
@Test
public void testMasterPersist() {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
assertEquals(2l, da.getNotesMasterPersist());
assertEquals(0l, da.getHandoutMasterPersist());
assertEquals(2L, da.getNotesMasterPersist());
assertEquals(0L, da.getHandoutMasterPersist());
}
@Test
public void testSlideDetails() {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
assertEquals(1, da.getFirstSlideNum());
assertEquals(0, da.getSlideSizeType());
}
@Test
public void testBooleans() {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
assertFalse(da.getSaveWithFonts());
@ -66,15 +79,11 @@ public final class TestDocumentAtom extends TestCase {
assertTrue(da.getShowComments());
}
@Test
public void testWrite() throws Exception {
DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
da.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
}

View File

@ -19,17 +19,17 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link org.apache.poi.hslf.record.ExControl} works properly
*
* @author Yegor Kozlov
*/
public final class TestExControl extends TestCase {
public final class TestExControl {
// From a real file (embedded SWF control)
/*
@ -55,7 +55,7 @@ public final class TestExControl extends TestCase {
</CString>
</ExControl>
*/
private final byte[] data = new byte[] {
private final byte[] data = {
0x0F, 0x00, (byte)0xEE, 0x0F, (byte)0xDA, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xFB, 0x0F, 0x04, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x01, 0x00, (byte)0xC3, 0x0F, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, (byte)0x96, 0x13, 0x00,
@ -71,6 +71,7 @@ public final class TestExControl extends TestCase {
0x65, 0x00, 0x63, 0x00, 0x74, 0x00
};
@Test
public void testRead() {
ExControl record = new ExControl(data, 0, data.length);
assertEquals(RecordTypes.ExControl.typeID, record.getRecordType());
@ -89,15 +90,15 @@ public final class TestExControl extends TestCase {
assertEquals("Shockwave Flash Object", record.getClipboardName());
}
@Test
public void testWrite() throws Exception {
ExControl record = new ExControl(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testNewRecord() throws Exception {
ExControl record = new ExControl();
ExControlAtom ctrl = record.getExControlAtom();
@ -117,9 +118,6 @@ public final class TestExControl extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data.length, b.length);
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
}

View File

@ -18,30 +18,34 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that ExHyperlinkAtom works properly.
*
* @author Nick Burch (nick at torchbox dot com)
*/
public class TestExHyperlinkAtom extends TestCase {
public class TestExHyperlinkAtom {
// From a real file
private final byte[] data_a = new byte[] {
00, 00, 0xD3-256, 0x0F, 04, 00, 00, 00,
01, 00, 00, 00
0, 0, 0xD3-256, 0x0F, 4, 0, 0, 0,
1, 0, 0, 0
};
private final byte[] data_b = new byte[] {
00, 00, 0xD3-256, 0x0F, 04, 00, 00, 00,
04, 00, 00, 00
0, 0, 0xD3-256, 0x0F, 4, 0, 0, 0,
4, 0, 0, 0
};
@Test
public void testRecordType() {
ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length);
assertEquals(4051l, eha.getRecordType());
assertEquals(4051L, eha.getRecordType());
}
@Test
public void testGetNumber() {
ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length);
ExHyperlinkAtom ehb = new ExHyperlinkAtom(data_b, 0, data_b.length);
@ -50,19 +54,16 @@ public class TestExHyperlinkAtom extends TestCase {
assertEquals(4, ehb.getNumber());
}
@Test
public void testWrite() throws Exception {
ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eha.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Create A from scratch
@Test
public void testCreate() throws Exception {
ExHyperlinkAtom eha = new ExHyperlinkAtom();
@ -72,15 +73,11 @@ public class TestExHyperlinkAtom extends TestCase {
// Check it's now the same as a
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eha.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Try to turn a into b
@Test
public void testChange() throws Exception {
ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length);
@ -90,12 +87,6 @@ public class TestExHyperlinkAtom extends TestCase {
// Check bytes are now the same
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eha.writeOut(baos);
byte[] b = baos.toByteArray();
// Should now be the same
assertEquals(data_b.length, b.length);
for(int i=0; i<data_b.length; i++) {
assertEquals(data_b[i],b[i]);
}
assertArrayEquals(data_b, baos.toByteArray());
}
}

View File

@ -19,22 +19,24 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link org.apache.poi.hslf.record.HeadersFootersAtom} works properly
*
* @author Yegor Kozlov
*/
public final class TestExMediaAtom extends TestCase {
public final class TestExMediaAtom {
// From a real file
private static final byte[] data = {
0x00, 0x00, (byte)0x04, 0x10, 0x08, 0x00, 0x00, 00,
0x00, 0x00, (byte)0x04, 0x10, 0x08, 0x00, 0x00, 0,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
@Test
public void testRead() {
ExMediaAtom record = new ExMediaAtom(data, 0, data.length);
assertEquals(RecordTypes.ExMediaAtom.typeID, record.getRecordType());
@ -45,6 +47,7 @@ public final class TestExMediaAtom extends TestCase {
assertFalse(record.getFlag(ExMediaAtom.fRewind));
}
@Test
public void testWrite() throws Exception {
ExMediaAtom record = new ExMediaAtom(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -54,6 +57,7 @@ public final class TestExMediaAtom extends TestCase {
assertArrayEquals(data, b);
}
@Test
public void testNewRecord() throws Exception {
ExMediaAtom ref = new ExMediaAtom(data, 0, data.length);
assertEquals(0, ref.getMask()); //
@ -71,6 +75,7 @@ public final class TestExMediaAtom extends TestCase {
assertArrayEquals(data, b);
}
@Test
public void testFlags() {
ExMediaAtom record = new ExMediaAtom();

View File

@ -18,30 +18,34 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.apache.poi.ss.formula.functions.AbstractNumericTestCase.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that ExObjListAtom works properly.
*
* @author Nick Burch (nick at torchbox dot com)
*/
public class TestExObjListAtom extends TestCase {
public class TestExObjListAtom {
// From a real file
private final byte[] data_a = new byte[] {
00, 00, 0x0A, 0x04, 04, 00, 00, 00,
01, 00, 00, 00
0, 0, 0x0A, 0x04, 4, 0, 0, 0,
1, 0, 0, 0
};
private final byte[] data_b = new byte[] {
00, 00, 0x0A, 0x04, 04, 00, 00, 00,
04, 00, 00, 00
0, 0, 0x0A, 0x04, 4, 0, 0, 0,
4, 0, 0, 0
};
@Test
public void testRecordType() {
ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length);
assertEquals(1034l, eoa.getRecordType());
assertEquals(1034L, eoa.getRecordType());
}
@Test
public void testGetSeed() {
ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length);
ExObjListAtom eob = new ExObjListAtom(data_b, 0, data_b.length);
@ -50,19 +54,16 @@ public class TestExObjListAtom extends TestCase {
assertEquals(4, eob.getObjectIDSeed());
}
@Test
public void testWrite() throws Exception {
ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eoa.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Create A from scratch
@Test
public void testCreate() throws Exception {
ExObjListAtom eoa = new ExObjListAtom();
@ -72,15 +73,11 @@ public class TestExObjListAtom extends TestCase {
// Check it's now the same as a
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eoa.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Try to turn a into b
@Test
public void testChange() throws Exception {
ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length);
@ -90,12 +87,6 @@ public class TestExObjListAtom extends TestCase {
// Check bytes are now the same
ByteArrayOutputStream baos = new ByteArrayOutputStream();
eoa.writeOut(baos);
byte[] b = baos.toByteArray();
// Should now be the same
assertEquals(data_b.length, b.length);
for(int i=0; i<data_b.length; i++) {
assertEquals(data_b[i],b[i]);
}
assertArrayEquals(data_b, baos.toByteArray());
}
}

View File

@ -18,23 +18,23 @@
package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link ExOleObjAtom} works properly
*
* @author Yegor Kozlov
*/
public final class TestExOleObjAtom extends TestCase {
public final class TestExOleObjAtom {
// From a real file (embedded SWF control)
private final byte[] data = {
0x01, 0x00, (byte)0xC3, 0x0F, 0x18, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, (byte)0x96, 0x13, 0x00 };
@Test
public void testRead() {
ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length);
assertEquals(RecordTypes.ExOleObjAtom.typeID, record.getRecordType());
@ -47,15 +47,15 @@ public final class TestExOleObjAtom extends TestCase {
assertEquals(record.getOptions(), 1283584); //ther meaning is unknown
}
@Test
public void testWrite() throws Exception {
ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testNewRecord() throws Exception {
ExOleObjAtom record = new ExOleObjAtom();
record.setDrawAspect(ExOleObjAtom.DRAW_ASPECT_VISIBLE);
@ -67,8 +67,6 @@ public final class TestExOleObjAtom extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
}

View File

@ -19,17 +19,20 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link HeadersFootersAtom} works properly
*
* @author Yegor Kozlov
*/
public final class TestExVideoContainer extends TestCase {
public final class TestExVideoContainer {
// From a real file
private final byte[] data = new byte[]{
@ -47,9 +50,7 @@ public final class TestExVideoContainer extends TestCase {
0x73, 0x00, 0x5C, 0x00, 0x63, 0x00, 0x61, 0x00, 0x72, 0x00, 0x64, 0x00, 0x73, 0x00, 0x2E, 0x00,
0x6D, 0x00, 0x70, 0x00, 0x67, 0x00};
@Test
public void testRead() {
ExVideoContainer record = new ExVideoContainer(data, 0, data.length);
assertEquals(RecordTypes.ExVideoContainer.typeID, record.getRecordType());
@ -66,15 +67,15 @@ public final class TestExVideoContainer extends TestCase {
assertEquals("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg", path.getText());
}
@Test
public void testWrite() throws Exception {
ExVideoContainer record = new ExVideoContainer(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testNewRecord() throws Exception {
ExVideoContainer record = new ExVideoContainer();
record.getExMediaAtom().setObjectId(1);
@ -82,8 +83,6 @@ public final class TestExVideoContainer extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
}

View File

@ -19,22 +19,24 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link HeadersFootersAtom} works properly
*
* @author Yegor Kozlov
*/
public final class TestHeadersFootersAtom extends TestCase {
public final class TestHeadersFootersAtom {
// From a real file
private final byte[] data = new byte[] {
0x00, 0x00, (byte)0xDA, 0x0F, 0x04, 0x00, 0x00, 00,
0x00, 0x00, (byte)0xDA, 0x0F, 0x04, 0x00, 0x00, 0,
0x00, 0x00, 0x23, 0x00 };
@Test
public void testRead() {
HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length);
assertEquals(RecordTypes.HeadersFootersAtom.typeID, record.getRecordType());
@ -50,15 +52,15 @@ public final class TestHeadersFootersAtom extends TestCase {
assertTrue(record.getFlag(HeadersFootersAtom.fHasFooter));
}
@Test
public void testWrite() throws Exception {
HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testNewRecord() throws Exception {
HeadersFootersAtom record = new HeadersFootersAtom();
record.setFlag(HeadersFootersAtom.fHasDate, true);
@ -67,11 +69,10 @@ public final class TestHeadersFootersAtom extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(data, b);
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testFlags() {
HeadersFootersAtom record = new HeadersFootersAtom();

View File

@ -19,17 +19,18 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that {@link HeadersFootersContainer} works properly
*
* @author Yegor Kozlov
*/
public final class TestHeadersFootersContainer extends TestCase {
public final class TestHeadersFootersContainer {
// SlideHeadersFootersContainer
private final byte[] slideData = new byte[] {
0x3F, 0x00, (byte)0xD9, 0x0F, 0x2E, 0x00, 0x00, 0x00,
@ -52,6 +53,7 @@ public final class TestHeadersFootersContainer extends TestCase {
0x6F, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00
};
@Test
public void testReadSlideHeadersFootersContainer() {
HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length);
assertEquals(RecordTypes.HeadersFooters.typeID, record.getRecordType());
@ -71,15 +73,15 @@ public final class TestHeadersFootersContainer extends TestCase {
assertNull(record.getHeaderAtom());
}
@Test
public void testWriteSlideHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(slideData, b);
assertArrayEquals(slideData, baos.toByteArray());
}
@Test
public void testNewSlideHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
@ -100,11 +102,10 @@ public final class TestHeadersFootersContainer extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(slideData, b);
assertArrayEquals(slideData, baos.toByteArray());
}
@Test
public void testReadNotesHeadersFootersContainer() {
HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length);
assertEquals(RecordTypes.HeadersFooters.typeID, record.getRecordType());
@ -125,15 +126,15 @@ public final class TestHeadersFootersContainer extends TestCase {
assertEquals("Note Footer", csFooter.getText());
}
@Test
public void testWriteNotesHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(notesData, b);
assertArrayEquals(notesData, baos.toByteArray());
}
@Test
public void testNewNotesHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(HeadersFootersContainer.NotesHeadersFootersContainer);
@ -162,9 +163,7 @@ public final class TestHeadersFootersContainer extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
assertArrayEquals(notesData, b);
assertArrayEquals(notesData, baos.toByteArray());
}
}

View File

@ -21,29 +21,32 @@
package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests that InteractiveInfoAtom works properly.
*
* @author Nick Burch (nick at torchbox dot com)
*/
public class TestInteractiveInfo extends TestCase {
public class TestInteractiveInfo {
// From a real file
private final byte[] data_a = new byte[] {
0x0F, 00, 0xF2-256, 0x0F, 0x18, 00, 00, 00,
00, 00, 0xF3-256, 0x0F, 0x10, 00, 00, 00,
00, 00, 00, 00, 01, 00, 00, 00,
04, 00, 00, 00, 8, 00, 00, 00
private final byte[] data_a = {
0x0F, 0, 0xF2-256, 0x0F, 0x18, 0, 0, 0,
0, 0, 0xF3-256, 0x0F, 0x10, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
4, 0, 0, 0, 8, 0, 0, 0
};
@Test
public void testRecordType() {
InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length);
assertEquals(4082, ii.getRecordType());
}
@Test
public void testGetChildDetails() {
InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length);
InteractiveInfoAtom ia = ii.getInteractiveInfoAtom();
@ -51,19 +54,16 @@ public class TestInteractiveInfo extends TestCase {
assertEquals(1, ia.getHyperlinkID());
}
@Test
public void testWrite() throws Exception {
InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ii.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Create A from scratch
@Test
public void testCreate() throws Exception {
InteractiveInfo ii = new InteractiveInfo();
InteractiveInfoAtom ia = ii.getInteractiveInfoAtom();
@ -77,11 +77,6 @@ public class TestInteractiveInfo extends TestCase {
// Check it's now the same as a
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ii.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
}

View File

@ -18,32 +18,36 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that InteractiveInfoAtom works properly.
*
* @author Nick Burch (nick at torchbox dot com)
*/
public class TestInteractiveInfoAtom extends TestCase {
public class TestInteractiveInfoAtom {
// From a real file
private final byte[] data_a = new byte[] {
00, 00, 0xF3-256, 0x0F, 0x10, 00, 00, 00,
00, 00, 00, 00, 01, 00, 00, 00,
04, 00, 00, 00, 8, 00, 00, 00
0, 0, 0xF3-256, 0x0F, 0x10, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
4, 0, 0, 0, 8, 0, 0, 0
};
private final byte[] data_b = new byte[] {
00, 00, 0xF3-256, 0x0F, 0x10, 00, 00, 00,
00, 00, 00, 00, 04, 00, 00, 00,
04, 00, 00, 00, 8, 00, 00, 00
0, 0, 0xF3-256, 0x0F, 0x10, 0, 0, 0,
0, 0, 0, 0, 4, 0, 0, 0,
4, 0, 0, 0, 8, 0, 0, 0
};
@Test
public void testRecordType() {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
assertEquals(4083l, ia.getRecordType());
assertEquals(4083L, ia.getRecordType());
}
@Test
public void testGetNumber() {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
InteractiveInfoAtom ib = new InteractiveInfoAtom(data_b, 0, data_b.length);
@ -52,6 +56,7 @@ public class TestInteractiveInfoAtom extends TestCase {
assertEquals(4, ib.getHyperlinkID());
}
@Test
public void testGetRest() {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
InteractiveInfoAtom ib = new InteractiveInfoAtom(data_b, 0, data_b.length);
@ -66,19 +71,16 @@ public class TestInteractiveInfoAtom extends TestCase {
assertEquals(8, ib.getHyperlinkType());
}
@Test
public void testWrite() throws Exception {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ia.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Create A from scratch
@Test
public void testCreate() throws Exception {
InteractiveInfoAtom ia = new InteractiveInfoAtom();
@ -91,15 +93,11 @@ public class TestInteractiveInfoAtom extends TestCase {
// Check it's now the same as a
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ia.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Try to turn a into b
@Test
public void testChange() throws Exception {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
@ -109,12 +107,6 @@ public class TestInteractiveInfoAtom extends TestCase {
// Check bytes are now the same
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ia.writeOut(baos);
byte[] b = baos.toByteArray();
// Should now be the same
assertEquals(data_b.length, b.length);
for(int i=0; i<data_b.length; i++) {
assertEquals(data_b[i],b[i]);
}
assertArrayEquals(data_b, baos.toByteArray());
}
}

View File

@ -18,23 +18,29 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that NotesAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestNotesAtom extends TestCase {
public final class TestNotesAtom {
// From a real file
private final byte[] data_a = new byte[] { 1, 0, 0xF1-256, 3, 8, 0, 0, 0,
0, 0, 0, 0x80-256, 0, 0, 0x0D, 0x30 };
@Test
public void testRecordType() {
NotesAtom na = new NotesAtom(data_a, 0, data_a.length);
assertEquals(1009l, na.getRecordType());
assertEquals(1009L, na.getRecordType());
}
@Test
public void testFlags() {
NotesAtom na = new NotesAtom(data_a, 0, data_a.length);
assertEquals(0x80000000, na.getSlideID());
@ -43,15 +49,11 @@ public final class TestNotesAtom extends TestCase {
assertFalse(na.getFollowMasterBackground());
}
@Test
public void testWrite() throws Exception {
NotesAtom na = new NotesAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
na.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
}

View File

@ -18,24 +18,30 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that SlidePersistAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestSlidePersistAtom extends TestCase {
public final class TestSlidePersistAtom {
// From a real file
private final byte[] data_a = new byte[] { 0, 0, 0xF3-256, 3, 0x14, 0, 0, 0,
4, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0 };
@Test
public void testRecordType() {
SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length);
assertEquals(1011l, spa.getRecordType());
assertEquals(1011L, spa.getRecordType());
}
@Test
public void testFlags() {
SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length);
assertEquals(4, spa.getRefID() );
@ -44,15 +50,11 @@ public final class TestSlidePersistAtom extends TestCase {
assertEquals(256, spa.getSlideIdentifier());
}
@Test
public void testWrite() throws Exception {
SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
spa.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
}

View File

@ -18,65 +18,62 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
/**
* Tests that TextBytesAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestTextBytesAtom extends TestCase {
public final class TestTextBytesAtom {
// From a real file
private final byte[] data = new byte[] { 0, 0, 0xA8-256, 0x0f, 0x1c, 0, 0, 0,
private final byte[] data = { 0, 0, 0xA8-256, 0x0f, 0x1c, 0, 0, 0,
0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
0x65, 0x20, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x20, 0x6F, 0x6E,
0x20, 0x70, 0x61, 0x67, 0x65, 0x20, 0x32 };
private final String data_text = "This is the title on page 2";
private final byte[] alt_data = new byte[] { 0, 0, 0xA8-256, 0x0F, 0x14, 0, 0, 0,
private final byte[] alt_data = { 0, 0, 0xA8-256, 0x0F, 0x14, 0, 0, 0,
0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20,
0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x69, 0x74, 0x6C, 0x65 };
private final String alt_text = "This is a test title";
@Test
public void testRecordType() {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
assertEquals(4008l, tba.getRecordType());
assertEquals(4008L, tba.getRecordType());
}
@Test
public void testTextA() {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
String data_text = "This is the title on page 2";
assertEquals(data_text, tba.getText());
}
@Test
public void testTextB() {
TextBytesAtom tba = new TextBytesAtom(alt_data,0,alt_data.length);
assertEquals(alt_text, tba.getText());
}
@Test
public void testChangeText() throws Exception {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
tba.setText(alt_text.getBytes(StandardCharsets.ISO_8859_1));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tba.writeOut(baos);
byte[] b = baos.toByteArray();
// Compare the header and the text
assertEquals(alt_data.length, b.length);
for(int i=0; i<alt_data.length; i++) {
assertEquals(alt_data[i],b[i]);
}
assertArrayEquals(alt_data, baos.toByteArray());
}
@Test
public void testWrite() throws Exception {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tba.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data.length, b.length);
for(int i=0; i<data.length; i++) {
assertEquals(data[i],b[i]);
}
assertArrayEquals(data, baos.toByteArray());
}
}

View File

@ -18,15 +18,17 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that TextCharsAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestTextCharsAtom extends TestCase {
public final class TestTextCharsAtom {
// From a real file
private final byte[] data = new byte[] { 0, 0, 0xA0-256, 0x0f, 0x08, 0, 0, 0,
0x54, 0x00, 0x68, 0x00, 0x69, 0x00, 0x73, 0x00 };
@ -35,47 +37,43 @@ public final class TestTextCharsAtom extends TestCase {
0x54, 0x00, 0x68, 0x00, 0x69, 0x00, 0x73, 0x00, 0xa3-256, 0x01 };
private final String alt_text = "This\u01A3";
@Test
public void testRecordType() {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
assertEquals(4000l, tca.getRecordType());
assertEquals(4000L, tca.getRecordType());
}
@Test
public void testTextA() {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
assertEquals(data_text, tca.getText());
}
@Test
public void testTextB() {
TextCharsAtom tca = new TextCharsAtom(alt_data,0,alt_data.length);
assertEquals(alt_text, tca.getText());
}
@Test
public void testChangeText() throws Exception {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
tca.setText(alt_text);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tca.writeOut(baos);
byte[] b = baos.toByteArray();
// Compare the header and the text
assertEquals(alt_data.length, b.length);
for(int i=0; i<alt_data.length; i++) {
assertEquals(alt_data[i],b[i]);
}
assertArrayEquals(alt_data, baos.toByteArray());
}
@Test
public void testWrite() throws Exception {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tca.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data.length, b.length);
for(int i=0; i<data.length; i++) {
assertEquals(data[i],b[i]);
}
assertArrayEquals(data, baos.toByteArray());
}
@Test
public void testCreateNew() throws Exception {
TextCharsAtom tca = new TextCharsAtom();
assertEquals(0, tca.getText().length());
@ -86,12 +84,7 @@ public final class TestTextCharsAtom extends TestCase {
// Check it's now like data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tca.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data.length, b.length);
for(int i=0; i<data.length; i++) {
assertEquals(data[i],b[i]);
}
assertArrayEquals(data, baos.toByteArray());
}
}

View File

@ -18,26 +18,30 @@
package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder;
import org.junit.Test;
/**
* Tests that TextHeaderAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestTextHeaderAtom extends TestCase {
public final class TestTextHeaderAtom {
// From a real file
private final byte[] notes_data = new byte[] { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 2, 0, 0, 0};
private final byte[] title_data = new byte[] { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 0, 0, 0, 0 };
private final byte[] body_data = new byte[] { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 1, 0, 0, 0 };
private final byte[] notes_data = { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 2, 0, 0, 0 };
private final byte[] title_data = { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 0, 0, 0, 0 };
private final byte[] body_data = { 0, 0, 0x9f-256, 0x0f, 4, 0, 0, 0, 1, 0, 0, 0 };
@Test
public void testRecordType() {
TextHeaderAtom tha = new TextHeaderAtom(notes_data,0,12);
assertEquals(3999l, tha.getRecordType());
assertEquals(3999L, tha.getRecordType());
}
@Test
public void testTypes() {
TextHeaderAtom n_tha = new TextHeaderAtom(notes_data,0,12);
TextHeaderAtom t_tha = new TextHeaderAtom(title_data,0,12);
@ -47,15 +51,11 @@ public final class TestTextHeaderAtom extends TestCase {
assertEquals(TextPlaceholder.BODY.nativeId, b_tha.getTextType());
}
@Test
public void testWrite() throws Exception {
TextHeaderAtom tha = new TextHeaderAtom(notes_data,0,12);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tha.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(notes_data.length, b.length);
for(int i=0; i<notes_data.length; i++) {
assertEquals(notes_data[i],b[i]);
}
assertArrayEquals(notes_data, baos.toByteArray());
}
}

View File

@ -18,20 +18,21 @@
package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Tests TextSpecInfoAtom
*
* @author Yegor Kozlov
*/
public final class TestTextSpecInfoAtom extends TestCase {
public final class TestTextSpecInfoAtom {
//from a real file
private final byte[] data_1 = new byte[] {
private final byte[] data_1 = {
0x00, 0x00, (byte)0xAA, 0x0F, 0x2C, 0x00, 0x00, 0x00,
0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00,
@ -39,7 +40,7 @@ public final class TestTextSpecInfoAtom extends TestCase {
0x00, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@Test
public void testRead() {
TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length);
TextSpecInfoRun[] run = spec.getTextSpecInfoRuns();
@ -50,18 +51,17 @@ public final class TestTextSpecInfoAtom extends TestCase {
assertEquals(70, run[2].getLength());
assertEquals(9, run[3].getLength());
assertEquals(32, run[4].getLength());
}
@Test
public void testWrite() throws Exception {
TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length);
ByteArrayOutputStream out = new ByteArrayOutputStream();
spec.writeOut(out);
byte[] result = out.toByteArray();
assertArrayEquals(result, data_1);
assertArrayEquals(data_1, out.toByteArray());
}
@Test
public void testReset() throws Exception {
TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length);
spec.reset(32); //length of the parent text

View File

@ -18,26 +18,29 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that TxInteractiveInfoAtom works properly.
*
* @author Yegor Kozlov
*/
public final class TestTxInteractiveInfoAtom extends TestCase {
public final class TestTxInteractiveInfoAtom {
// From WithLinks.ppt
private final byte[] data_a = new byte[] {
00, 00, (byte)0xDF, 0x0F, 0x08, 00, 00, 00,
0x19, 00, 00, 00, 0x38, 00, 00, 00
private final byte[] data_a = {
0, 0, (byte)0xDF, 0x0F, 0x08, 0, 0, 0,
0x19, 0, 0, 0, 0x38, 0, 0, 0
};
private final byte[] data_b = new byte[] {
00, 00, (byte)0xDF, 0x0F, 0x08, 00, 00, 00,
0x39, 00, 00, 00, 0x4E, 00, 00, 00
private final byte[] data_b = {
0, 0, (byte)0xDF, 0x0F, 0x08, 0, 0, 0,
0x39, 0, 0, 0, 0x4E, 0, 0, 0
};
@Test
public void testRead() {
TxInteractiveInfoAtom ia1 = new TxInteractiveInfoAtom(data_a, 0, data_a.length);
@ -52,19 +55,16 @@ public final class TestTxInteractiveInfoAtom extends TestCase {
assertEquals(78, ia2.getEndIndex());
}
@Test
public void testWrite() throws Exception {
TxInteractiveInfoAtom atom = new TxInteractiveInfoAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
atom.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Create A from scratch
@Test
public void testCreate() throws Exception {
TxInteractiveInfoAtom ia = new TxInteractiveInfoAtom();
@ -75,15 +75,11 @@ public final class TestTxInteractiveInfoAtom extends TestCase {
// Check it's now the same as a
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ia.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
// Try to turn a into b
@Test
public void testChange() throws Exception {
TxInteractiveInfoAtom ia = new TxInteractiveInfoAtom(data_a, 0, data_a.length);
@ -94,12 +90,6 @@ public final class TestTxInteractiveInfoAtom extends TestCase {
// Check bytes are now the same
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ia.writeOut(baos);
byte[] b = baos.toByteArray();
// Should now be the same
assertEquals(data_b.length, b.length);
for(int i=0; i<data_b.length; i++) {
assertEquals(data_b[i],b[i]);
}
assertArrayEquals(data_b, baos.toByteArray());
}
}

View File

@ -17,37 +17,43 @@
package org.apache.poi.hslf.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hslf.model.textproperties.TextProp;
import org.apache.poi.hslf.model.textproperties.TextPropCollection;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder;
import org.junit.Before;
import org.junit.Test;
/**
* Test <code>TestTxMasterStyleAtom</code> record.
* Check master style for the empty ppt which is created
* by the default constructor of <code>SlideShow</code>
*
* @author Yegor Kozlov
*/
public final class TestTxMasterStyleAtom extends TestCase {
protected HSLFSlideShow _ppt;
public final class TestTxMasterStyleAtom {
private HSLFSlideShow _ppt;
@Override
@Before
public void setUp() {
_ppt = new HSLFSlideShow();
}
@Test
public void testDefaultStyles() {
TxMasterStyleAtom[] txmaster = getMasterStyles();
for (final TxMasterStyleAtom atom : txmaster) {
final int txtype = atom.getTextType();
switch (TextPlaceholder.fromNativeId(txtype)){
TextPlaceholder tp = TextPlaceholder.fromNativeId(txtype);
assertNotNull(tp);
switch (tp) {
case TITLE:
checkTitleType(atom);
break;
@ -61,11 +67,8 @@ public final class TestTxMasterStyleAtom extends TestCase {
checkOtherType(atom);
break;
case CENTER_BODY:
break;
case CENTER_TITLE:
break;
case HALF_BODY:
break;
case QUARTER_BODY:
break;
default:
@ -200,7 +203,7 @@ public final class TestTxMasterStyleAtom extends TestCase {
* Collect all TxMasterStyleAtom records contained in the supplied slide show.
* There must be a TxMasterStyleAtom per each type of text defined in TextHeaderAtom
*/
protected TxMasterStyleAtom[] getMasterStyles(){
private TxMasterStyleAtom[] getMasterStyles(){
List<TxMasterStyleAtom> lst = new ArrayList<>();
Record[] coreRecs = _ppt.getMostRecentCoreRecords();
@ -221,13 +224,12 @@ public final class TestTxMasterStyleAtom extends TestCase {
Record[] rec = doc.getEnvironment().getChildRecords();
for (final Record atom : rec) {
if (atom instanceof TxMasterStyleAtom) {
if (txstyle != null) fail("Document.Environment must contain 1 TxMasterStyleAtom");
assertNull("Document.Environment must contain 1 TxMasterStyleAtom", txstyle);
txstyle = (TxMasterStyleAtom)atom;
}
}
if (txstyle == null) {
throw new AssertionFailedError("TxMasterStyleAtom not found in Document.Environment");
}
assertNotNull("TxMasterStyleAtom not found in Document.Environment", txstyle);
assertEquals("Document.Environment must contain TxMasterStyleAtom with type=TextHeaderAtom.OTHER_TYPE",
TextPlaceholder.OTHER.nativeId, txstyle.getTextType());

View File

@ -18,25 +18,30 @@
package org.apache.poi.hslf.record;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
/**
* Tests that UserEditAtom works properly
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestUserEditAtom extends TestCase {
public final class TestUserEditAtom {
// From a real file
private final byte[] data_a = new byte[] { 0, 0, 0xF5-256, 0x0F, 0x1C, 0, 0, 0,
00, 01, 00, 00, 0xD9-256, 18, 00, 03,
00, 00, 00, 00, 00, 0x18, 00, 00, 01, 00, 00, 00,
05, 00, 00, 00, 01, 00, 0xF6-256, 77 };
0, 1, 0, 0, 0xD9-256, 18, 0, 3,
0, 0, 0, 0, 0, 0x18, 0, 0, 1, 0, 0, 0,
5, 0, 0, 0, 1, 0, 0xF6-256, 77 };
@Test
public void testRecordType() {
UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length);
assertEquals(4085l, uea.getRecordType());
assertEquals(4085L, uea.getRecordType());
}
@Test
public void testFlags() {
UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length);
@ -49,15 +54,11 @@ public final class TestUserEditAtom extends TestCase {
assertEquals((short)1, uea.getLastViewType() );
}
@Test
public void testWrite() throws Exception {
UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
uea.writeOut(baos);
byte[] b = baos.toByteArray();
assertEquals(data_a.length, b.length);
for(int i=0; i<data_a.length; i++) {
assertEquals(data_a[i],b[i]);
}
assertArrayEquals(data_a, baos.toByteArray());
}
}

View File

@ -18,28 +18,30 @@
package org.apache.poi.hslf.usermodel;
import static org.junit.Assert.assertEquals;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.record.Record;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that SlideShow finds the right records as its most recent ones
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestMostRecentRecords extends TestCase {
public final class TestMostRecentRecords {
// HSLFSlideShow primed on the test data
private final HSLFSlideShowImpl hss;
private HSLFSlideShowImpl hss;
// SlideShow primed on the test data
private final HSLFSlideShow ss;
private HSLFSlideShow ss;
public TestMostRecentRecords() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
@Before
public void setup() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
ss = new HSLFSlideShow(hss);
}
@Test
public void testCount() {
// Most recent core records
Record[] mrcr = ss.getMostRecentCoreRecords();
@ -48,6 +50,7 @@ public final class TestMostRecentRecords extends TestCase {
assertEquals(7, mrcr.length);
}
@Test
public void testRightRecordTypes() {
// Most recent core records
Record[] mrcr = ss.getMostRecentCoreRecords();
@ -69,6 +72,7 @@ public final class TestMostRecentRecords extends TestCase {
assertEquals(1008, mrcr[6].getRecordType());
}
@Test
public void testCorrectRecords() {
// Most recent core records
Record[] mrcr = ss.getMostRecentCoreRecords();

View File

@ -18,41 +18,41 @@
package org.apache.poi.hslf.usermodel;
import org.apache.poi.POIDataSamples;
import static org.junit.Assert.assertArrayEquals;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.junit.Before;
import org.junit.Test;
/**
* Tests that SlideShow returns MetaSheets which have the right text in them
*
* @author Nick Burch (nick at torchbox dot com)
*/
public final class TestNotesText extends TestCase {
public final class TestNotesText {
// SlideShow primed on the test data
private final HSLFSlideShow ss;
private HSLFSlideShow ss;
public TestNotesText() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
@Before
public void setup() throws Exception {
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
ss = new HSLFSlideShow(hss);
}
@Test
public void testNotesOne() {
HSLFNotes notes = ss.getNotes().get(0);
String[] expectText = new String[] {"These are the notes for page 1"};
assertEquals(expectText.length, notes.getTextParagraphs().size());
for(int i=0; i<expectText.length; i++) {
assertEquals(expectText[i], HSLFTextParagraph.getRawText(notes.getTextParagraphs().get(i)));
}
String[] expectText = {"These are the notes for page 1"};
assertArrayEquals(expectText, toStrings(notes));
}
@Test
public void testNotesTwo() {
HSLFNotes notes = ss.getNotes().get(1);
String[] expectText = new String[] {"These are the notes on page two, again lacking formatting"};
assertEquals(expectText.length, notes.getTextParagraphs().size());
for(int i=0; i<expectText.length; i++) {
assertEquals(expectText[i], HSLFTextParagraph.getRawText(notes.getTextParagraphs().get(i)));
}
String[] expectText = {"These are the notes on page two, again lacking formatting"};
assertArrayEquals(expectText, toStrings(notes));
}
private static String[] toStrings(HSLFNotes notes) {
return notes.getTextParagraphs().stream().map(HSLFTextParagraph::getRawText).toArray(String[]::new);
}
}

View File

@ -17,28 +17,31 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.junit.Before;
import org.junit.Test;
/**
* Tests to verify if code page for general properties like subject,
* text body and html body is evaluated correctly.
*/
public final class Test7BitCodepage extends TestCase {
private final MAPIMessage ascii_cp1251_lcid1049;
private final MAPIMessage ascii_utf_8_cp1252_lcid1031;
private final MAPIMessage ascii_utf_8_cp1252_lcid1031_html;
private final MAPIMessage htmlbodybinary_cp1251;
private final MAPIMessage htmlbodybinary_utf_8;
public final class Test7BitCodepage {
private MAPIMessage ascii_cp1251_lcid1049;
private MAPIMessage ascii_utf_8_cp1252_lcid1031;
private MAPIMessage ascii_utf_8_cp1252_lcid1031_html;
private MAPIMessage htmlbodybinary_cp1251;
private MAPIMessage htmlbodybinary_utf_8;
/**
* Initialize this test, load up the messages.
* @throws Exception
*/
public Test7BitCodepage() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
ascii_cp1251_lcid1049 = new MAPIMessage(samples.openResourceAsStream("ASCII_CP1251_LCID1049.msg"));
ascii_utf_8_cp1252_lcid1031 = new MAPIMessage(samples.openResourceAsStream("ASCII_UTF-8_CP1252_LCID1031.msg"));
@ -50,6 +53,7 @@ public final class Test7BitCodepage extends TestCase {
/**
* Evaluate encoding and check if the subject, text body and html body is decoded correctly.
*/
@Test
public void test7BitEncoding() throws Exception {
ascii_cp1251_lcid1049.guess7BitEncoding();
ascii_cp1251_lcid1049.setReturnNullOnMissingChunk(true);
@ -61,23 +65,23 @@ public final class Test7BitCodepage extends TestCase {
htmlbodybinary_cp1251.setReturnNullOnMissingChunk(true);
htmlbodybinary_utf_8.guess7BitEncoding();
htmlbodybinary_utf_8.setReturnNullOnMissingChunk(true);
assertEquals("Subject автоматически Subject", ascii_cp1251_lcid1049.getSubject());
assertEquals("Body автоматически Body", ascii_cp1251_lcid1049.getTextBody());
assertEquals("<!DOCTYPE html><html><meta charset=\\\"windows-1251\\\"><body>HTML автоматически</body></html>", ascii_cp1251_lcid1049.getHtmlBody());
assertEquals("Subject öäü Subject", ascii_utf_8_cp1252_lcid1031.getSubject());
assertEquals("Body öäü Body", ascii_utf_8_cp1252_lcid1031.getTextBody());
assertNull(ascii_utf_8_cp1252_lcid1031.getHtmlBody());
assertEquals("Subject öäü Subject", ascii_utf_8_cp1252_lcid1031_html.getSubject());
assertEquals("Body öäü Body", ascii_utf_8_cp1252_lcid1031_html.getTextBody());
assertEquals("<!DOCTYPE html><html><meta charset=\\\"utf-8\\\"><body>HTML öäü</body></html>", ascii_utf_8_cp1252_lcid1031_html.getHtmlBody());
assertEquals("Subject öäü Subject", htmlbodybinary_cp1251.getSubject());
assertNull(htmlbodybinary_cp1251.getTextBody());
assertEquals("<!DOCTYPE html><html><meta charset=\\\"utf-8\\\"><body>HTML автоматически</body></html>", htmlbodybinary_cp1251.getHtmlBody());
assertEquals("Subject öäü Subject", htmlbodybinary_utf_8.getSubject());
assertNull(htmlbodybinary_utf_8.getTextBody());
assertEquals("<!DOCTYPE html><html><meta charset=\\\"utf-8\\\"><body>HTML öäü</body></html>", htmlbodybinary_utf_8.getHtmlBody());

View File

@ -19,34 +19,38 @@ package org.apache.poi.hsmf;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertStartsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Before;
import org.junit.Test;
/**
* Tests to verify that we can perform basic opperations on
* Tests to verify that we can perform basic opperations on
* a range of files
*/
public final class TestBasics extends TestCase {
private final MAPIMessage simple;
private final MAPIMessage quick;
private final MAPIMessage outlook30;
private final MAPIMessage attachments;
private final MAPIMessage noRecipientAddress;
private final MAPIMessage unicode;
private final MAPIMessage cyrillic;
private final MAPIMessage chinese;
public final class TestBasics {
private MAPIMessage simple;
private MAPIMessage quick;
private MAPIMessage outlook30;
private MAPIMessage attachments;
private MAPIMessage noRecipientAddress;
private MAPIMessage unicode;
private MAPIMessage cyrillic;
private MAPIMessage chinese;
/**
* Initialize this test, load up the blank.msg mapi message.
* @throws Exception
*/
public TestBasics() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
simple = new MAPIMessage(samples.openResourceAsStream("simple_test_msg.msg"));
quick = new MAPIMessage(samples.openResourceAsStream("quick.msg"));
@ -61,18 +65,19 @@ public final class TestBasics extends TestCase {
/**
* Can we always get the recipient's email?
*/
@Test
public void testRecipientEmail() throws Exception {
assertEquals("travis@overwrittenstack.com", simple.getRecipientEmailAddress());
assertEquals("kevin.roast@alfresco.org", quick.getRecipientEmailAddress());
assertEquals("nicolas1.23456@free.fr", attachments.getRecipientEmailAddress());
// This one has lots...
assertEquals(18, outlook30.getRecipientEmailAddressList().length);
assertEquals("shawn.bohn@pnl.gov; gus.calapristi@pnl.gov; Richard.Carter@pnl.gov; " +
"barb.cheney@pnl.gov; nick.cramer@pnl.gov; vern.crow@pnl.gov; Laura.Curtis@pnl.gov; " +
"julie.dunkle@pnl.gov; david.gillen@pnl.gov; michelle@pnl.gov; Jereme.Haack@pnl.gov; " +
"Michelle.Hart@pnl.gov; ranata.johnson@pnl.gov; grant.nakamura@pnl.gov; " +
"debbie.payne@pnl.gov; stuart.rose@pnl.gov; randall.scarberry@pnl.gov; Leigh.Williams@pnl.gov",
"debbie.payne@pnl.gov; stuart.rose@pnl.gov; randall.scarberry@pnl.gov; Leigh.Williams@pnl.gov",
outlook30.getRecipientEmailAddress()
);
}
@ -80,6 +85,7 @@ public final class TestBasics extends TestCase {
/**
* Test subject
*/
@Test
public void testSubject() throws Exception {
assertEquals("test message", simple.getSubject());
assertEquals("Test the content transformer", quick.getSubject());
@ -90,25 +96,26 @@ public final class TestBasics extends TestCase {
/**
* Test message headers
*/
@Test
public void testHeaders() throws Exception {
// Simple email first
assertEquals(26, simple.getHeaders().length);
assertStartsWith(simple.getHeaders()[0], "Return-path:");
assertEquals("Envelope-to: travis@overwrittenstack.com", simple.getHeaders()[1]);
assertStartsWith(simple.getHeaders()[25], "X-Antivirus-Scanner: Clean");
// Quick doesn't have them
try {
quick.getHeaders();
fail("expected ChunkNotFoundException");
} catch(ChunkNotFoundException e) {}
// Attachments doesn't have them
try {
attachments.getHeaders();
fail("expected ChunkNotFoundException");
} catch(ChunkNotFoundException e) {}
// Outlook30 has some
assertEquals(33, outlook30.getHeaders().length);
assertStartsWith(outlook30.getHeaders()[0], "Microsoft Mail Internet Headers");
@ -116,6 +123,7 @@ public final class TestBasics extends TestCase {
assertStartsWith(outlook30.getHeaders()[32], "\t\"Williams"); // May need better parsing in future
}
@Test
public void testBody() throws Exception {
// Messages may have their bodies saved as plain text, html, and/or rtf.
assertEquals("This is a test message.", simple.getTextBody());
@ -123,17 +131,17 @@ public final class TestBasics extends TestCase {
assertStartsWith(outlook30.getTextBody(), "I am shutting down the IN-SPIRE servers now for 30ish minutes.\r\n\r\n");
assertStartsWith(attachments.getTextBody(), "contenu\r\n\r\n");
assertStartsWith(unicode.getTextBody(), "..less you are Nick.....");
// outlook30 has chunks for all 3 body formats
// Examine one of the paragraphs is present in all 3 formats, surrounded by markup tags
String text = "I am shutting down the IN-SPIRE servers now for 30ish minutes.";
assertStartsWith(outlook30.getTextBody(), text + "\r\n\r\n");
assertEquals(850494485, outlook30.getTextBody().hashCode());
assertStartsWith(outlook30.getHtmlBody(), "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n<HTML>\r\n<HEAD>");
assertContains(outlook30.getHtmlBody(), "<P DIR=LTR><SPAN LANG=\"en-us\"><FONT FACE=\"Calibri\">" + text + "</FONT></SPAN></P>");
assertEquals(-654938715, outlook30.getHtmlBody().hashCode());
assertStartsWith(outlook30.getRtfBody(), "{\\rtf1\\adeflang1025\\ansi\\ansicpg1252\\uc1\\adeff3150");
assertContains(outlook30.getRtfBody(), "{\\rtlch\\fcs1 \\af31507 \\ltrch\\fcs0 \\cf0\\insrsid5003910 " + text + "\r\n\\par \r\n\\par");
assertEquals(891652290, outlook30.getRtfBody().hashCode());
@ -142,7 +150,8 @@ public final class TestBasics extends TestCase {
/**
* Test attachments
*/
public void testAttachments() throws Exception {
@Test
public void testAttachments() {
assertEquals(0, simple.getAttachmentFiles().length);
assertEquals(0, quick.getAttachmentFiles().length);
assertEquals(0, outlook30.getAttachmentFiles().length);
@ -153,6 +162,7 @@ public final class TestBasics extends TestCase {
* Test missing chunks.
* Use a file with no HTML body
*/
@Test
public void testMissingChunks() throws Exception {
assertFalse(attachments.isReturnNullOnMissingChunk());
@ -166,9 +176,9 @@ public final class TestBasics extends TestCase {
attachments.setReturnNullOnMissingChunk(true);
assertNull(attachments.getHtmlBody());
attachments.setReturnNullOnMissingChunk(false);
try {
attachments.getHtmlBody();
fail("expected ChunkNotFoundException");
@ -181,6 +191,7 @@ public final class TestBasics extends TestCase {
* More missing chunk testing, this time for
* missing recipient email address
*/
@Test
public void testMissingAddressChunk() throws Exception {
assertFalse(noRecipientAddress.isReturnNullOnMissingChunk());
@ -196,66 +207,68 @@ public final class TestBasics extends TestCase {
} catch(ChunkNotFoundException e) {
// Good
}
noRecipientAddress.setReturnNullOnMissingChunk(true);
noRecipientAddress.getRecipientEmailAddress();
noRecipientAddress.getRecipientEmailAddressList();
assertEquals("", noRecipientAddress.getRecipientEmailAddress());
assertEquals(1, noRecipientAddress.getRecipientEmailAddressList().length);
assertNull(noRecipientAddress.getRecipientEmailAddressList()[0]);
// Check a few other bits too
assertEquals("Microsoft Outlook 2003 Team", noRecipientAddress.getDisplayFrom());
assertEquals("New Outlook User", noRecipientAddress.getDisplayTo());
noRecipientAddress.setReturnNullOnMissingChunk(false);
}
/**
* Test the 7 bit detection
*/
public void test7BitDetection() throws Exception {
@Test
public void test7BitDetection() {
assertFalse(unicode.has7BitEncodingStrings());
assertTrue(simple.has7BitEncodingStrings());
assertTrue(chinese.has7BitEncodingStrings());
assertTrue(cyrillic.has7BitEncodingStrings());
}
/**
* We default to CP1252, but can sometimes do better
* if needed.
* This file is really CP1251, according to the person
* who submitted it in bug #49441
*/
@Test
public void testEncoding() throws Exception {
assertEquals(2, cyrillic.getRecipientDetailsChunks().length);
assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
cyrillic.guess7BitEncoding();
assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
// Override it, check it's taken
cyrillic.set7BitEncoding("UTF-8");
assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
// Check with a file that has no headers
try {
chinese.getHeaders();
fail("File doesn't have headers!");
} catch(ChunkNotFoundException e) {}
String html = chinese.getHtmlBody();
assertTrue("Charset not found:\n" + html, html.contains("text/html; charset=big5"));
// Defaults to CP1251
assertEquals("CP1252", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
// But after guessing goes to the correct one, cp950 (Windows Traditional Chinese)
chinese.guess7BitEncoding();
assertEquals("cp950", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());

View File

@ -17,104 +17,97 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.apache.poi.POIDataSamples;
import junit.framework.TestCase;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Before;
import org.junit.Test;
/**
* Tests to verify that the library can read blank msg files.
*/
public final class TestBlankFileRead extends TestCase {
private final MAPIMessage mapiMessage;
public final class TestBlankFileRead {
private MAPIMessage mapiMessage;
/**
* Initialize this test, load up the blank.msg mapi message.
*/
public TestBlankFileRead() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("blank.msg"));
mapiMessage = new MAPIMessage(samples.openResourceAsStream("blank.msg"));
}
/**
* Check if we can read the body of the blank message, we expect "".
*/
public void testReadBody() {
try {
mapiMessage.getTextBody();
} catch(ChunkNotFoundException exp) {
return;
}
TestCase.fail("Should have thrown a ChunkNotFoundException but didn't");
@Test(expected = ChunkNotFoundException.class)
public void testReadBody() throws ChunkNotFoundException {
mapiMessage.getTextBody();
}
/**
* Test to see if we can read the CC Chunk.
*/
@Test
public void testReadDisplayCC() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayCC();
String expected = "";
TestCase.assertEquals(expected, obtained);
assertEquals(expected, obtained);
}
/**
* Test to see if we can read the CC Chunk.
*/
@Test
public void testReadDisplayTo() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayTo();
String expected = "";
TestCase.assertEquals(expected, obtained);
assertEquals(expected, obtained);
}
/**
* Test to see if we can read the FROM Chunk.
*/
public void testReadDisplayFrom() {
try {
mapiMessage.getDisplayFrom();
} catch(ChunkNotFoundException exp) {
return;
}
TestCase.fail("Should have thrown a ChunkNotFoundException but didn't");
@Test(expected = ChunkNotFoundException.class)
public void testReadDisplayFrom() throws ChunkNotFoundException {
mapiMessage.getDisplayFrom();
}
/**
* Test to see if we can read the CC Chunk.
*/
@Test
public void testReadDisplayBCC() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayBCC();
String expected = "";
TestCase.assertEquals(expected, obtained);
assertEquals(expected, obtained);
}
/**
* Check if we can read the subject line of the blank message, we expect ""
*/
@Test
public void testReadSubject() throws Exception {
String obtained = mapiMessage.getSubject();
TestCase.assertEquals("", obtained);
assertEquals("", obtained);
}
/**
* Check if we can read the subject line of the blank message, we expect ""
*/
public void testReadConversationTopic() {
try {
mapiMessage.getConversationTopic();
} catch(ChunkNotFoundException exp) {
return;
}
TestCase.fail("We shouldn't have a ConversationTopic node on the blank.msg file.");
@Test(expected = ChunkNotFoundException.class)
public void testReadConversationTopic() throws ChunkNotFoundException {
mapiMessage.getConversationTopic();
}
}

View File

@ -17,41 +17,45 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.apache.poi.POIDataSamples;
import java.util.Calendar;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Before;
import org.junit.Test;
public final class TestMessageSubmissionChunk extends TestCase {
private final MAPIMessage mapiMessageExtraHyphenSubmissionChunk;
private final MAPIMessage mapiMessageNormalSubmissionChunk;
public final class TestMessageSubmissionChunk {
private MAPIMessage mapiMessageExtraHyphenSubmissionChunk;
private MAPIMessage mapiMessageNormalSubmissionChunk;
/**
* Initialise this test, load up the test messages.
* @throws Exception
*/
public TestMessageSubmissionChunk() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
this.mapiMessageExtraHyphenSubmissionChunk = new MAPIMessage(samples.openResourceAsStream("message_extra_hyphen_submission_chunk.msg"));
this.mapiMessageNormalSubmissionChunk = new MAPIMessage(samples.openResourceAsStream("message_normal_submission_chunk.msg"));
}
@Test
public void testReadMessageDateExtraHyphenSubmissionChunk() throws ChunkNotFoundException {
final Calendar date = mapiMessageExtraHyphenSubmissionChunk.getMessageDate();
TestCase.assertNotNull(date);
assertNotNull(date);
final int year = date.get(Calendar.YEAR);
TestCase.assertEquals(2007, year);
assertEquals(2007, year);
}
@Test
public void testReadMessageDateNormalSubmissionChunk() throws ChunkNotFoundException {
final Calendar date = mapiMessageNormalSubmissionChunk.getMessageDate();
TestCase.assertNotNull(date);
assertNotNull(date);
final int year = date.get(Calendar.YEAR);
TestCase.assertEquals(2007, year);
assertEquals(2007, year);
}
}

View File

@ -17,50 +17,54 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.apache.poi.POIDataSamples;
import java.util.Calendar;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Before;
import org.junit.Test;
public final class TestMessageSubmissionChunkY2KRead extends TestCase {
private final MAPIMessage mapiMessage1979;
private final MAPIMessage mapiMessage1980;
private final MAPIMessage mapiMessage1981;
public final class TestMessageSubmissionChunkY2KRead {
private MAPIMessage mapiMessage1979;
private MAPIMessage mapiMessage1980;
private MAPIMessage mapiMessage1981;
/**
* Initialise this test, load up the three test messages.
* @throws Exception
*/
public TestMessageSubmissionChunkY2KRead() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
this.mapiMessage1979 = new MAPIMessage(samples.openResourceAsStream("message_1979.msg"));
this.mapiMessage1980 = new MAPIMessage(samples.openResourceAsStream("message_1980.msg"));
this.mapiMessage1981 = new MAPIMessage(samples.openResourceAsStream("message_1981.msg"));
mapiMessage1979 = new MAPIMessage(samples.openResourceAsStream("message_1979.msg"));
mapiMessage1980 = new MAPIMessage(samples.openResourceAsStream("message_1980.msg"));
mapiMessage1981 = new MAPIMessage(samples.openResourceAsStream("message_1981.msg"));
}
// 1979 is one year before our pivot year (so this is an expected "failure")
@Test
public void testReadMessageDate1979() throws ChunkNotFoundException {
final Calendar date = mapiMessage1979.getMessageDate();
final int year = date.get(Calendar.YEAR);
TestCase.assertEquals(2079, year);
assertEquals(2079, year);
}
// 1980 is our pivot year (so this is an expected "failure")
@Test
public void testReadMessageDate1980() throws ChunkNotFoundException {
final Calendar date = mapiMessage1980.getMessageDate();
final int year = date.get(Calendar.YEAR);
TestCase.assertEquals(2080, year);
assertEquals(2080, year);
}
// 1981 is one year after our pivot year (so this starts working)
@Test
public void testReadMessageDate1981() throws ChunkNotFoundException {
final Calendar date = mapiMessage1981.getMessageDate();
final int year = date.get(Calendar.YEAR);
TestCase.assertEquals(1981, year);
assertEquals(1981, year);
}
}

View File

@ -17,45 +17,47 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.apache.poi.POIDataSamples;
import junit.framework.TestCase;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Before;
import org.junit.Test;
/**
* Tests to verify that we can still work on the newer Outlook 3.0 files.
*/
public final class TestOutlook30FileRead extends TestCase {
private final MAPIMessage mapiMessage;
public final class TestOutlook30FileRead {
private MAPIMessage mapiMessage;
/**
* Initialize this test, load up the blank.msg mapi message.
* @throws Exception
*/
public TestOutlook30FileRead() throws IOException {
@Before
public void setup() throws IOException {
POIDataSamples samples = POIDataSamples.getHSMFInstance();
this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("outlook_30_msg.msg"));
}
/**
* Test to see if we can read the CC Chunk.
* @throws ChunkNotFoundException
*
*/
@Test
public void testReadDisplayCC() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayCC();
String expected = "";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
* Test to see if we can read the CC Chunk.
* @throws ChunkNotFoundException
*
*/
@Test
public void testReadDisplayTo() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayTo();
@ -64,34 +66,31 @@ public final class TestOutlook30FileRead extends TestCase {
/**
* Test to see if we can read the From Chunk.
* @throws ChunkNotFoundException
*
*/
@Test
public void testReadDisplayFrom() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayFrom();
String expected = "Cramer, Nick";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
* Test to see if we can read the CC Chunk.
* @throws ChunkNotFoundException
*
*/
@Test
public void testReadDisplayBCC() throws ChunkNotFoundException {
String obtained = mapiMessage.getDisplayBCC();
String expected = "";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
* Check if we can read the body of the blank message, we expect "".
*
* @throws Exception
*/
@Test
public void testReadBody() throws Exception {
String obtained = mapiMessage.getTextBody();
assertTrue(obtained.startsWith("I am shutting down"));
@ -99,39 +98,37 @@ public final class TestOutlook30FileRead extends TestCase {
/**
* Check if we can read the subject line of the blank message, we expect ""
*
* @throws Exception
*/
@Test
public void testReadSubject() throws Exception {
String obtained = mapiMessage.getSubject();
String expected = "IN-SPIRE servers going down for a bit, back up around 8am";
TestCase.assertEquals(expected, obtained);
assertEquals(expected, obtained);
}
/**
* Check if we can read the subject line of the blank message, we expect ""
*
* @throws Exception
*/
@Test
public void testReadConversationTopic() throws Exception {
String obtained = mapiMessage.getConversationTopic();
TestCase.assertEquals("IN-SPIRE servers going down for a bit, back up around 8am", obtained);
assertEquals("IN-SPIRE servers going down for a bit, back up around 8am", obtained);
}
/**
* Check if we can read the subject line of the blank message, we expect ""
*
* @throws Exception
*/
@Test
public void testReadMessageClass() throws Exception {
MAPIMessage.MESSAGE_CLASS obtained = mapiMessage.getMessageClassEnum();
TestCase.assertEquals(MAPIMessage.MESSAGE_CLASS.NOTE, obtained);
assertEquals(MAPIMessage.MESSAGE_CLASS.NOTE, obtained);
}
/**
* Ensure we can get the HTML and RTF versions
*/
@Test
public void testReadBodyContents() throws Exception {
String html = mapiMessage.getHtmlBody();
String rtf = mapiMessage.getRtfBody();

View File

@ -17,15 +17,15 @@
package org.apache.poi.hsmf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Tests to verify that we can read a simple msg file, that is in plain/text
* format with no attachments or extra recipents.
@ -50,7 +50,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getDisplayCC();
String expected = "";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
@ -61,7 +61,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getDisplayTo();
String expected = "travis@overwrittenstack.com";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
@ -72,7 +72,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getDisplayFrom();
String expected = "Travis Ferguson";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
@ -83,7 +83,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getDisplayBCC();
String expected = "";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
@ -95,7 +95,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getTextBody();
String expected = "This is a test message.";
TestCase.assertEquals(obtained, expected);
assertEquals(obtained, expected);
}
/**
@ -106,7 +106,7 @@ public final class TestSimpleFileRead {
String obtained = mapiMessage.getSubject();
String expected = "test message";
TestCase.assertEquals(expected, obtained);
assertEquals(expected, obtained);
}
/**
@ -115,7 +115,7 @@ public final class TestSimpleFileRead {
@Test
public void testReadConversationTopic() throws Exception {
String obtained = mapiMessage.getConversationTopic();
TestCase.assertEquals("test message", obtained);
assertEquals("test message", obtained);
}
@ -125,7 +125,7 @@ public final class TestSimpleFileRead {
@Test
public void testReadMessageClass() throws Exception {
MAPIMessage.MESSAGE_CLASS obtained = mapiMessage.getMessageClassEnum();
TestCase.assertEquals(MAPIMessage.MESSAGE_CLASS.NOTE, obtained);
assertEquals(MAPIMessage.MESSAGE_CLASS.NOTE, obtained);
}
/**
@ -133,7 +133,7 @@ public final class TestSimpleFileRead {
*/
@Test
public void testReadMessageClass2() throws Exception {
TestCase.assertEquals(
assertEquals(
MAPIMessage.MESSAGE_CLASS.NOTE, mapiMessage.getMessageClassEnum());
for (String messageClass : new String[]{

View File

@ -17,19 +17,19 @@
package org.apache.poi.hsmf.datatypes;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Verifies that the Chunks class is actually setup properly and hasn't been changed in ways
* that will break the library.
*
* @author Travis Ferguson
*
*/
public final class TestChunkData extends TestCase {
public final class TestChunkData {
@Test
public void testChunkCreate() {
Chunk chunk;
chunk = new StringChunk(0x0200, Types.createCustom(0x001E));
assertEquals("__substg1.0_0200001E", chunk.getEntryName());
assertEquals(0x0200, chunk.getChunkId());
@ -39,12 +39,12 @@ public final class TestChunkData extends TestCase {
assertEquals("__substg1.0_0200001E", chunk.getEntryName());
assertEquals(0x0200, chunk.getChunkId());
assertEquals(0x001E, chunk.getType().getId());
chunk = new StringChunk("__substg1.0_", 0x0200, Types.getById(0x001E));
assertEquals("__substg1.0_0200001E", chunk.getEntryName());
assertEquals(0x0200, chunk.getChunkId());
assertEquals(0x001E, chunk.getType().getId());
/* test the lower and upper limits of the chunk ids */
chunk = new StringChunk(0x0000, Types.createCustom(0x001E));
assertEquals("__substg1.0_0000001E", chunk.getEntryName());
@ -56,27 +56,32 @@ public final class TestChunkData extends TestCase {
assertEquals("__substg1.0_FFFF001F", chunk.getEntryName());
}
@Test
public void testTextBodyChunk() {
StringChunk chunk = new StringChunk(0x1000, Types.UNICODE_STRING);
assertEquals(chunk.getChunkId(), MAPIProperty.BODY.id);
}
@Test
public void testDisplayToChunk() {
StringChunk chunk = new StringChunk(0x0E04, Types.UNICODE_STRING);
assertEquals(chunk.getChunkId(), MAPIProperty.DISPLAY_TO.id);
}
@Test
public void testDisplayCCChunk() {
StringChunk chunk = new StringChunk(0x0E03, Types.UNICODE_STRING);
assertEquals(chunk.getChunkId(), MAPIProperty.DISPLAY_CC.id);
}
@Test
public void testDisplayBCCChunk() {
StringChunk chunk = new StringChunk(0x0E02, Types.UNICODE_STRING);
assertEquals(chunk.getChunkId(), MAPIProperty.DISPLAY_BCC.id);
}
@Test
public void testSubjectChunk() {
Chunk chunk = new StringChunk(0x0037, Types.UNICODE_STRING);
assertEquals(chunk.getChunkId(), MAPIProperty.SUBJECT.id);

View File

@ -17,42 +17,50 @@
package org.apache.poi.hsmf.datatypes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Checks various MAPIProperty related logic
*/
public final class TestMAPIProperty extends TestCase {
public void testGet() throws Exception {
public final class TestMAPIProperty {
@Test
public void testGet() {
assertEquals(MAPIProperty.DISPLAY_NAME, MAPIProperty.get(MAPIProperty.DISPLAY_NAME.id));
assertEquals(MAPIProperty.DISPLAY_BCC, MAPIProperty.get(MAPIProperty.DISPLAY_BCC.id));
assertNotSame(MAPIProperty.DISPLAY_BCC, MAPIProperty.get(MAPIProperty.DISPLAY_CC.id));
}
public void testGetAll() throws Exception {
@Test
public void testGetAll() {
Collection<MAPIProperty> all = MAPIProperty.getAll();
assertTrue(all.contains(MAPIProperty.DISPLAY_NAME));
assertTrue(all.contains(MAPIProperty.DISPLAY_CC));
// Won't contain custom
assertFalse(all.contains(MAPIProperty.createCustom(1, Types.UNSPECIFIED, "")));
// Won't contain unknown
assertFalse(all.contains(MAPIProperty.UNKNOWN));
}
public void testCustom() throws Exception {
@Test
public void testCustom() {
MAPIProperty c1 = MAPIProperty.createCustom(1, Types.UNSPECIFIED, "");
MAPIProperty c2a = MAPIProperty.createCustom(2, Types.UNSPECIFIED, "2");
MAPIProperty c2b = MAPIProperty.createCustom(2, Types.UNSPECIFIED, "2");
// New object each time
assertNotSame(c1, c2a);
assertNotSame(c1, c2b);
assertNotSame(c2a, c2b);
// Won't be in all list
Collection<MAPIProperty> all = MAPIProperty.getAll();
assertFalse(all.contains(c1));

View File

@ -17,21 +17,22 @@
package org.apache.poi.hsmf.datatypes;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.apache.poi.hsmf.datatypes.AttachmentChunks.AttachmentChunksSorter;
import org.apache.poi.hsmf.datatypes.RecipientChunks.RecipientChunksSorter;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Checks that the sorters on the chunk groups order
* chunks properly.
* Checks that the sorters on the chunk groups order chunks properly.
*/
public final class TestSorters extends TestCase {
public final class TestSorters {
@Test
public void testAttachmentChunksSorter() {
AttachmentChunks[] chunks;
// Simple
chunks = new AttachmentChunks[] {
new AttachmentChunks("__attach_version1.0_#00000001"),
@ -40,7 +41,7 @@ public final class TestSorters extends TestCase {
Arrays.sort(chunks, new AttachmentChunksSorter());
assertEquals("__attach_version1.0_#00000000", chunks[0].getPOIFSName());
assertEquals("__attach_version1.0_#00000001", chunks[1].getPOIFSName());
// Lots, with gaps
chunks = new AttachmentChunks[] {
new AttachmentChunks("__attach_version1.0_#00000101"),
@ -60,10 +61,11 @@ public final class TestSorters extends TestCase {
assertEquals("__attach_version1.0_#000000AB", chunks[5].getPOIFSName());
assertEquals("__attach_version1.0_#00000101", chunks[6].getPOIFSName());
}
@Test
public void testRecipientChunksSorter() {
RecipientChunks[] chunks;
// Simple
chunks = new RecipientChunks[] {
new RecipientChunks("__recip_version1.0_#00000001"),
@ -72,7 +74,7 @@ public final class TestSorters extends TestCase {
Arrays.sort(chunks, new RecipientChunksSorter());
assertEquals(0, chunks[0].recipientNumber);
assertEquals(1, chunks[1].recipientNumber);
// Lots, with gaps
chunks = new RecipientChunks[] {
new RecipientChunks("__recip_version1.0_#00020001"),

View File

@ -17,39 +17,44 @@
package org.apache.poi.hsmf.datatypes;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Verifies that the Types class is behaving properly.
* Also check that no changes have been made that will
* break the library.
*/
public final class TestTypes extends TestCase {
public final class TestTypes {
@Test
public void testTypeIds() {
assertEquals(0x1e, Types.ASCII_STRING.getId());
assertEquals(0x1f, Types.UNICODE_STRING.getId());
assertEquals(0x0102, Types.BINARY.getId());
assertEquals(0x000B, Types.BOOLEAN.getId());
assertEquals(0x0003, Types.LONG.getId());
assertEquals(0x0040, Types.TIME.getId());
assertEquals(Types.ASCII_STRING, Types.getById(0x1e));
assertEquals(Types.UNICODE_STRING, Types.getById(0x1f));
assertEquals(Types.BINARY, Types.getById(0x0102));
assertEquals(Types.BOOLEAN, Types.getById(0x000B));
assertEquals(Types.LONG, Types.getById(0x0003));
assertEquals(Types.TIME, Types.getById(0x0040));
}
@Test
public void testTypeFormatting() {
assertEquals("0000", Types.asFileEnding(0x0000));
assertEquals("0020", Types.asFileEnding(0x0020));
assertEquals("0102", Types.asFileEnding(0x0102));
assertEquals("FEDC", Types.asFileEnding(0xfedc));
}
@Test
public void testName() {
assertEquals("ASCII String", Types.ASCII_STRING.getName());
assertEquals("Boolean", Types.BOOLEAN.getName());

View File

@ -17,6 +17,11 @@
package org.apache.poi.hwpf;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -27,14 +32,13 @@ import javax.imageio.ImageIO;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.Picture;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
/**
* Test picture support in HWPF
* @author nick
*/
public final class TestHWPFPictures extends TestCase {
public final class TestHWPFPictures {
private String docAFile;
private String docBFile;
private String docCFile;
@ -45,10 +49,8 @@ public final class TestHWPFPictures extends TestCase {
private String imgCFile;
private String imgDFile;
@Override
protected void setUp() throws Exception {
super.setUp();
@Before
public void setUp() {
docAFile = "testPictures.doc";
docBFile = "two_images.doc";
docCFile = "vector_image.doc";
@ -68,6 +70,7 @@ public final class TestHWPFPictures extends TestCase {
/**
* Test just opening the files
*/
@Test
public void testOpen() {
HWPFTestDataSamples.openSampleFile(docAFile);
HWPFTestDataSamples.openSampleFile(docBFile);
@ -76,6 +79,7 @@ public final class TestHWPFPictures extends TestCase {
/**
* Test that we have the right numbers of images in each file
*/
@Test
public void testImageCount() {
HWPFDocument docA = HWPFTestDataSamples.openSampleFile(docAFile);
HWPFDocument docB = HWPFTestDataSamples.openSampleFile(docBFile);
@ -96,6 +100,7 @@ public final class TestHWPFPictures extends TestCase {
/**
* Test that we have the right images in at least one file
*/
@Test
public void testImageData() {
HWPFDocument docB = HWPFTestDataSamples.openSampleFile(docBFile);
PicturesTable picB = docB.getPicturesTable();
@ -113,16 +118,14 @@ public final class TestHWPFPictures extends TestCase {
byte[] pic1B = readFile(imgAFile);
byte[] pic2B = readFile(imgBFile);
assertEquals(pic1B.length, pic1.getContent().length);
assertEquals(pic2B.length, pic2.getContent().length);
assertBytesSame(pic1B, pic1.getContent());
assertBytesSame(pic2B, pic2.getContent());
assertArrayEquals(pic1B, pic1.getContent());
assertArrayEquals(pic2B, pic2.getContent());
}
/**
* Test that compressed image data is correctly returned.
*/
@Test
public void testCompressedImageData() {
HWPFDocument docC = HWPFTestDataSamples.openSampleFile(docCFile);
PicturesTable picC = docC.getPicturesTable();
@ -135,11 +138,10 @@ public final class TestHWPFPictures extends TestCase {
// Check the same
byte[] picBytes = readFile(imgCFile);
assertEquals(picBytes.length, pic.getContent().length);
assertBytesSame(picBytes, pic.getContent());
assertArrayEquals(picBytes, pic.getContent());
}
@Test
public void testMacImages() throws Exception {
HWPFDocument docC = HWPFTestDataSamples.openSampleFile("53446.doc");
PicturesTable picturesTable = docC.getPicturesTable();
@ -168,6 +170,7 @@ public final class TestHWPFPictures extends TestCase {
* Pending the missing files being uploaded to
* bug #44937
*/
@Test
public void testEscherDrawing() {
HWPFDocument docD = HWPFTestDataSamples.openSampleFile(docDFile);
List<Picture> allPictures = docD.getPicturesTable().getAllPictures();
@ -180,14 +183,7 @@ public final class TestHWPFPictures extends TestCase {
assertEquals(picD.length, pic.getContent().length);
assertBytesSame(picD, pic.getContent());
}
private void assertBytesSame(byte[] a, byte[] b) {
assertEquals(a.length, b.length);
for(int i=0; i<a.length; i++) {
assertEquals(a[i],b[i]);
}
assertArrayEquals(picD, pic.getContent());
}
private static byte[] readFile(String file) {

View File

@ -17,15 +17,16 @@
package org.apache.poi.hwpf;
import org.apache.poi.hwpf.usermodel.Range;
import static org.junit.Assert.assertEquals;
import junit.framework.TestCase;
import org.apache.poi.hwpf.usermodel.Range;
import org.junit.Before;
import org.junit.Test;
/**
* Test that we pull out the right bits of a file into
* the different ranges
* Test that we pull out the right bits of a file into the different ranges
*/
public final class TestHWPFRangeParts extends TestCase {
public final class TestHWPFRangeParts {
private static final char page_break = (char)12;
private static final String headerDef =
"\u0003\r\r" +
@ -93,7 +94,7 @@ public final class TestHWPFRangeParts extends TestCase {
*/
private HWPFDocument docUnicode;
@Override
@Before
public void setUp() {
docUnicode = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc");
docAscii = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc");
@ -104,11 +105,12 @@ public final class TestHWPFRangeParts extends TestCase {
* don't get broken as we write out and read back in again
* TODO - Make this work with 3+ runs
*/
@Test
public void testContents() {
HWPFDocument doc = docAscii;
for(int run=0; run<3; run++) {
Range r;
// Now check the real ranges
r = doc.getRange();
assertEquals(
@ -117,7 +119,7 @@ public final class TestHWPFRangeParts extends TestCase {
a_page_2,
r.text()
);
r = doc.getHeaderStoryRange();
assertEquals(
headerDef +
@ -127,7 +129,7 @@ public final class TestHWPFRangeParts extends TestCase {
endHeaderFooter,
r.text()
);
r = doc.getOverallRange();
assertEquals(
a_page_1 +
@ -141,7 +143,7 @@ public final class TestHWPFRangeParts extends TestCase {
"\r",
r.text()
);
// Write out and read back in again, ready for
// the next run of the test
// TODO run more than once
@ -150,6 +152,7 @@ public final class TestHWPFRangeParts extends TestCase {
}
}
@Test
public void testContentsUnicode() {
Range r;

View File

@ -16,25 +16,23 @@
==================================================================== */
package org.apache.poi.hwpf.converter;
import org.apache.poi.hwpf.usermodel.Range;
import static org.junit.Assert.assertEquals;
import junit.framework.TestCase;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.junit.Test;
/**
* Test cases for {@link AbstractWordUtils}
*
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public class AbstractWordUtilsTest extends TestCase
{
public class AbstractWordUtilsTest {
/**
* Test case for {@link AbstractWordUtils#buildTableCellEdgesArray(Table)}
*/
public void testBuildTableCellEdgesArray()
{
@Test
public void testBuildTableCellEdgesArray() {
HWPFDocument document = HWPFTestDataSamples
.openSampleFile( "table-merges.doc" );
final Range range = document.getRange();

View File

@ -16,13 +16,14 @@
==================================================================== */
package org.apache.poi.hwpf.converter;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
public class TestNumberFormatter extends TestCase
{
import org.junit.Test;
public void testRoman()
{
public class TestNumberFormatter {
@Test
public void testRoman() {
assertEquals( "i", NumberFormatter.getNumber( 1, 2 ) );
assertEquals( "ii", NumberFormatter.getNumber( 2, 2 ) );
assertEquals( "iii", NumberFormatter.getNumber( 3, 2 ) );
@ -39,44 +40,42 @@ public class TestNumberFormatter extends TestCase
assertEquals( "mcmliv", NumberFormatter.getNumber( 1954, 2 ) );
}
public void testEnglish()
{
@Test
public void testEnglish() {
assertEquals( "a", NumberFormatter.getNumber( 1, 4 ) );
assertEquals( "z", NumberFormatter.getNumber( 26, 4 ) );
assertEquals( "aa", NumberFormatter.getNumber( 1 * 26 + 1, 4 ) );
assertEquals( "az", NumberFormatter.getNumber( 1 * 26 + 26, 4 ) );
assertEquals( "aa", NumberFormatter.getNumber( 26 + 1, 4 ) );
assertEquals( "az", NumberFormatter.getNumber( 26 + 26, 4 ) );
assertEquals( "za", NumberFormatter.getNumber( 26 * 26 + 1, 4 ) );
assertEquals( "zz", NumberFormatter.getNumber( 26 * 26 + 26, 4 ) );
assertEquals( "aaa",
NumberFormatter.getNumber( 26 * 26 + 1 * 26 + 1, 4 ) );
NumberFormatter.getNumber( 26 * 26 + 26 + 1, 4 ) );
assertEquals( "aaz",
NumberFormatter.getNumber( 26 * 26 + 1 * 26 + 26, 4 ) );
NumberFormatter.getNumber( 26 * 26 + 26 + 26, 4 ) );
assertEquals( "aba",
NumberFormatter.getNumber( 1 * 26 * 26 + 2 * 26 + 1, 4 ) );
NumberFormatter.getNumber( 26 * 26 + 2 * 26 + 1, 4 ) );
assertEquals( "aza",
NumberFormatter.getNumber( 1 * 26 * 26 + 26 * 26 + 1, 4 ) );
NumberFormatter.getNumber( 26 * 26 + 26 * 26 + 1, 4 ) );
assertEquals( "azz",
NumberFormatter.getNumber( 26 * 26 + 26 * 26 + 26, 4 ) );
assertEquals( "baa",
NumberFormatter.getNumber( 2 * 26 * 26 + 1 * 26 + 1, 4 ) );
NumberFormatter.getNumber( 2 * 26 * 26 + 26 + 1, 4 ) );
assertEquals( "zaa",
NumberFormatter.getNumber( 26 * 26 * 26 + 1 * 26 + 1, 4 ) );
NumberFormatter.getNumber( 26 * 26 * 26 + 26 + 1, 4 ) );
assertEquals( "zzz",
NumberFormatter.getNumber( 26 * 26 * 26 + 26 * 26 + 26, 4 ) );
assertEquals(
"aaaa",
NumberFormatter.getNumber( 1 * 26 * 26 * 26 + 1 * 26 * 26 + 1
* 26 + 1, 4 ) );
NumberFormatter.getNumber( 26 * 26 * 26 + 26 * 26 + 26 + 1, 4 ) );
assertEquals(
"azzz",
NumberFormatter.getNumber( 1 * 26 * 26 * 26 + 26 * 26 * 26 + 26
* 26 + 26, 4 ) );
NumberFormatter.getNumber( 26 * 26 * 26 + 26 * 26 * 26 + 26 * 26 + 26, 4 ) );
assertEquals(
"zzzz",
NumberFormatter.getNumber( 26 * 26 * 26 * 26 + 26 * 26 * 26

View File

@ -16,45 +16,47 @@
==================================================================== */
package org.apache.poi.hwpf.converter;
import junit.framework.TestCase;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFTestDataSamples;
import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile;
import static org.junit.Assert.assertTrue;
public class TestWordToTextConverter extends TestCase
{
import org.apache.poi.hwpf.HWPFDocument;
import org.junit.Test;
public class TestWordToTextConverter {
/**
* [FAILING] Bug 47731 - Word Extractor considers text copied from some
* website as an embedded object
*/
public void testBug47731() throws Exception
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "Bug47731.doc" );
String foundText = WordToTextConverter.getText( doc );
@Test
public void testBug47731() throws Exception {
try (HWPFDocument doc = openSampleFile( "Bug47731.doc" )) {
String foundText = WordToTextConverter.getText(doc);
assertTrue( foundText
.contains( "Soak the rice in water for three to four hours" ) );
assertTrue(foundText.contains("Soak the rice in water for three to four hours"));
}
}
public void testBug52311() throws Exception
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "Bug52311.doc" );
String result = WordToTextConverter.getText( doc );
@Test
public void testBug52311() throws Exception {
try (HWPFDocument doc = openSampleFile( "Bug52311.doc" )) {
String result = WordToTextConverter.getText(doc);
assertTrue( result.contains( "2.1\tHeader 2.1" ) );
assertTrue( result.contains( "2.2\tHeader 2.2" ) );
assertTrue( result.contains( "2.3\tHeader 2.3" ) );
assertTrue( result.contains( "2.3.1\tHeader 2.3.1" ) );
assertTrue( result.contains( "2.99\tHeader 2.99" ) );
assertTrue( result.contains( "2.99.1\tHeader 2.99.1" ) );
assertTrue( result.contains( "2.100\tHeader 2.100" ) );
assertTrue( result.contains( "2.101\tHeader 2.101" ) );
assertTrue(result.contains("2.1\tHeader 2.1"));
assertTrue(result.contains("2.2\tHeader 2.2"));
assertTrue(result.contains("2.3\tHeader 2.3"));
assertTrue(result.contains("2.3.1\tHeader 2.3.1"));
assertTrue(result.contains("2.99\tHeader 2.99"));
assertTrue(result.contains("2.99.1\tHeader 2.99.1"));
assertTrue(result.contains("2.100\tHeader 2.100"));
assertTrue(result.contains("2.101\tHeader 2.101"));
}
}
public void testBug53380_3() throws Exception
{
HWPFDocument doc = HWPFTestDataSamples
.openSampleFile( "Bug53380_3.doc" );
WordToTextConverter.getText( doc );
@Test
public void testBug53380_3() throws Exception {
try (HWPFDocument doc = openSampleFile( "Bug53380_3.doc" )) {
WordToTextConverter.getText(doc);
}
}
}

View File

@ -16,81 +16,85 @@
==================================================================== */
package org.apache.poi.hwpf.model;
import org.apache.poi.hwpf.usermodel.Range;
import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile;
import static org.junit.Assert.assertEquals;
import junit.framework.TestCase;
import java.io.IOException;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.junit.Test;
/**
* Test cases for {@link BookmarksTables} and default implementation of
* {@link Bookmarks}
*
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public class TestBookmarksTables extends TestCase
{
public void test()
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" );
Bookmarks bookmarks = doc.getBookmarks();
public class TestBookmarksTables {
@Test
public void test() throws IOException {
try (HWPFDocument doc = openSampleFile( "pageref.doc" )) {
Bookmarks bookmarks = doc.getBookmarks();
assertEquals( 1, bookmarks.getBookmarksCount() );
assertEquals(1, bookmarks.getBookmarksCount());
Bookmark bookmark = bookmarks.getBookmark( 0 );
assertEquals( "userref", bookmark.getName() );
assertEquals( 27, bookmark.getStart() );
assertEquals( 38, bookmark.getEnd() );
Bookmark bookmark = bookmarks.getBookmark(0);
assertEquals("userref", bookmark.getName());
assertEquals(27, bookmark.getStart());
assertEquals(38, bookmark.getEnd());
}
}
public void testDeleteRange()
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" );
Range range = new Range( 27, 41, doc );
range.delete();
@Test
public void testDeleteRange() throws IOException {
try (HWPFDocument doc = openSampleFile( "pageref.doc" )) {
Range range = new Range(27, 41, doc);
range.delete();
assertEquals( 0, doc.getBookmarks().getBookmarksCount() );
assertEquals(0, doc.getBookmarks().getBookmarksCount());
}
}
public void testReplaceTextAfter()
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" );
Bookmark bookmark = doc.getBookmarks().getBookmark( 0 );
Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc );
range.replaceText( "1destin2ation3", true );
@Test
public void testReplaceTextAfter() throws IOException {
try (HWPFDocument doc = openSampleFile( "pageref.doc" )) {
Bookmark bookmark = doc.getBookmarks().getBookmark(0);
Range range = new Range(bookmark.getStart(), bookmark.getEnd(), doc);
range.replaceText("1destin2ation3", true);
bookmark = doc.getBookmarks().getBookmark( 0 );
assertEquals( "userref", bookmark.getName() );
assertEquals( 27, bookmark.getStart() );
assertEquals( 41, bookmark.getEnd() );
bookmark = doc.getBookmarks().getBookmark(0);
assertEquals("userref", bookmark.getName());
assertEquals(27, bookmark.getStart());
assertEquals(41, bookmark.getEnd());
}
}
public void testReplaceTextBefore()
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" );
Bookmark bookmark = doc.getBookmarks().getBookmark( 0 );
Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc );
range.replaceText( "1destin2ation3", false );
@Test
public void testReplaceTextBefore() throws IOException {
try (HWPFDocument doc = openSampleFile( "pageref.doc" )) {
Bookmark bookmark = doc.getBookmarks().getBookmark(0);
Range range = new Range(bookmark.getStart(), bookmark.getEnd(), doc);
range.replaceText("1destin2ation3", false);
bookmark = doc.getBookmarks().getBookmark( 0 );
assertEquals( "userref", bookmark.getName() );
assertEquals( 27, bookmark.getStart() );
assertEquals( 41, bookmark.getEnd() );
bookmark = doc.getBookmarks().getBookmark(0);
assertEquals("userref", bookmark.getName());
assertEquals(27, bookmark.getStart());
assertEquals(41, bookmark.getEnd());
}
}
public void testUpdateText()
{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" );
Bookmark bookmark = doc.getBookmarks().getBookmark( 0 );
Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc );
range.replaceText( "destination", "1destin2ation3" );
@Test
public void testUpdateText() throws IOException {
try (HWPFDocument doc = openSampleFile( "pageref.doc" )) {
Bookmark bookmark = doc.getBookmarks().getBookmark(0);
Range range = new Range(bookmark.getStart(), bookmark.getEnd(), doc);
range.replaceText("destination", "1destin2ation3");
bookmark = doc.getBookmarks().getBookmark( 0 );
assertEquals( "userref", bookmark.getName() );
assertEquals( 27, bookmark.getStart() );
assertEquals( 41, bookmark.getEnd() );
bookmark = doc.getBookmarks().getBookmark(0);
assertEquals("userref", bookmark.getName());
assertEquals(27, bookmark.getStart());
assertEquals(41, bookmark.getEnd());
}
}
}

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