View Javadoc
1   /*
2    * SPDX-License-Identifier: Apache-2.0
3    * See LICENSE file for details.
4    *
5    * Copyright 2025-2026 Hazendaz
6    * Copyright 2011-2025 Acegi Technology Pty Limited.
7    */
8   package au.com.acegi.xmlformat;
9   
10  import static au.com.acegi.xmlformat.IOUtil.hash;
11  import static au.com.acegi.xmlformat.TestUtil.getResource;
12  import static au.com.acegi.xmlformat.TestUtil.stringToFile;
13  import static org.hamcrest.CoreMatchers.is;
14  import static org.hamcrest.CoreMatchers.not;
15  import static org.hamcrest.MatcherAssert.assertThat;
16  
17  import java.io.File;
18  import java.io.IOException;
19  import java.io.InputStream;
20  
21  import org.junit.jupiter.api.Test;
22  import org.junit.jupiter.api.io.TempDir;
23  
24  /**
25   * Tests {@link IOUtil}.
26   */
27  public class IOTest {
28  
29      @TempDir
30      private File tmp;
31  
32      @Test
33      void hash1() throws IOException {
34          testHash("/test1-in.xml", 459_402_491L);
35      }
36  
37      @Test
38      void hash2() throws IOException {
39          testHash("/test2-in.xml", 1_687_393_391L);
40      }
41  
42      @Test
43      void hashInvalid() throws IOException {
44          testHash("/invalid.xml", 2_274_913_643L);
45      }
46  
47      @Test
48      void hashFileMatchesStreamHash() throws IOException {
49          final File file = File.createTempFile("junit", ".xml", tmp);
50          stringToFile("<root><child/></root>", file);
51  
52          final long fileHash = hash(file);
53          try (InputStream in = java.nio.file.Files.newInputStream(file.toPath())) {
54              final long streamHash = hash(in);
55              assertThat(fileHash, is(streamHash));
56          }
57      }
58  
59      @Test
60      void hashDifferentContentProducesDifferentHash() throws IOException {
61          final File file1 = File.createTempFile("junit-a", ".xml", tmp);
62          final File file2 = File.createTempFile("junit-b", ".xml", tmp);
63          stringToFile("<root><child/></root>", file1);
64          stringToFile("<root><other/></root>", file2);
65  
66          assertThat(hash(file1), not(hash(file2)));
67      }
68  
69      @Test
70      void hashSameContentProducesSameHash() throws IOException {
71          final File file1 = File.createTempFile("junit-c", ".xml", tmp);
72          final File file2 = File.createTempFile("junit-d", ".xml", tmp);
73          final String content = "<root><child/></root>";
74          stringToFile(content, file1);
75          stringToFile(content, file2);
76  
77          assertThat(hash(file1), is(hash(file2)));
78      }
79  
80      private void testHash(final String resource, final long expected) throws IOException {
81          try (InputStream in = getResource(resource)) {
82              final long hash = hash(in);
83              assertThat(hash, is(expected));
84          }
85      }
86  
87  }