From: Josh Micich Date: Thu, 5 Feb 2009 05:07:23 +0000 (+0000) Subject: Improvements to OpenXML4J unit tests. Fixed class names. Refactored code for opening... X-Git-Tag: REL_3_5_BETA5~8 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=ba79578f0f359d59d22745a8d181ac371c9c41e8;p=poi.git 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 --- diff --git a/build.xml b/build.xml index c04db3d0e0..bf960aa88e 100644 --- a/build.xml +++ b/build.xml @@ -797,7 +797,6 @@ under the License. - diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java new file mode 100755 index 0000000000..62291d37bd --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java @@ -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; + } + +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/TestCore.java b/src/ooxml/testcases/org/apache/poi/openxml4j/TestCore.java deleted file mode 100755 index 26bf0ce0fe..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/TestCore.java +++ /dev/null @@ -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; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java new file mode 100755 index 0000000000..12bc3888b2 --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java @@ -0,0 +1,44 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +package org.apache.poi.openxml4j.opc; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.poi.openxml4j.opc.compliance.AllOpenXML4JComplianceTests; +import org.apache.poi.openxml4j.opc.internal.AllOpenXML4JInternalTests; + +public final class AllOpenXML4JTests { + + public static Test suite() { + + TestSuite suite = new TestSuite(AllOpenXML4JTests.class.getName()); + suite.addTestSuite(TestContentType.class); + suite.addTestSuite(TestFileHelper.class); + suite.addTestSuite(TestListParts.class); + suite.addTestSuite(TestPackage.class); + suite.addTestSuite(TestPackageCoreProperties.class); + suite.addTestSuite(TestPackagePartName.class); + suite.addTestSuite(TestPackageThumbnail.class); + suite.addTestSuite(TestPackagingURIHelper.class); + suite.addTestSuite(TestRelationships.class); + suite.addTest(AllOpenXML4JComplianceTests.suite()); + suite.addTest(AllOpenXML4JInternalTests.suite()); + return suite; + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllTests.java deleted file mode 100755 index 4b2cc45a56..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllTests.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class AllTests { - - public static Test suite() { - TestSuite suite = new TestSuite( - "Functional tests for org.apache.poi.openxml4j.opc"); - suite.addTestSuite(TestListParts.class); - suite.addTestSuite(TestFileHelper.class); - suite.addTestSuite(TestPackage.class); - suite.addTestSuite(TestPackageCoreProperties.class); - suite.addTestSuite(TestPackagePartName.class); - suite.addTestSuite(TestPackagingURIHelper.class); - suite.addTestSuite(TestContentType.class); - suite.addTestSuite(TestPackageThumbnail.class); - return suite; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestCreatePackageOUTPUT.docx b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestCreatePackageOUTPUT.docx deleted file mode 100755 index 3da1daeb98..0000000000 Binary files a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestCreatePackageOUTPUT.docx and /dev/null differ diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageRemovePartRecursiveTMP.docx b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageRemovePartRecursiveTMP.docx deleted file mode 100755 index c8c43dce69..0000000000 Binary files a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageRemovePartRecursiveTMP.docx and /dev/null differ diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageThumbnailOUTPUT.docx b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageThumbnailOUTPUT.docx deleted file mode 100755 index a41daa5ec5..0000000000 Binary files a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/OUTPUT/TestPackageThumbnailOUTPUT.docx and /dev/null differ diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java index 359c02faf8..c35f57833e 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java @@ -17,27 +17,22 @@ package org.apache.poi.openxml4j.opc; -import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.util.TreeMap; 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.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 expectedValues; - TestCore testCore = new TestCore(this.getClass()); - - TreeMap expectedValues; - - TreeMap values; + private TreeMap values; @Override protected void setUp() throws Exception { @@ -86,13 +81,17 @@ public class TestListParts extends TestCase { * List all parts of a package. */ public void testListParts() throws InvalidFormatException { - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "sample.docx"; + InputStream is = OpenXML4JTestDataSamples.openSampleStream("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()) { values.put(part.getPartName(), part.getContentType()); - TestCore.getLogger().debug(part.getPartName()); + logger.debug(part.getPartName()); } // Compare expected values with values return by the package diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java index 8d4e3313e2..0b95bbe119 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java @@ -30,33 +30,28 @@ import java.util.TreeMap; 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.DocumentHelper; import org.dom4j.Element; import org.dom4j.Namespace; 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 class TestPackage extends TestCase { - - TestCore testCore = new TestCore(this.getClass()); +public final class TestPackage extends TestCase { + private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test"); /** * Test that just opening and closing the file doesn't alter the document. */ public void testOpenSave() throws Exception { - File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator - + "TestPackageCommon.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(), - PackageAccess.READ_WRITE); + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); + + Package p = Package.open(originalFile, PackageAccess.READ_WRITE); p.save(targetFile.getAbsoluteFile()); // Compare the original and newly saved document @@ -70,8 +65,7 @@ public class TestPackage extends TestCase { * the correct default content types */ public void testCreateGetsContentTypes() throws Exception { - File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator - + "TestCreatePackageTMP.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); // Zap the target file, in case of an earlier run if(targetFile.exists()) targetFile.delete(); @@ -103,11 +97,9 @@ public class TestPackage extends TestCase { * Test package creation. */ public void testCreatePackageAddPart() throws Exception { - File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator - + "TestCreatePackageTMP.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); - File expectedFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator - + "TestCreatePackageOUTPUT.docx"); + File expectedFileFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageOUTPUT.docx"); // Zap the target file, in case of an earlier run if(targetFile.exists()) targetFile.delete(); @@ -208,14 +200,11 @@ public class TestPackage extends TestCase { * Test package opening. */ public void testOpenPackage() throws Exception { - File targetFile = new File(System.getProperty("openxml4j.testdata.output") - + File.separator + "TestOpenPackageTMP.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx"); - File inputFile = new File(System.getProperty("openxml4j.testdata.input") - + File.separator + "TestOpenPackageINPUT.docx"); + File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx"); - File expectedFile = new File(System.getProperty("openxml4j.testdata.output") - + File.separator + "TestOpenPackageOUTPUT.docx"); + File expectedFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageOUTPUT.docx"); // Copy the input file in the output directory FileHelper.copyFile(inputFile, targetFile); @@ -271,14 +260,10 @@ public class TestPackage extends TestCase { * to a file */ public void testSaveToOutputStream() throws Exception { - File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator - + "TestPackageCommon.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(), - PackageAccess.READ_WRITE); + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); + + Package p = Package.open(originalFile, PackageAccess.READ_WRITE); FileOutputStream fout = new FileOutputStream(targetFile); p.save(fout); fout.close(); @@ -295,9 +280,7 @@ public class TestPackage extends TestCase { * reading from a file */ public void testOpenFromInputStream() throws Exception { - File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator - + "TestPackageCommon.docx"); - assertTrue("Source file " + originalFile + " doesn't exist!", originalFile.exists()); + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); 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 { - File originalFile = new File(System.getProperty("openxml4j.testdata.input") + File.separator - + "TestPackageCommon.docx"); - File targetFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator - + "TestPackageRemovePartRecursiveOUTPUT.docx"); - File tempFile = new File(System.getProperty("openxml4j.testdata.output") + File.separator - + "TestPackageRemovePartRecursiveTMP.docx"); - - Package p = Package.open(originalFile.getAbsolutePath(), - PackageAccess.READ_WRITE); + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); + File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); + + Package p = Package.open(originalFile, PackageAccess.READ_WRITE); p.removePartRecursive(PackagingURIHelper.createPartName(new URI( "/word/document.xml"))); p.save(tempFile.getAbsoluteFile()); @@ -372,8 +351,7 @@ public class TestPackage extends TestCase { .createPartName("/word/webSettings.xml"), "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "sample.docx"; + String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); Package p = Package.open(filepath, PackageAccess.READ_WRITE); // Remove the core part @@ -381,7 +359,7 @@ public class TestPackage extends TestCase { for (PackagePart part : p.getParts()) { values.put(part.getPartName(), part.getContentType()); - TestCore.getLogger().debug(part.getPartName()); + logger.debug(part.getPartName()); } // Compare expected values with values return by the package @@ -389,7 +367,7 @@ public class TestPackage extends TestCase { assertNotNull(values.get(partName)); assertEquals(expectedValues.get(partName), values.get(partName)); } - // Don't save modfications + // Don't save modifications p.revert(); } @@ -411,8 +389,7 @@ public class TestPackage extends TestCase { .createPartName("/docProps/core.xml"), "application/vnd.openxmlformats-package.core-properties+xml"); - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "sample.docx"; + String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); Package p = Package.open(filepath, PackageAccess.READ_WRITE); // Remove the core part @@ -420,7 +397,7 @@ public class TestPackage extends TestCase { for (PackagePart part : p.getParts()) { values.put(part.getPartName(), part.getContentType()); - TestCore.getLogger().debug(part.getPartName()); + logger.debug(part.getPartName()); } // Compare expected values with values return by the package @@ -428,7 +405,7 @@ public class TestPackage extends TestCase { assertNotNull(values.get(partName)); assertEquals(expectedValues.get(partName), values.get(partName)); } - // Don't save modfications + // Don't save modifications p.revert(); } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java index acb7cd84f4..54e21b89d3 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java @@ -18,22 +18,20 @@ package org.apache.poi.openxml4j.opc; import java.io.File; +import java.io.IOException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; 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.OpenXML4JException; import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.openxml4j.TestCore; -import org.apache.log4j.Logger; - -public class TestPackageCoreProperties extends TestCase { - - TestCore testCore = new TestCore(this.getClass()); +public final class TestPackageCoreProperties extends TestCase { /** * Test package core properties getters. @@ -41,13 +39,14 @@ public class TestPackageCoreProperties extends TestCase { public void testGetProperties() { try { // Open the package - Package p = Package.open(System.getProperty("openxml4j.testdata.input") + File.separator - + "TestPackageCoreProperiesGetters.docx", - PackageAccess.READ); + Package p = Package.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx")); compareProperties(p); p.revert(); } catch (OpenXML4JException e) { 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. */ public void testSetProperties() throws Exception { - String inputPath = System.getProperty("openxml4j.testdata.input") - + File.separator + "TestPackageCoreProperiesSetters.docx"; + String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx"); - String outputFilename = System.getProperty("openxml4j.testdata.input") - + File.separator + "TestPackageCoreProperiesSettersOUTPUT.docx"; + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); // Open package Package p = Package.open(inputPath, PackageAccess.READ_WRITE); @@ -86,14 +83,13 @@ public class TestPackageCoreProperties extends TestCase { props.setSubjectProperty("MySubject"); props.setVersionProperty("2"); // 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. - File fOut = new File(outputFilename); - Package p2 = Package.open(outputFilename, PackageAccess.READ); + Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ); compareProperties(p2); p2.revert(); - fOut.delete(); + outputFile.delete(); } private void compareProperties(Package p) throws InvalidFormatException { diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java index bbf5402f48..a7b9e7b6f6 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java @@ -21,47 +21,37 @@ import java.io.File; import junit.framework.TestCase; -import org.apache.poi.openxml4j.opc.Package; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; - -import org.apache.poi.openxml4j.TestCore; +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; /** * Test the addition of thumbnail in a package. * * @author Julien Chable */ -public class TestPackageThumbnail extends TestCase { - - TestCore testCore = new TestCore(this.getClass()); +public final class TestPackageThumbnail extends TestCase { /** * Test package addThumbnail() method. */ public void testSetProperties() throws Exception { - String inputPath = System.getProperty("openxml4j.testdata.input") - + File.separator + "TestPackageThumbnail.docx"; + String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); - String imagePath = System.getProperty("openxml4j.testdata.input") - + File.separator + "thumbnail.jpg"; + String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); - String outputFilename = System.getProperty("openxml4j.testdata.output") - + File.separator + "TestPackageThumbnailOUTPUT.docx"; + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); // Open package Package p = Package.open(inputPath, PackageAccess.READ_WRITE); p.addThumbnail(imagePath); // 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. - File fOut = new File(outputFilename); - Package p2 = Package.open(outputFilename, PackageAccess.READ); + Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ); if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) .size() == 0) fail("Thumbnail not added to the package !"); p2.revert(); - //fOut.delete(); + outputFile.delete(); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java index 3ca1281033..972bd268a3 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -19,32 +19,23 @@ package org.apache.poi.openxml4j.opc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; +import java.io.InputStream; import junit.framework.TestCase; -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.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; +import org.apache.log4j.Logger; +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; 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"; - public static final String COMMENTS_REL_TYPE = + private static final String COMMENTS_REL_TYPE = "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"; - 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) @@ -53,10 +44,9 @@ public class TestRelationships extends TestCase { * really look also for not yet loaded parts. */ public void testLoadRelationships() throws Exception { - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "sample.xlsx"; - Package pkg = Package.open(filepath, PackageAccess.READ); - TestCore.getLogger().debug("1: " + pkg); + InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx"); + Package pkg = Package.open(is); + logger.debug("1: " + pkg); PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); PackageRelationship coreDocRelationship = rels.getRelationship(0); PackagePart corePart = pkg.getPart(coreDocRelationship); @@ -75,10 +65,8 @@ public class TestRelationships extends TestCase { * type, then grab from within there by id */ public void testFetchFromCollection() throws Exception { - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "ExcelWithHyperlinks.xlsx"; - - Package pkg = Package.open(filepath, PackageAccess.READ); + InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); + Package pkg = Package.open(is); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertNotNull(sheet); @@ -118,10 +106,8 @@ public class TestRelationships extends TestCase { * external hyperlinks. Check we can load these ok. */ public void testLoadExcelHyperlinkRelations() throws Exception { - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "ExcelWithHyperlinks.xlsx"; - - Package pkg = Package.open(filepath, PackageAccess.READ); + InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); + Package pkg = Package.open(is); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertNotNull(sheet); @@ -150,13 +136,11 @@ public class TestRelationships extends TestCase { /* * 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 */ public void testCreateExcelHyperlinkRelations() throws Exception { - String filepath = System.getProperty("openxml4j.testdata.input") + File.separator - + "ExcelWithHyperlinks.xlsx"; - + String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); Package pkg = Package.open(filepath, PackageAccess.READ_WRITE); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllOpenXML4JComplianceTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllOpenXML4JComplianceTests.java new file mode 100755 index 0000000000..cd990ccf08 --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllOpenXML4JComplianceTests.java @@ -0,0 +1,33 @@ +/* ==================================================================== + 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 junit.framework.Test; +import junit.framework.TestSuite; + +public class AllOpenXML4JComplianceTests { + + public static Test suite() { + TestSuite suite = new TestSuite(AllOpenXML4JComplianceTests.class.getName()); + suite.addTestSuite(TestOPCCompliancePartName.class); + suite.addTestSuite(TestOPCComplianceCoreProperties.class); + suite.addTestSuite(TestOPCCompliancePackageModel.class); + return suite; + } + +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllTests.java deleted file mode 100755 index 56974b0caf..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/AllTests.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class AllTests { - - public static Test suite() { - TestSuite suite = new TestSuite( - "Test for test.org.apache.poi.openxml4j.opc.compliance"); - // $JUnit-BEGIN$ - suite.addTestSuite(OPCCompliance_PartName.class); - suite.addTestSuite(OPCCompliance_CoreProperties.class); - suite.addTestSuite(OPCCompliance_PackageModel.class); - // $JUnit-END$ - return suite; - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_CoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_CoreProperties.java deleted file mode 100755 index a26fd3012e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_CoreProperties.java +++ /dev/null @@ -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: - * and 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 or - * 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: and 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: and 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: and 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: and 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(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PackageModel.java deleted file mode 100755 index f54c294b0b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PackageModel.java +++ /dev/null @@ -1,167 +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 junit.framework.TestCase; - -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.PackagePartName; -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; - -/** - * Test Open Packaging Convention package model compliance. - * - * M1.11 : A package implementer shall neither create nor recognize a part with - * a part name derived from another part name by appending segments to it. - * - * @author Julien Chable - */ -public class OPCCompliance_PackageModel extends TestCase { - - TestCore testCore = new TestCore(this.getClass()); - - public OPCCompliance_PackageModel(String name) { - super(name); - } - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - public void testPartNameDerivationAdditionFailure() { - Package pkg = null; - try { - pkg = Package.create("TODELETEIFEXIST.docx"); - PackagePartName name = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePartName nameDerived = PackagingURIHelper - .createPartName("/word/document.xml/image1.gif"); - pkg.createPart(name, ContentTypes.XML); - pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF); - } catch (InvalidOperationException e) { - pkg.revert(); - return; - } catch (InvalidFormatException e) { - fail(e.getMessage()); - } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); - } - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - public void testPartNameDerivationReadingFailure() { - String filepath = System.getProperty("openxml4j.compliance.input") - + File.separator + "OPCCompliance_DerivedPartNameFAIL.docx"; - try { - Package.open(filepath); - } catch (InvalidFormatException e) { - return; - } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - public void testAddPackageAlreadyAddFailure() throws Exception { - Package pkg = Package.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - PackagePartName name2 = null; - try { - name1 = PackagingURIHelper.createPartName("/word/document.xml"); - name2 = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); - } - pkg.createPart(name1, ContentTypes.XML); - try { - pkg.createPart(name2, ContentTypes.XML); - } catch (InvalidOperationException e) { - return; - } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - public void testAddPackageAlreadyAddFailure2() throws Exception { - Package pkg = Package.create("DELETEIFEXISTS.docx"); - PackagePartName partName = null; - try { - partName = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); - } - pkg.createPart(partName, ContentTypes.XML); - try { - pkg.createPart(partName, ContentTypes.XML); - } catch (InvalidOperationException e) { - return; - } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /** - * Try to add a relationship to a relationship part. - * - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - */ - public void testAddRelationshipRelationshipsPartFailure() { - Package pkg = Package.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - try { - name1 = PackagingURIHelper - .createPartName("/test/_rels/document.xml.rels"); - } catch (InvalidFormatException e) { - fail("This exception should never happen !"); - } - - try { - pkg.addRelationship(name1, TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_DOCUMENT); - } catch (InvalidOperationException e) { - return; - } - fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PartName.java deleted file mode 100755 index 80f6be75e9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/OPCCompliance_PartName.java +++ /dev/null @@ -1,253 +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.net.URI; -import java.net.URISyntaxException; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; - -/** - * Test part name Open Packaging Convention compliance. - * - * (Open Packaging Convention 8.1.1 Part names) : - * - * The part name grammar is defined as follows: - * - * part_name = 1*( "/" segment ) - * - * segment = 1*( pchar ) - * - * pchar is defined in RFC 3986. - * - * The part name grammar implies the following constraints. The package - * implementer shall neither create any part that violates these constraints nor - * retrieve any data from a package as a part if the purported part name - * violates these constraints. - * - * A part name shall not be empty. [M1.1] - * - * A part name shall not have empty segments. [M1.3] - * - * A part name shall start with a forward slash ("/") character. [M1.4] - * - * A part name shall not have a forward slash as the last character. [M1.5] - * - * A segment shall not hold any characters other than pchar characters. [M1.6] - * - * Part segments have the following additional constraints. The package - * implementer shall neither create any part with a part name comprised of a - * segment that violates these constraints nor retrieve any data from a package - * as a part if the purported part name contains a segment that violates these - * constraints. - * - * A segment shall not contain percent-encoded forward slash ("/"), or backward - * slash ("\") characters. [M1.7] - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - * - * A segment shall not end with a dot (".") character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - * - * A package implementer shall neither create nor recognize a part with a part - * name derived from another part name by appending segments to it. [M1.11] - * - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - * - * @author Julien Chable - * @version 1.0 - */ -public class OPCCompliance_PartName extends TestCase { - - public OPCCompliance_PartName(String name) { - super(name); - } - - /** - * Test some common invalid names. - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - */ - public void testInvalidPartNames() { - String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." }; - for (String s : invalidNames) { - URI uri = null; - try { - uri = new URI(s); - } catch (URISyntaxException e) { - assertTrue(s == "[Content_Types].xml"); - continue; - } - assertFalse("This part name SHOULD NOT be valid: " + s, - PackagingURIHelper.isValidPartName(uri)); - } - } - - /** - * Test some common valid names. - */ - public void testValidPartNames() throws URISyntaxException { - String[] validNames = { "/xml/item1.xml", "/document.xml", - "/a/%D1%86.xml" }; - for (String s : validNames) - assertTrue("This part name SHOULD be valid: " + s, - PackagingURIHelper.isValidPartName(new URI(s))); - } - - /** - * A part name shall not be empty. [M1.1] - */ - public void testEmptyPartNameFailure() throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("")); - fail("A part name shall not be empty. [M1.1]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - } - - /** - * A part name shall not have empty segments. [M1.3] - * - * A segment shall not end with a dot ('.') character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - */ - public void testPartNameWithInvalidSegmentsFailure() { - String[] invalidNames = { "//document.xml", "//word/document.xml", - "/word//document.rels", "/word//rels//document.rels", - "/xml./doc.xml", "/document.", "/./document.xml", - "/word/./doc.rels", "/%2F/document.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A part name shall not have empty segments. [M1.3]", - PackagingURIHelper.isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A segment shall not hold any characters other than pchar characters. - * [M1.6]. - */ - public void testPartNameWithNonPCharCharacters() { - String[] invalidNames = { "/doc�&.xml" }; - try { - for (String s : invalidNames) - assertTrue( - "A segment shall not contain non pchar characters [M1.6] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A segment shall not contain percent-encoded unreserved characters [M1.8]. - */ - public void testPartNameWithUnreservedEncodedCharactersFailure() { - String[] invalidNames = { "/a/docum%65nt.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A segment shall not contain percent-encoded unreserved characters [M1.8] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A part name shall start with a forward slash ('/') character. [M1.4] - */ - public void testPartNameStartsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("document.xml")); - fail("A part name shall start with a forward slash ('/') character. [M1.4]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - } - - /** - * A part name shall not have a forward slash as the last character. [M1.5] - */ - public void testPartNameEndsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("/document.xml/")); - fail("A part name shall not have a forward slash as the last character. [M1.5]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - */ - public void testPartNameComparaison() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", - "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", - "/rels/.rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper - .createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper - .createPartName(partName2[i]); - assertTrue(p1.equals(p2)); - assertTrue(p1.compareTo(p2) == 0); - assertTrue(p1.hashCode() == p2.hashCode()); - } - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12]. - * - * All the comparaisons MUST FAIL ! - */ - public void testPartNameComparaisonFailure() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", - "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", - "/rels/rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper - .createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper - .createPartName(partName2[i]); - assertFalse(p1.equals(p2)); - assertFalse(p1.compareTo(p2) == 0); - assertFalse(p1.hashCode() == p2.hashCode()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java new file mode 100755 index 0000000000..d2cb8f616e --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java @@ -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: + * and 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 or + * 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: and 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); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java new file mode 100755 index 0000000000..f135b41388 --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java @@ -0,0 +1,162 @@ +/* ==================================================================== + 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 junit.framework.TestCase; + +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.PackagePartName; +import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; +import org.apache.poi.openxml4j.opc.PackagingURIHelper; +import org.apache.poi.openxml4j.opc.TargetMode; + +/** + * Test Open Packaging Convention package model compliance. + * + * M1.11 : A package implementer shall neither create nor recognize a part with + * a part name derived from another part name by appending segments to it. + * + * @author Julien Chable + */ +public class TestOPCCompliancePackageModel extends TestCase { + + public TestOPCCompliancePackageModel(String name) { + super(name); + } + + /** + * A package implementer shall neither create nor recognize a part with a + * part name derived from another part name by appending segments to it. + * [M1.11] + */ + public void testPartNameDerivationAdditionFailure() { + Package pkg = Package.create("TODELETEIFEXIST.docx"); + try { + PackagePartName name = PackagingURIHelper + .createPartName("/word/document.xml"); + PackagePartName nameDerived = PackagingURIHelper + .createPartName("/word/document.xml/image1.gif"); + pkg.createPart(name, ContentTypes.XML); + pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF); + } catch (InvalidOperationException e) { + pkg.revert(); + return; + } catch (InvalidFormatException e) { + fail(e.getMessage()); + } + fail("A package implementer shall neither create nor recognize a part with a" + + " part name derived from another part name by appending segments to it." + + " [M1.11]"); + } + + /** + * A package implementer shall neither create nor recognize a part with a + * part name derived from another part name by appending segments to it. + * [M1.11] + */ + public void testPartNameDerivationReadingFailure() { + String filepath = System.getProperty("openxml4j.compliance.input") + + File.separator + "OPCCompliance_DerivedPartNameFAIL.docx"; + try { + Package.open(filepath); + } catch (InvalidFormatException e) { + return; + } + fail("A package implementer shall neither create nor recognize a part with a" + + " part name derived from another part name by appending segments to it." + + " [M1.11]"); + } + + /** + * Rule M1.12 : Packages shall not contain equivalent part names and package + * implementers shall neither create nor recognize packages with equivalent + * part names. + */ + public void testAddPackageAlreadyAddFailure() throws Exception { + Package pkg = Package.create("DELETEIFEXISTS.docx"); + PackagePartName name1 = null; + PackagePartName name2 = null; + try { + name1 = PackagingURIHelper.createPartName("/word/document.xml"); + name2 = PackagingURIHelper.createPartName("/word/document.xml"); + } catch (InvalidFormatException e) { + throw new Exception(e.getMessage()); + } + pkg.createPart(name1, ContentTypes.XML); + try { + pkg.createPart(name2, ContentTypes.XML); + } catch (InvalidOperationException e) { + return; + } + fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + + /** + * Rule M1.12 : Packages shall not contain equivalent part names and package + * implementers shall neither create nor recognize packages with equivalent + * part names. + */ + public void testAddPackageAlreadyAddFailure2() throws Exception { + Package pkg = Package.create("DELETEIFEXISTS.docx"); + PackagePartName partName = null; + try { + partName = PackagingURIHelper.createPartName("/word/document.xml"); + } catch (InvalidFormatException e) { + throw new Exception(e.getMessage()); + } + pkg.createPart(partName, ContentTypes.XML); + try { + pkg.createPart(partName, ContentTypes.XML); + } catch (InvalidOperationException e) { + return; + } + fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + + /** + * Try to add a relationship to a relationship part. + * + * Check rule M1.25: The Relationships part shall not have relationships to + * any other part. Package implementers shall enforce this requirement upon + * the attempt to create such a relationship and shall treat any such + * relationship as invalid. + */ + public void testAddRelationshipRelationshipsPartFailure() { + Package pkg = Package.create("DELETEIFEXISTS.docx"); + PackagePartName name1 = null; + try { + name1 = PackagingURIHelper + .createPartName("/test/_rels/document.xml.rels"); + } catch (InvalidFormatException e) { + fail("This exception should never happen !"); + } + + try { + pkg.addRelationship(name1, TargetMode.INTERNAL, + PackageRelationshipTypes.CORE_DOCUMENT); + } catch (InvalidOperationException e) { + return; + } + fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java new file mode 100755 index 0000000000..899c43e037 --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java @@ -0,0 +1,253 @@ +/* ==================================================================== + 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.net.URI; +import java.net.URISyntaxException; + +import junit.framework.TestCase; + +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.PackagePartName; +import org.apache.poi.openxml4j.opc.PackagingURIHelper; + +/** + * Test part name Open Packaging Convention compliance. + * + * (Open Packaging Convention 8.1.1 Part names) : + * + * The part name grammar is defined as follows: + * + * part_name = 1*( "/" segment ) + * + * segment = 1*( pchar ) + * + * pchar is defined in RFC 3986. + * + * The part name grammar implies the following constraints. The package + * implementer shall neither create any part that violates these constraints nor + * retrieve any data from a package as a part if the purported part name + * violates these constraints. + * + * A part name shall not be empty. [M1.1] + * + * A part name shall not have empty segments. [M1.3] + * + * A part name shall start with a forward slash ("/") character. [M1.4] + * + * A part name shall not have a forward slash as the last character. [M1.5] + * + * A segment shall not hold any characters other than pchar characters. [M1.6] + * + * Part segments have the following additional constraints. The package + * implementer shall neither create any part with a part name comprised of a + * segment that violates these constraints nor retrieve any data from a package + * as a part if the purported part name contains a segment that violates these + * constraints. + * + * A segment shall not contain percent-encoded forward slash ("/"), or backward + * slash ("\") characters. [M1.7] + * + * A segment shall not contain percent-encoded unreserved characters. [M1.8] + * + * A segment shall not end with a dot (".") character. [M1.9] + * + * A segment shall include at least one non-dot character. [M1.10] + * + * A package implementer shall neither create nor recognize a part with a part + * name derived from another part name by appending segments to it. [M1.11] + * + * Part name equivalence is determined by comparing part names as + * case-insensitive ASCII strings. [M1.12] + * + * @author Julien Chable + * @version 1.0 + */ +public class TestOPCCompliancePartName extends TestCase { + + public TestOPCCompliancePartName(String name) { + super(name); + } + + /** + * Test some common invalid names. + * + * A segment shall not contain percent-encoded unreserved characters. [M1.8] + */ + public void testInvalidPartNames() { + String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." }; + for (String s : invalidNames) { + URI uri = null; + try { + uri = new URI(s); + } catch (URISyntaxException e) { + assertTrue(s == "[Content_Types].xml"); + continue; + } + assertFalse("This part name SHOULD NOT be valid: " + s, + PackagingURIHelper.isValidPartName(uri)); + } + } + + /** + * Test some common valid names. + */ + public void testValidPartNames() throws URISyntaxException { + String[] validNames = { "/xml/item1.xml", "/document.xml", + "/a/%D1%86.xml" }; + for (String s : validNames) + assertTrue("This part name SHOULD be valid: " + s, + PackagingURIHelper.isValidPartName(new URI(s))); + } + + /** + * A part name shall not be empty. [M1.1] + */ + public void testEmptyPartNameFailure() throws URISyntaxException { + try { + PackagingURIHelper.createPartName(new URI("")); + fail("A part name shall not be empty. [M1.1]"); + } catch (InvalidFormatException e) { + // Normal behaviour + } + } + + /** + * A part name shall not have empty segments. [M1.3] + * + * A segment shall not end with a dot ('.') character. [M1.9] + * + * A segment shall include at least one non-dot character. [M1.10] + */ + public void testPartNameWithInvalidSegmentsFailure() { + String[] invalidNames = { "//document.xml", "//word/document.xml", + "/word//document.rels", "/word//rels//document.rels", + "/xml./doc.xml", "/document.", "/./document.xml", + "/word/./doc.rels", "/%2F/document.xml" }; + try { + for (String s : invalidNames) + assertFalse( + "A part name shall not have empty segments. [M1.3]", + PackagingURIHelper.isValidPartName(new URI(s))); + } catch (URISyntaxException e) { + fail(); + } + } + + /** + * A segment shall not hold any characters other than pchar characters. + * [M1.6]. + */ + public void testPartNameWithNonPCharCharacters() { + String[] invalidNames = { "/doc�&.xml" }; + try { + for (String s : invalidNames) + assertTrue( + "A segment shall not contain non pchar characters [M1.6] : " + + s, PackagingURIHelper + .isValidPartName(new URI(s))); + } catch (URISyntaxException e) { + fail(); + } + } + + /** + * A segment shall not contain percent-encoded unreserved characters [M1.8]. + */ + public void testPartNameWithUnreservedEncodedCharactersFailure() { + String[] invalidNames = { "/a/docum%65nt.xml" }; + try { + for (String s : invalidNames) + assertFalse( + "A segment shall not contain percent-encoded unreserved characters [M1.8] : " + + s, PackagingURIHelper + .isValidPartName(new URI(s))); + } catch (URISyntaxException e) { + fail(); + } + } + + /** + * A part name shall start with a forward slash ('/') character. [M1.4] + */ + public void testPartNameStartsWithAForwardSlashFailure() + throws URISyntaxException { + try { + PackagingURIHelper.createPartName(new URI("document.xml")); + fail("A part name shall start with a forward slash ('/') character. [M1.4]"); + } catch (InvalidFormatException e) { + // Normal behaviour + } + } + + /** + * A part name shall not have a forward slash as the last character. [M1.5] + */ + public void testPartNameEndsWithAForwardSlashFailure() + throws URISyntaxException { + try { + PackagingURIHelper.createPartName(new URI("/document.xml/")); + fail("A part name shall not have a forward slash as the last character. [M1.5]"); + } catch (InvalidFormatException e) { + // Normal behaviour + } + + } + + /** + * Part name equivalence is determined by comparing part names as + * case-insensitive ASCII strings. [M1.12] + */ + public void testPartNameComparaison() throws Exception { + String[] partName1 = { "/word/document.xml", "/docProps/core.xml", + "/rels/.rels" }; + String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", + "/rels/.rels" }; + for (int i = 0; i < partName1.length || i < partName2.length; ++i) { + PackagePartName p1 = PackagingURIHelper + .createPartName(partName1[i]); + PackagePartName p2 = PackagingURIHelper + .createPartName(partName2[i]); + assertTrue(p1.equals(p2)); + assertTrue(p1.compareTo(p2) == 0); + assertTrue(p1.hashCode() == p2.hashCode()); + } + } + + /** + * Part name equivalence is determined by comparing part names as + * case-insensitive ASCII strings. [M1.12]. + * + * All the comparaisons MUST FAIL ! + */ + public void testPartNameComparaisonFailure() throws Exception { + String[] partName1 = { "/word/document.xml", "/docProps/core.xml", + "/rels/.rels" }; + String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", + "/rels/rels" }; + for (int i = 0; i < partName1.length || i < partName2.length; ++i) { + PackagePartName p1 = PackagingURIHelper + .createPartName(partName1[i]); + PackagePartName p2 = PackagingURIHelper + .createPartName(partName2[i]); + assertFalse(p1.equals(p2)); + assertFalse(p1.compareTo(p2) == 0); + assertFalse(p1.hashCode() == p2.hashCode()); + } + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllOpenXML4JInternalTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllOpenXML4JInternalTests.java new file mode 100755 index 0000000000..338f5df455 --- /dev/null +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllOpenXML4JInternalTests.java @@ -0,0 +1,30 @@ +/* ==================================================================== + 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.internal; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllOpenXML4JInternalTests { + + public static Test suite() { + TestSuite suite = new TestSuite(AllOpenXML4JInternalTests.class.getName()); + suite.addTestSuite(TestContentTypeManager.class); + return suite; + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllTests.java deleted file mode 100755 index 25d140c819..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/AllTests.java +++ /dev/null @@ -1,33 +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.internal; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class AllTests { - - public static Test suite() { - TestSuite suite = new TestSuite( - "Test for test.org.apache.poi.openxml4j.opc.internal"); - //$JUnit-BEGIN$ - suite.addTestSuite(TestContentTypeManager.class); - //$JUnit-END$ - return suite; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java index 6af3e6f544..d509272d76 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java @@ -21,15 +21,9 @@ import junit.framework.TestCase; import org.apache.poi.openxml4j.opc.PackagePartName; 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 { - TestCore testCore = new TestCore(this.getClass()); - /** * Test the properties part content parsing. */ diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java index d715650528..c820f2c9bc 100644 --- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java +++ b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java @@ -62,10 +62,10 @@ public final class TestExcelExtractor extends TestCase { assertEquals( "Sheet1\n" + "1000.0\t1.0\t5.0\n" + - "2000.0\t2.0\t\n" + - "3000.0\t3.0\t\n" + - "4000.0\t4.0\t\n" + - "5000.0\t5.0\t\n" + + "2000.0\t2.0\n" + + "3000.0\t3.0\n" + + "4000.0\t4.0\n" + + "5000.0\t5.0\n" + "Sheet2\nSheet3\n", extractor.getText() ); @@ -75,10 +75,10 @@ public final class TestExcelExtractor extends TestCase { assertEquals( "Sheet1\n" + "1000.0\t1.0\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + - "2000.0\t2.0\t\n" + - "3000.0\t3.0\t\n" + - "4000.0\t4.0\t\n" + - "5000.0\t5.0\t\n" + + "2000.0\t2.0\n" + + "3000.0\t3.0\n" + + "4000.0\t4.0\n" + + "5000.0\t5.0\n" + "Sheet2\nSheet3\n", extractor.getText() ); @@ -196,15 +196,15 @@ public final class TestExcelExtractor extends TestCase { assertTrue(def.startsWith( "Sheet1\n" + "&[TAB]\t\n" + - "Hello\t\n" + - "11.0\t23.0\t\n" + "Hello\n" + + "11.0\t23.0\n" )); assertTrue(padded.startsWith( "Sheet1\n" + "&[TAB]\t\n" + - "Hello\t\t\t\t\t\t\t\t\t\t\t\n" + - "11.0\t\t\t23.0\t\t\t\t\t\t\t\t\n" + "Hello\n" + + "11.0\t\t\t23.0\n" )); }