You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestAllFiles.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.stress;
  16. import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
  17. import static org.junit.jupiter.api.Assertions.assertEquals;
  18. import static org.junit.jupiter.api.Assertions.assertNotNull;
  19. import static org.junit.jupiter.api.Assertions.assertThrows;
  20. import static org.junit.jupiter.api.Assertions.assertTrue;
  21. import static org.junit.jupiter.api.Assertions.fail;
  22. import java.io.BufferedInputStream;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Set;
  30. import java.util.stream.Stream;
  31. import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
  32. import org.apache.tools.ant.DirectoryScanner;
  33. import org.junit.jupiter.api.function.Executable;
  34. import org.junit.jupiter.api.parallel.Execution;
  35. import org.junit.jupiter.api.parallel.ExecutionMode;
  36. import org.junit.jupiter.params.ParameterizedTest;
  37. import org.junit.jupiter.params.provider.Arguments;
  38. import org.junit.jupiter.params.provider.MethodSource;
  39. import org.opentest4j.AssertionFailedError;
  40. /**
  41. * This is an integration test which performs various actions on all stored test-files and tries
  42. * to reveal problems which are introduced, but not covered (yet) by unit tests.
  43. *
  44. * This test looks for any file under the test-data directory and tries to do some useful
  45. * processing with it based on it's type.
  46. *
  47. * The test is implemented as a junit {@link ParameterizedTest} test, which leads
  48. * to one test-method call for each file (currently around 950 files are handled).
  49. *
  50. * There is a a mapping of extension to implementations of the interface
  51. * {@link FileHandler} which defines how the file is loaded and which actions are
  52. * tried with the file.
  53. *
  54. * The test can be expanded by adding more actions to the FileHandlers, this automatically
  55. * applies the action to any such file in our test-data repository.
  56. *
  57. * There is also a list of files that should actually fail.
  58. *
  59. * Note: It is also a test-failure if a file that is expected to fail now actually works,
  60. * i.e. if a bug was fixed in POI itself, the file should be removed from the expected-failures
  61. * here as well! This is to ensure that files that should not work really do not work, e.g.
  62. * that we do not remove expected sanity checks.
  63. */
  64. // also need to set JVM parameter: -Djunit.jupiter.execution.parallel.enabled=true
  65. @Execution(ExecutionMode.CONCURRENT)
  66. public class TestAllFiles {
  67. private static final String DEFAULT_TEST_DATA_PATH = "test-data";
  68. public static final File ROOT_DIR = new File(System.getProperty("POI.testdata.path", DEFAULT_TEST_DATA_PATH));
  69. public static final String[] SCAN_EXCLUDES = {
  70. "**/.svn/**",
  71. "lost+found",
  72. "**/.git/**",
  73. "**/ExternalEntityInText.docx", //the DocType (DTD) declaration causes this to fail
  74. "**/right-to-left.xlsx" //the threaded comments in this file cause XSSF clone to fail
  75. };
  76. // cheap workaround of skipping the few problematic files
  77. public static final String[] SCAN_EXCLUDES_NOSCRATCHPAD = {
  78. "**/.svn/**",
  79. "lost+found",
  80. "**/.git/**",
  81. "**/right-to-left.xlsx",
  82. "document/word2.doc",
  83. "document/cpansearch.perl.org_src_tobyink_acme-rundoc-0.001_word-lib_hello_world.docm",
  84. "hpsf/Test0313rur.adm",
  85. "spreadsheet/43493.xls",
  86. "spreadsheet/44958.xls",
  87. "spreadsheet/44958_1.xls",
  88. "spreadsheet/46904.xls",
  89. "spreadsheet/51832.xls",
  90. "spreadsheet/60284.xls",
  91. "spreadsheet/testArraysAndTables.xls",
  92. "spreadsheet/testEXCEL_3.xls",
  93. "spreadsheet/testEXCEL_4.xls",
  94. "poifs/unknown_properties.msg"
  95. };
  96. private static final Set<String> EXPECTED_FAILURES = StressTestUtils.unmodifiableHashSet(
  97. "document/truncated62886.docx"
  98. );
  99. public static Stream<Arguments> allfiles(String testName) throws IOException {
  100. StressMap sm = new StressMap();
  101. sm.load(new File(ROOT_DIR, "spreadsheet/stress.xls"));
  102. boolean noScratch = Boolean.getBoolean("scratchpad.ignore");
  103. DirectoryScanner scanner = new DirectoryScanner();
  104. scanner.setBasedir(ROOT_DIR);
  105. scanner.setExcludes(noScratch ? SCAN_EXCLUDES_NOSCRATCHPAD : SCAN_EXCLUDES);
  106. scanner.scan();
  107. final List<Arguments> result = new ArrayList<>(100);
  108. for (String file : scanner.getIncludedFiles()) {
  109. // avoid running on files leftover from previous failed runs
  110. if(file.endsWith("-saved.xls") || file.endsWith("TestHPSFWritingFunctionality.doc")) {
  111. continue;
  112. }
  113. for (FileHandlerKnown handler : sm.getHandler(file)) {
  114. ExcInfo info1 = sm.getExcInfo(file, testName, handler);
  115. if (info1 == null || info1.isValid(testName, handler.name())) {
  116. result.add(Arguments.of(
  117. file,
  118. handler,
  119. (info1 != null) ? info1.getPassword() : null,
  120. (info1 != null) ? info1.getExClazz() : null,
  121. (info1 != null) ? info1.getExMessage() : null
  122. ));
  123. }
  124. }
  125. }
  126. return result.stream();
  127. }
  128. public static Stream<Arguments> extractFiles() throws IOException {
  129. return allfiles("extract");
  130. }
  131. @ParameterizedTest(name = "Extracting - #{index} {0} {1}")
  132. @MethodSource("extractFiles")
  133. void handleExtracting(String file, FileHandlerKnown handler, String password, Class<? extends Throwable> exClass, String exMessage) throws IOException {
  134. if (StressTestUtils.excludeFile(file, EXPECTED_FAILURES)) return;
  135. System.out.println("Running extractFiles on "+file);
  136. FileHandler fileHandler = handler.getHandler();
  137. assertNotNull(fileHandler, "Did not find a handler for file " + file);
  138. Executable exec = () -> fileHandler.handleExtracting(new File(ROOT_DIR, file));
  139. verify(file, exec, exClass, exMessage, password);
  140. }
  141. public static Stream<Arguments> handleFiles() throws IOException {
  142. return allfiles("handle");
  143. }
  144. @ParameterizedTest(name = "#{index} {0} {1}")
  145. @MethodSource("handleFiles")
  146. void handleFile(String file, FileHandlerKnown handler, String password, Class<? extends Throwable> exClass, String exMessage) throws IOException {
  147. System.out.println("Running handleFiles on "+file);
  148. FileHandler fileHandler = handler.getHandler();
  149. assertNotNull(fileHandler, "Did not find a handler for file " + file);
  150. try (InputStream stream = new BufferedInputStream(new FileInputStream(new File(ROOT_DIR, file)), 64 * 1024)) {
  151. Executable exec = () -> fileHandler.handleFile(stream, file);
  152. verify(file, exec, exClass, exMessage, password);
  153. }
  154. }
  155. public static Stream<Arguments> handleAdditionals() throws IOException {
  156. return allfiles("additional");
  157. }
  158. @ParameterizedTest(name = "Additional - #{index} {0} {1}")
  159. @MethodSource("handleAdditionals")
  160. void handleAdditional(String file, FileHandlerKnown handler, String password, Class<? extends Throwable> exClass, String exMessage) {
  161. System.out.println("Running additionals on "+file);
  162. FileHandler fileHandler = handler.getHandler();
  163. assertNotNull(fileHandler, "Did not find a handler for file " + file);
  164. Executable exec = () -> fileHandler.handleAdditional(new File(ROOT_DIR, file));
  165. verify(file, exec, exClass, exMessage, password);
  166. }
  167. @SuppressWarnings("unchecked")
  168. private static void verify(String file, Executable exec, Class<? extends Throwable> exClass, String exMessage, String password) {
  169. final String errPrefix = file + " - failed. ";
  170. // this also removes the password for non encrypted files
  171. Biff8EncryptionKey.setCurrentUserPassword(password);
  172. if (exClass != null && AssertionFailedError.class.isAssignableFrom(exClass)) {
  173. try {
  174. exec.execute();
  175. fail(errPrefix + "Expected failed assertion");
  176. } catch (AssertionFailedError e) {
  177. String actMsg = pathReplace(e.getMessage());
  178. assertEquals(exMessage, actMsg, errPrefix);
  179. } catch (Throwable e) {
  180. fail(errPrefix + "Unexpected exception", e);
  181. }
  182. } else if (exClass != null) {
  183. Exception e = assertThrows((Class<? extends Exception>)exClass, exec);
  184. String actMsg = pathReplace(e.getMessage());
  185. if (NullPointerException.class.isAssignableFrom(exClass)) {
  186. if (actMsg != null) {
  187. assertTrue(actMsg.contains(exMessage), errPrefix + "Message: "+actMsg+" - didn't contain: "+exMessage);
  188. }
  189. } else {
  190. assertNotNull(actMsg, errPrefix);
  191. assertTrue(actMsg.contains(exMessage), errPrefix + "Message: "+actMsg+" - didn't contain: "+exMessage);
  192. }
  193. } else {
  194. assertDoesNotThrow(exec, errPrefix);
  195. }
  196. }
  197. private static String pathReplace(String msg) {
  198. if (msg == null) return null;
  199. // Windows path replacement
  200. msg = msg.replace('\\', '/');
  201. // Adjust file paths to remove unwanted file path info.
  202. int filePathIndex = msg.indexOf(ROOT_DIR.toString());
  203. if (filePathIndex > 0) {
  204. int testDataDirectoryIndex = msg.indexOf(DEFAULT_TEST_DATA_PATH);
  205. msg = msg.substring(0, filePathIndex) + msg.substring(testDataDirectoryIndex);
  206. }
  207. return msg;
  208. }
  209. }