Improvements to OpenXML4J unit tests. Fixed class names. Refactored code for opening test data files. Changed test output to go to temp dir.

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@741002 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Josh Micich 2009-02-05 05:07:23 +00:00
parent d7c95a10c8
commit e6472ffac4
20 changed files with 476 additions and 546 deletions

View File

@ -797,7 +797,6 @@ under the License.
<sysproperty key="OOXML.testdata.path" file="${ooxml.src.test}/org/apache/poi/ooxml/data"/> <sysproperty key="OOXML.testdata.path" file="${ooxml.src.test}/org/apache/poi/ooxml/data"/>
<sysproperty key="openxml4j.compliance.input" file="${ooxml.src.test}/org/apache/poi/openxml4j/opc/compliance/input"/> <sysproperty key="openxml4j.compliance.input" file="${ooxml.src.test}/org/apache/poi/openxml4j/opc/compliance/input"/>
<sysproperty key="openxml4j.testdata.input" file="${ooxml.src.test}/org/apache/poi/openxml4j/opc/INPUT"/> <sysproperty key="openxml4j.testdata.input" file="${ooxml.src.test}/org/apache/poi/openxml4j/opc/INPUT"/>
<sysproperty key="openxml4j.testdata.output" file="${ooxml.src.test}/org/apache/poi/openxml4j/opc/OUTPUT"/>
<sysproperty key="java.awt.headless" value="true"/> <sysproperty key="java.awt.headless" value="true"/>
<formatter type="plain"/> <formatter type="plain"/>
<formatter type="xml"/> <formatter type="xml"/>

View File

@ -0,0 +1,148 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Centralises logic for finding/opening sample files for ooxml4j unit tests
*
* @author jmicich
*/
public final class OpenXML4JTestDataSamples {
private static final String IN_DIR_PROP_NAME = "openxml4j.testdata.input";
private static final String COMP_IN_DIR_PROP_NAME = "openxml4j.compliance.input";
private static File _sampleInputDir;
private static File _sampleOutputDir;
private static File _complianceSampleInputDir;
private OpenXML4JTestDataSamples() {
// no instances of this class
}
public static InputStream openSampleStream(String sampleFileName) {
File f = getSampleFile(sampleFileName);
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public static String getSampleFileName(String sampleFileName) {
// TODO - investigate allowing read/write access for package opened on stream
return getSampleFile(sampleFileName).getAbsolutePath();
}
public static File getSampleFile(String sampleFileName) {
File dir = getSampleInputDir();
File f = new File(dir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Specified sample file '"
+ f.getAbsolutePath() + "' does not exist");
}
if (f.isDirectory()) {
throw new RuntimeException("Specified sample file '"
+ f.getAbsolutePath() + "' is a directory");
}
return f;
}
public static File getOutputFile(String outputFileName) {
File dir = getSampleOutputDir();
return new File(dir, outputFileName);
}
public static InputStream openComplianceSampleStream(String sampleFileName) {
File f = getComplianceSampleFile(sampleFileName);
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private static File getComplianceSampleFile(String sampleFileName) {
File dir = getComplianceSampleInputDir();
File f = new File(dir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Specified sample file '"
+ f.getAbsolutePath() + "' does not exist");
}
if (f.isDirectory()) {
throw new RuntimeException("Specified sample file '"
+ f.getAbsolutePath() + "' is a directory");
}
return f;
}
public static String getComplianceSampleFileName(String sampleFileName) {
return getComplianceSampleFile(sampleFileName).getAbsolutePath();
}
private static File getComplianceSampleInputDir() {
if (_complianceSampleInputDir == null) {
_complianceSampleInputDir = getAndCheckDirByProperty(COMP_IN_DIR_PROP_NAME);
}
return _complianceSampleInputDir;
}
private static File getSampleInputDir() {
if (_sampleInputDir == null) {
_sampleInputDir = getAndCheckDirByProperty(IN_DIR_PROP_NAME);
}
return _sampleInputDir;
}
private static File getAndCheckDirByProperty(String propName) {
String dirName = System.getProperty(propName);
File dir = new File(dirName);
if (!dir.exists()) {
throw new RuntimeException("Specified '" + propName + "' directory: '"
+ dirName + "' does not exist");
}
if (!dir.isDirectory()) {
throw new RuntimeException("Specified '" + propName + "' directory: '"
+ dirName + "' is a not a proper directory");
}
return dir;
}
private static File getSampleOutputDir() {
if (_sampleOutputDir == null) {
File dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
if (dir.exists()) {
if (!dir.isDirectory()) {
throw new RuntimeException("Specified output directory: '"
+ dir.getAbsolutePath() + "' is a not a proper directory");
}
} else {
if (!dir.mkdirs()) {
throw new RuntimeException("Failed to create directory: '"
+ dir.getAbsolutePath() + "'");
}
}
_sampleOutputDir = dir;
}
return _sampleOutputDir;
}
}

View File

@ -1,102 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j;
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* Core helper for tests.
*
* @author Julien Chable
* @version 1.0
*/
public class TestCore {
private String testRootPath; // Test root path
/**
* All sample document are normally located at this place.
*/
private static String pathRootProject; // Project root path
/**
* Demo logger
*/
private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
static {
pathRootProject = System.getProperty("user.dir") + File.separator + "bin";
// Log4j configuration
//PropertyConfigurator.configure(pathRootProject + File.separator
// + "config.log4j");
}
/**
* Constructor. Initialize the demo.
*
*/
public TestCore(Class cl) {
init(cl);
}
/**
* Initialize the test root path
*/
public void init(Class cl) {
String packageName = cl.getPackage().getName();
// replace . by /
String sep = File.separator;
if (sep.equals("\\")) {
sep = "\\\\";
}
testRootPath = pathRootProject + File.separator
+ packageName.replaceAll("\\.", sep)
+ File.separator;
}
// Accessors
/**
* Gets the test root path.
*
* @return The test root path.
*/
public String getTestRootPath() {
return testRootPath;
}
/**
* Sets the test root path.
*
* @param testRoot
*/
public void setTestRootPath(String testRoot) {
this.testRootPath = testRoot;
}
/**
* @return the logger
*/
public static Logger getLogger() {
return logger;
}
}

View File

@ -20,19 +20,25 @@ package org.apache.poi.openxml4j.opc;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
public class AllTests { import org.apache.poi.openxml4j.opc.compliance.AllOpenXML4JComplianceTests;
import org.apache.poi.openxml4j.opc.internal.AllOpenXML4JInternalTests;
public final class AllOpenXML4JTests {
public static Test suite() { public static Test suite() {
TestSuite suite = new TestSuite(
"Functional tests for org.apache.poi.openxml4j.opc"); TestSuite suite = new TestSuite(AllOpenXML4JTests.class.getName());
suite.addTestSuite(TestListParts.class); suite.addTestSuite(TestContentType.class);
suite.addTestSuite(TestFileHelper.class); suite.addTestSuite(TestFileHelper.class);
suite.addTestSuite(TestListParts.class);
suite.addTestSuite(TestPackage.class); suite.addTestSuite(TestPackage.class);
suite.addTestSuite(TestPackageCoreProperties.class); suite.addTestSuite(TestPackageCoreProperties.class);
suite.addTestSuite(TestPackagePartName.class); suite.addTestSuite(TestPackagePartName.class);
suite.addTestSuite(TestPackagingURIHelper.class);
suite.addTestSuite(TestContentType.class);
suite.addTestSuite(TestPackageThumbnail.class); suite.addTestSuite(TestPackageThumbnail.class);
suite.addTestSuite(TestPackagingURIHelper.class);
suite.addTestSuite(TestRelationships.class);
suite.addTest(AllOpenXML4JComplianceTests.suite());
suite.addTest(AllOpenXML4JInternalTests.suite());
return suite; return suite;
} }
} }

View File

@ -17,27 +17,22 @@
package org.apache.poi.openxml4j.opc; package org.apache.poi.openxml4j.opc;
import java.io.File; import java.io.IOException;
import java.io.InputStream;
import java.util.TreeMap; import java.util.TreeMap;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.Package;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.TestCore; public final class TestListParts extends TestCase {
private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
public class TestListParts extends TestCase { private TreeMap<PackagePartName, String> expectedValues;
TestCore testCore = new TestCore(this.getClass()); private TreeMap<PackagePartName, String> values;
TreeMap<PackagePartName, String> expectedValues;
TreeMap<PackagePartName, String> values;
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
@ -86,13 +81,17 @@ public class TestListParts extends TestCase {
* List all parts of a package. * List all parts of a package.
*/ */
public void testListParts() throws InvalidFormatException { public void testListParts() throws InvalidFormatException {
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx");
+ "sample.docx";
Package p = Package.open(filepath, PackageAccess.READ); Package p;
try {
p = Package.open(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (PackagePart part : p.getParts()) { for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType()); values.put(part.getPartName(), part.getContentType());
TestCore.getLogger().debug(part.getPartName()); logger.debug(part.getPartName());
} }
// Compare expected values with values return by the package // Compare expected values with values return by the package

View File

@ -30,33 +30,28 @@ import java.util.TreeMap;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.DocumentHelper; import org.dom4j.DocumentHelper;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.Namespace; import org.dom4j.Namespace;
import org.dom4j.QName; import org.dom4j.QName;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.apache.poi.openxml4j.TestCore; public final class TestPackage extends TestCase {
private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
public class TestPackage extends TestCase {
TestCore testCore = new TestCore(this.getClass());
/** /**
* Test that just opening and closing the file doesn't alter the document. * Test that just opening and closing the file doesn't alter the document.
*/ */
public void testOpenSave() throws Exception { public void testOpenSave() throws Exception {
File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
+ "TestPackageCommon.docx"); File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
File targetFile = new File(System.getProperty("openxml4j.testdata.output")
+ File.separator + "TestPackageOpenSaveTMP.docx");
assertTrue("Source file " + originalFile + " doesn't exist!", originalFile.exists());
Package p = Package.open(originalFile.getAbsolutePath(), Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
PackageAccess.READ_WRITE);
p.save(targetFile.getAbsoluteFile()); p.save(targetFile.getAbsoluteFile());
// Compare the original and newly saved document // Compare the original and newly saved document
@ -70,8 +65,7 @@ public class TestPackage extends TestCase {
* the correct default content types * the correct default content types
*/ */
public void testCreateGetsContentTypes() throws Exception { public void testCreateGetsContentTypes() throws Exception {
File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
+ "TestCreatePackageTMP.docx");
// Zap the target file, in case of an earlier run // Zap the target file, in case of an earlier run
if(targetFile.exists()) targetFile.delete(); if(targetFile.exists()) targetFile.delete();
@ -103,11 +97,9 @@ public class TestPackage extends TestCase {
* Test package creation. * Test package creation.
*/ */
public void testCreatePackageAddPart() throws Exception { public void testCreatePackageAddPart() throws Exception {
File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
+ "TestCreatePackageTMP.docx");
File expectedFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator File expectedFileFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageOUTPUT.docx");
+ "TestCreatePackageOUTPUT.docx");
// Zap the target file, in case of an earlier run // Zap the target file, in case of an earlier run
if(targetFile.exists()) targetFile.delete(); if(targetFile.exists()) targetFile.delete();
@ -208,14 +200,11 @@ public class TestPackage extends TestCase {
* Test package opening. * Test package opening.
*/ */
public void testOpenPackage() throws Exception { public void testOpenPackage() throws Exception {
File targetFile = new File(System.getProperty("openxml4j.testdata.output") File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
+ File.separator + "TestOpenPackageTMP.docx");
File inputFile = new File(System.getProperty("openxml4j.testdata.input") File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
+ File.separator + "TestOpenPackageINPUT.docx");
File expectedFile = new File(System.getProperty("openxml4j.testdata.output") File expectedFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageOUTPUT.docx");
+ File.separator + "TestOpenPackageOUTPUT.docx");
// Copy the input file in the output directory // Copy the input file in the output directory
FileHelper.copyFile(inputFile, targetFile); FileHelper.copyFile(inputFile, targetFile);
@ -271,14 +260,10 @@ public class TestPackage extends TestCase {
* to a file * to a file
*/ */
public void testSaveToOutputStream() throws Exception { public void testSaveToOutputStream() throws Exception {
File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
+ "TestPackageCommon.docx"); File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator
+ "TestPackageOpenSaveTMP.docx");
assertTrue("Source file " + originalFile + " doesn't exist!", originalFile.exists());
Package p = Package.open(originalFile.getAbsolutePath(), Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
PackageAccess.READ_WRITE);
FileOutputStream fout = new FileOutputStream(targetFile); FileOutputStream fout = new FileOutputStream(targetFile);
p.save(fout); p.save(fout);
fout.close(); fout.close();
@ -295,9 +280,7 @@ public class TestPackage extends TestCase {
* reading from a file * reading from a file
*/ */
public void testOpenFromInputStream() throws Exception { public void testOpenFromInputStream() throws Exception {
File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
+ "TestPackageCommon.docx");
assertTrue("Source file " + originalFile + " doesn't exist!", originalFile.exists());
FileInputStream finp = new FileInputStream(originalFile); FileInputStream finp = new FileInputStream(originalFile);
@ -313,18 +296,14 @@ public class TestPackage extends TestCase {
} }
/** /**
* TODO: fix and unable * TODO: fix and enable
*/ */
public void disabled_testRemovePartRecursive() throws Exception { public void disabled_testRemovePartRecursive() throws Exception {
File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
+ "TestPackageCommon.docx"); File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
+ "TestPackageRemovePartRecursiveOUTPUT.docx");
File tempFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator
+ "TestPackageRemovePartRecursiveTMP.docx");
Package p = Package.open(originalFile.getAbsolutePath(), Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
PackageAccess.READ_WRITE);
p.removePartRecursive(PackagingURIHelper.createPartName(new URI( p.removePartRecursive(PackagingURIHelper.createPartName(new URI(
"/word/document.xml"))); "/word/document.xml")));
p.save(tempFile.getAbsoluteFile()); p.save(tempFile.getAbsoluteFile());
@ -372,8 +351,7 @@ public class TestPackage extends TestCase {
.createPartName("/word/webSettings.xml"), .createPartName("/word/webSettings.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
+ "sample.docx";
Package p = Package.open(filepath, PackageAccess.READ_WRITE); Package p = Package.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part // Remove the core part
@ -381,7 +359,7 @@ public class TestPackage extends TestCase {
for (PackagePart part : p.getParts()) { for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType()); values.put(part.getPartName(), part.getContentType());
TestCore.getLogger().debug(part.getPartName()); logger.debug(part.getPartName());
} }
// Compare expected values with values return by the package // Compare expected values with values return by the package
@ -389,7 +367,7 @@ public class TestPackage extends TestCase {
assertNotNull(values.get(partName)); assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName)); assertEquals(expectedValues.get(partName), values.get(partName));
} }
// Don't save modfications // Don't save modifications
p.revert(); p.revert();
} }
@ -411,8 +389,7 @@ public class TestPackage extends TestCase {
.createPartName("/docProps/core.xml"), .createPartName("/docProps/core.xml"),
"application/vnd.openxmlformats-package.core-properties+xml"); "application/vnd.openxmlformats-package.core-properties+xml");
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
+ "sample.docx";
Package p = Package.open(filepath, PackageAccess.READ_WRITE); Package p = Package.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part // Remove the core part
@ -420,7 +397,7 @@ public class TestPackage extends TestCase {
for (PackagePart part : p.getParts()) { for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType()); values.put(part.getPartName(), part.getContentType());
TestCore.getLogger().debug(part.getPartName()); logger.debug(part.getPartName());
} }
// Compare expected values with values return by the package // Compare expected values with values return by the package
@ -428,7 +405,7 @@ public class TestPackage extends TestCase {
assertNotNull(values.get(partName)); assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName)); assertEquals(expectedValues.get(partName), values.get(partName));
} }
// Don't save modfications // Don't save modifications
p.revert(); p.revert();
} }

View File

@ -18,22 +18,20 @@
package org.apache.poi.openxml4j.opc; package org.apache.poi.openxml4j.opc;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.text.ParsePosition; import java.text.ParsePosition;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.util.Nullable; import org.apache.poi.openxml4j.util.Nullable;
import org.apache.poi.openxml4j.TestCore; public final class TestPackageCoreProperties extends TestCase {
import org.apache.log4j.Logger;
public class TestPackageCoreProperties extends TestCase {
TestCore testCore = new TestCore(this.getClass());
/** /**
* Test package core properties getters. * Test package core properties getters.
@ -41,13 +39,14 @@ public class TestPackageCoreProperties extends TestCase {
public void testGetProperties() { public void testGetProperties() {
try { try {
// Open the package // Open the package
Package p = Package.open(System.getProperty("openxml4j.testdata.input") + File.separator Package p = Package.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx"));
+ "TestPackageCoreProperiesGetters.docx",
PackageAccess.READ);
compareProperties(p); compareProperties(p);
p.revert(); p.revert();
} catch (OpenXML4JException e) { } catch (OpenXML4JException e) {
Logger.getLogger("org.apache.poi.openxml4j.demo").debug(e.getMessage()); Logger.getLogger("org.apache.poi.openxml4j.demo").debug(e.getMessage());
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} }
} }
@ -55,11 +54,9 @@ public class TestPackageCoreProperties extends TestCase {
* Test package core properties setters. * Test package core properties setters.
*/ */
public void testSetProperties() throws Exception { public void testSetProperties() throws Exception {
String inputPath = System.getProperty("openxml4j.testdata.input") String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx");
+ File.separator + "TestPackageCoreProperiesSetters.docx";
String outputFilename = System.getProperty("openxml4j.testdata.input") File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx");
+ File.separator + "TestPackageCoreProperiesSettersOUTPUT.docx";
// Open package // Open package
Package p = Package.open(inputPath, PackageAccess.READ_WRITE); Package p = Package.open(inputPath, PackageAccess.READ_WRITE);
@ -86,14 +83,13 @@ public class TestPackageCoreProperties extends TestCase {
props.setSubjectProperty("MySubject"); props.setSubjectProperty("MySubject");
props.setVersionProperty("2"); props.setVersionProperty("2");
// Save the package in the output directory // Save the package in the output directory
p.save(new File(outputFilename)); p.save(outputFile);
// Open the newly created file to check core properties saved values. // Open the newly created file to check core properties saved values.
File fOut = new File(outputFilename); Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ);
Package p2 = Package.open(outputFilename, PackageAccess.READ);
compareProperties(p2); compareProperties(p2);
p2.revert(); p2.revert();
fOut.delete(); outputFile.delete();
} }
private void compareProperties(Package p) throws InvalidFormatException { private void compareProperties(Package p) throws InvalidFormatException {

View File

@ -21,47 +21,37 @@ import java.io.File;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.openxml4j.opc.Package; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.TestCore;
/** /**
* Test the addition of thumbnail in a package. * Test the addition of thumbnail in a package.
* *
* @author Julien Chable * @author Julien Chable
*/ */
public class TestPackageThumbnail extends TestCase { public final class TestPackageThumbnail extends TestCase {
TestCore testCore = new TestCore(this.getClass());
/** /**
* Test package addThumbnail() method. * Test package addThumbnail() method.
*/ */
public void testSetProperties() throws Exception { public void testSetProperties() throws Exception {
String inputPath = System.getProperty("openxml4j.testdata.input") String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx");
+ File.separator + "TestPackageThumbnail.docx";
String imagePath = System.getProperty("openxml4j.testdata.input") String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg");
+ File.separator + "thumbnail.jpg";
String outputFilename = System.getProperty("openxml4j.testdata.output") File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx");
+ File.separator + "TestPackageThumbnailOUTPUT.docx";
// Open package // Open package
Package p = Package.open(inputPath, PackageAccess.READ_WRITE); Package p = Package.open(inputPath, PackageAccess.READ_WRITE);
p.addThumbnail(imagePath); p.addThumbnail(imagePath);
// Save the package in the output directory // Save the package in the output directory
p.save(new File(outputFilename)); p.save(outputFile);
// Open the newly created file to check core properties saved values. // Open the newly created file to check core properties saved values.
File fOut = new File(outputFilename); Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ);
Package p2 = Package.open(outputFilename, PackageAccess.READ);
if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
.size() == 0) .size() == 0)
fail("Thumbnail not added to the package !"); fail("Thumbnail not added to the package !");
p2.revert(); p2.revert();
//fOut.delete(); outputFile.delete();
} }
} }

View File

@ -19,32 +19,23 @@ package org.apache.poi.openxml4j.opc;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.openxml4j.opc.Package; import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.openxml4j.TestCore;
public class TestRelationships extends TestCase { public class TestRelationships extends TestCase {
public static final String HYPERLINK_REL_TYPE = private static final String HYPERLINK_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
public static final String COMMENTS_REL_TYPE = private static final String COMMENTS_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
public static final String SHEET_WITH_COMMENTS = private static final String SHEET_WITH_COMMENTS =
"/xl/worksheets/sheet1.xml"; "/xl/worksheets/sheet1.xml";
TestCore testCore = new TestCore(this.getClass()); private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
/** /**
* Test relationships are correctly loaded. This at the moment fails (as of r499) * Test relationships are correctly loaded. This at the moment fails (as of r499)
@ -53,10 +44,9 @@ public class TestRelationships extends TestCase {
* really look also for not yet loaded parts. * really look also for not yet loaded parts.
*/ */
public void testLoadRelationships() throws Exception { public void testLoadRelationships() throws Exception {
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx");
+ "sample.xlsx"; Package pkg = Package.open(is);
Package pkg = Package.open(filepath, PackageAccess.READ); logger.debug("1: " + pkg);
TestCore.getLogger().debug("1: " + pkg);
PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
PackageRelationship coreDocRelationship = rels.getRelationship(0); PackageRelationship coreDocRelationship = rels.getRelationship(0);
PackagePart corePart = pkg.getPart(coreDocRelationship); PackagePart corePart = pkg.getPart(coreDocRelationship);
@ -75,10 +65,8 @@ public class TestRelationships extends TestCase {
* type, then grab from within there by id * type, then grab from within there by id
*/ */
public void testFetchFromCollection() throws Exception { public void testFetchFromCollection() throws Exception {
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx");
+ "ExcelWithHyperlinks.xlsx"; Package pkg = Package.open(is);
Package pkg = Package.open(filepath, PackageAccess.READ);
PackagePart sheet = pkg.getPart( PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
assertNotNull(sheet); assertNotNull(sheet);
@ -118,10 +106,8 @@ public class TestRelationships extends TestCase {
* external hyperlinks. Check we can load these ok. * external hyperlinks. Check we can load these ok.
*/ */
public void testLoadExcelHyperlinkRelations() throws Exception { public void testLoadExcelHyperlinkRelations() throws Exception {
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx");
+ "ExcelWithHyperlinks.xlsx"; Package pkg = Package.open(is);
Package pkg = Package.open(filepath, PackageAccess.READ);
PackagePart sheet = pkg.getPart( PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
assertNotNull(sheet); assertNotNull(sheet);
@ -150,13 +136,11 @@ public class TestRelationships extends TestCase {
/* /*
* 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 create these ok, * external hyperlinks. Check we can create these OK,
* then still read them later * then still read them later
*/ */
public void testCreateExcelHyperlinkRelations() throws Exception { public void testCreateExcelHyperlinkRelations() throws Exception {
String filepath = System.getProperty("openxml4j.testdata.input") + File.separator String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx");
+ "ExcelWithHyperlinks.xlsx";
Package pkg = Package.open(filepath, PackageAccess.READ_WRITE); Package pkg = Package.open(filepath, PackageAccess.READ_WRITE);
PackagePart sheet = pkg.getPart( PackagePart sheet = pkg.getPart(
PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));

View File

@ -20,16 +20,13 @@ package org.apache.poi.openxml4j.opc.compliance;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
public class AllTests { public class AllOpenXML4JComplianceTests {
public static Test suite() { public static Test suite() {
TestSuite suite = new TestSuite( TestSuite suite = new TestSuite(AllOpenXML4JComplianceTests.class.getName());
"Test for test.org.apache.poi.openxml4j.opc.compliance"); suite.addTestSuite(TestOPCCompliancePartName.class);
// $JUnit-BEGIN$ suite.addTestSuite(TestOPCComplianceCoreProperties.class);
suite.addTestSuite(OPCCompliance_PartName.class); suite.addTestSuite(TestOPCCompliancePackageModel.class);
suite.addTestSuite(OPCCompliance_CoreProperties.class);
suite.addTestSuite(OPCCompliance_PackageModel.class);
// $JUnit-END$
return suite; return suite;
} }

View File

@ -1,258 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j.opc.compliance;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.Package;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.openxml4j.TestCore;
import junit.framework.TestCase;
/**
* 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.
*
* 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
* @version 1.0
*/
public class OPCCompliance_CoreProperties extends TestCase {
TestCore testCore = new TestCore(this.getClass());
public void testCorePropertiesPart() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
} catch (InvalidFormatException e) {
fail("OPC compliance failure: the core properties is considered as invalid than it's not !");
} finally {
pkg.revert();
}
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.1 -> A format consumer shall consider more than one core properties relationship for a package to be an error.");
} catch (InvalidFormatException e) {
// DO nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart_AddRelationship() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.testdata.input")
+ File.separator
+ "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
pkg = Package.open(filepath);
pkg.addRelationship(PackagingURIHelper.createPartName(new URI(
"/docProps/core2.xml")), TargetMode.INTERNAL,
PackageRelationshipTypes.CORE_PROPERTIES);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.1 -> A format consumer shall consider more than one core properties relationship for a package to be an error.");
} catch (InvalidOperationException e) {
// Do nothing, it's the normal behavior
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} catch (URISyntaxException e) {
// Should never happen
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart_AddPart() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.testdata.input")
+ File.separator
+ "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
pkg = Package.open(filepath);
pkg.createPart(PackagingURIHelper.createPartName(new URI(
"/docProps/core2.xml")), ContentTypes.CORE_PROPERTIES_PART);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.1 -> A format consumer shall consider more than one core properties relationship for a package to be an error.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} catch (InvalidOperationException e) {
// Do nothing, it's the normal behavior
} catch (URISyntaxException e) {
// Should never happen
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.2 rule.
*/
public void testDoNotUseCompatibilityMarkup() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.2 -> A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.3 rule.
*/
public void testDCTermsNamespaceLimitedUse() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: 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.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.4 rule.
*/
public void testUnauthorizedXMLLangAttribute() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.4 -> 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.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.5 rule.
*/
public void testLimitedXSITypeAttribute_NotPresent() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.5 -> 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.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
/**
* Test M4.5 rule.
*/
public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() {
Package pkg = null;
try {
String filepath = System.getProperty("openxml4j.compliance.input")
+ File.separator
+ "OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx";
pkg = Package.open(filepath);
// Normally must thrown an InvalidFormatException exception.
fail("OPC compliance failure: M4.5 -> 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.");
} catch (InvalidFormatException e) {
// Do nothing, it's the normal behavior
} finally {
if (pkg != null)
pkg.revert();
}
}
}

View File

@ -0,0 +1,208 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j.opc.compliance;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
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;
import org.apache.poi.openxml4j.opc.Package;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
/**
* 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.
*
* 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 extends TestCase {
public void testCorePropertiesPart() {
Package pkg;
try {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
pkg = Package.open(is);
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
pkg.revert();
}
private static String extractInvalidFormatMessage(String sampleNameSuffix) {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
Package pkg;
try {
pkg = Package.open(is);
} catch (InvalidFormatException e) {
// expected during successful test
return e.getMessage();
} catch (IOException e) {
throw new RuntimeException(e);
}
pkg.revert();
// Normally must thrown an InvalidFormatException exception.
throw new AssertionFailedError("expected OPC compliance exception was not thrown");
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart() {
String msg = extractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx");
assertEquals("OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !", msg);
}
private static URI createURI(String text) {
try {
return new URI(text);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart_AddRelationship() {
InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
Package pkg;
try {
pkg = Package.open(is);
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
URI partUri = createURI("/docProps/core2.xml");
try {
pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL,
PackageRelationshipTypes.CORE_PROPERTIES);
fail("expected OPC compliance exception was not thrown");
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} catch (InvalidOperationException e) {
// expected during successful test
assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage());
}
pkg.revert();
}
/**
* Test M4.1 rule.
*/
public void testOnlyOneCorePropertiesPart_AddPart() {
String sampleFileName = OpenXML4JTestDataSamples.getComplianceSampleFileName("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
Package pkg = null;
try {
pkg = Package.open(sampleFileName);
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
}
URI partUri = createURI("/docProps/core2.xml");
try {
pkg.createPart(PackagingURIHelper.createPartName(partUri),
ContentTypes.CORE_PROPERTIES_PART);
fail("expected OPC compliance exception was not thrown");
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
} catch (InvalidOperationException e) {
// expected during successful test
assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage());
}
pkg.revert();
}
/**
* Test M4.2 rule.
*/
public void testDoNotUseCompatibilityMarkup() {
String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx");
assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg);
}
/**
* Test M4.3 rule.
*/
public void testDCTermsNamespaceLimitedUse() {
String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx");
assertEquals("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
/**
* Test M4.4 rule.
*/
public void testUnauthorizedXMLLangAttribute() {
String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx");
assertEquals("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
/**
* Test M4.5 rule.
*/
public void testLimitedXSITypeAttribute_NotPresent() {
String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx");
assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg);
}
/**
* Test M4.5 rule.
*/
public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() {
String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx");
assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF' !", msg);
}
}

View File

@ -30,8 +30,6 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.openxml4j.TestCore;
/** /**
* Test Open Packaging Convention package model compliance. * Test Open Packaging Convention package model compliance.
* *
@ -40,11 +38,9 @@ import org.apache.poi.openxml4j.TestCore;
* *
* @author Julien Chable * @author Julien Chable
*/ */
public class OPCCompliance_PackageModel extends TestCase { public class TestOPCCompliancePackageModel extends TestCase {
TestCore testCore = new TestCore(this.getClass()); public TestOPCCompliancePackageModel(String name) {
public OPCCompliance_PackageModel(String name) {
super(name); super(name);
} }
@ -54,9 +50,8 @@ public class OPCCompliance_PackageModel extends TestCase {
* [M1.11] * [M1.11]
*/ */
public void testPartNameDerivationAdditionFailure() { public void testPartNameDerivationAdditionFailure() {
Package pkg = null; Package pkg = Package.create("TODELETEIFEXIST.docx");
try { try {
pkg = Package.create("TODELETEIFEXIST.docx");
PackagePartName name = PackagingURIHelper PackagePartName name = PackagingURIHelper
.createPartName("/word/document.xml"); .createPartName("/word/document.xml");
PackagePartName nameDerived = PackagingURIHelper PackagePartName nameDerived = PackagingURIHelper

View File

@ -78,9 +78,9 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper;
* @author Julien Chable * @author Julien Chable
* @version 1.0 * @version 1.0
*/ */
public class OPCCompliance_PartName extends TestCase { public class TestOPCCompliancePartName extends TestCase {
public OPCCompliance_PartName(String name) { public TestOPCCompliancePartName(String name) {
super(name); super(name);
} }

View File

@ -20,14 +20,11 @@ package org.apache.poi.openxml4j.opc.internal;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
public class AllTests { public class AllOpenXML4JInternalTests {
public static Test suite() { public static Test suite() {
TestSuite suite = new TestSuite( TestSuite suite = new TestSuite(AllOpenXML4JInternalTests.class.getName());
"Test for test.org.apache.poi.openxml4j.opc.internal");
//$JUnit-BEGIN$
suite.addTestSuite(TestContentTypeManager.class); suite.addTestSuite(TestContentTypeManager.class);
//$JUnit-END$
return suite; return suite;
} }
} }

View File

@ -21,15 +21,9 @@ import junit.framework.TestCase;
import org.apache.poi.openxml4j.opc.PackagePartName; import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;
import org.apache.poi.openxml4j.TestCore;
public class TestContentTypeManager extends TestCase { public class TestContentTypeManager extends TestCase {
TestCore testCore = new TestCore(this.getClass());
/** /**
* Test the properties part content parsing. * Test the properties part content parsing.
*/ */

View File

@ -62,10 +62,10 @@ public final class TestExcelExtractor extends TestCase {
assertEquals( assertEquals(
"Sheet1\n" + "Sheet1\n" +
"1000.0\t1.0\t5.0\n" + "1000.0\t1.0\t5.0\n" +
"2000.0\t2.0\t\n" + "2000.0\t2.0\n" +
"3000.0\t3.0\t\n" + "3000.0\t3.0\n" +
"4000.0\t4.0\t\n" + "4000.0\t4.0\n" +
"5000.0\t5.0\t\n" + "5000.0\t5.0\n" +
"Sheet2\nSheet3\n", "Sheet2\nSheet3\n",
extractor.getText() extractor.getText()
); );
@ -75,10 +75,10 @@ public final class TestExcelExtractor extends TestCase {
assertEquals( assertEquals(
"Sheet1\n" + "Sheet1\n" +
"1000.0\t1.0\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + "1000.0\t1.0\tSUMIF(A1:A5,\">4000\",B1:B5)\n" +
"2000.0\t2.0\t\n" + "2000.0\t2.0\n" +
"3000.0\t3.0\t\n" + "3000.0\t3.0\n" +
"4000.0\t4.0\t\n" + "4000.0\t4.0\n" +
"5000.0\t5.0\t\n" + "5000.0\t5.0\n" +
"Sheet2\nSheet3\n", "Sheet2\nSheet3\n",
extractor.getText() extractor.getText()
); );
@ -196,15 +196,15 @@ public final class TestExcelExtractor extends TestCase {
assertTrue(def.startsWith( assertTrue(def.startsWith(
"Sheet1\n" + "Sheet1\n" +
"&[TAB]\t\n" + "&[TAB]\t\n" +
"Hello\t\n" + "Hello\n" +
"11.0\t23.0\t\n" "11.0\t23.0\n"
)); ));
assertTrue(padded.startsWith( assertTrue(padded.startsWith(
"Sheet1\n" + "Sheet1\n" +
"&[TAB]\t\n" + "&[TAB]\t\n" +
"Hello\t\t\t\t\t\t\t\t\t\t\t\n" + "Hello\n" +
"11.0\t\t\t23.0\t\t\t\t\t\t\t\t\n" "11.0\t\t\t23.0\n"
)); ));
} }