1
2
3
4
5 package com.qulice.spi;
6
7 import java.io.File;
8 import java.nio.charset.StandardCharsets;
9 import java.nio.file.Files;
10 import java.nio.file.Path;
11 import org.hamcrest.MatcherAssert;
12 import org.hamcrest.Matchers;
13 import org.junit.jupiter.api.Test;
14 import org.junit.jupiter.api.io.TempDir;
15
16
17
18
19
20 final class BinaryTest {
21
22 @Test
23 void detectsPngFileAsBinary(@TempDir final Path dir) throws Exception {
24 final File file = dir.resolve("pixel.png").toFile();
25 Files.write(
26 file.toPath(),
27 new byte[] {
28 (byte) 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
29 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
30 }
31 );
32 MatcherAssert.assertThat(
33 "PNG header must not be treated as a text file",
34 new Binary(file).yes(),
35 Matchers.is(true)
36 );
37 }
38
39 @Test
40 void detectsJavaSourceAsNotBinary(@TempDir final Path dir)
41 throws Exception {
42 final File file = dir.resolve("Foo.java").toFile();
43 Files.writeString(
44 file.toPath(),
45 "class Foo { int bar = 42; }".concat(String.valueOf('\n')),
46 StandardCharsets.UTF_8
47 );
48 MatcherAssert.assertThat(
49 "plain Java source cannot be treated as binary",
50 new Binary(file).yes(),
51 Matchers.is(false)
52 );
53 }
54
55 @Test
56 void treatsUnicodeTextWithAccentsAsNotBinary(@TempDir final Path dir)
57 throws Exception {
58 final File file = dir.resolve("notes.txt").toFile();
59 Files.writeString(
60 file.toPath(),
61 "voilà — árvíztűrő tükörfúrógép".concat(String.valueOf('\n')),
62 StandardCharsets.UTF_8
63 );
64 MatcherAssert.assertThat(
65 "UTF-8 multibyte characters must not be mistaken for binary data",
66 new Binary(file).yes(),
67 Matchers.is(false)
68 );
69 }
70
71 @Test
72 void treatsEmptyFileAsNotBinary(@TempDir final Path dir) throws Exception {
73 final File file = dir.resolve("empty.txt").toFile();
74 Files.write(file.toPath(), new byte[0]);
75 MatcherAssert.assertThat(
76 "empty file cannot be classified as binary",
77 new Binary(file).yes(),
78 Matchers.is(false)
79 );
80 }
81
82 @Test
83 void detectsFileWithNullByteAsBinary(@TempDir final Path dir)
84 throws Exception {
85 final File file = dir.resolve("blob.dat").toFile();
86 Files.write(
87 file.toPath(),
88 new byte[] {'h', 'e', 'l', 'l', 'o', 0x00, 'w', 'o', 'r', 'l', 'd'}
89 );
90 MatcherAssert.assertThat(
91 "file containing a NULL byte must be classified as binary",
92 new Binary(file).yes(),
93 Matchers.is(true)
94 );
95 }
96
97 @Test
98 void treatsMissingFileAsNotBinary(@TempDir final Path dir) {
99 MatcherAssert.assertThat(
100 "non-existing file cannot be classified as binary",
101 new Binary(dir.resolve("missing").toFile()).yes(),
102 Matchers.is(false)
103 );
104 }
105 }