aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/apache/commons/io/test/TestUtils.java
blob: 0620603dc6b52fc548923d769da03ed0d9d6bfc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
 * 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.commons.io.test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.ThreadUtils;

/**
 * Base class for tests doing tests with files.
 */
public abstract class TestUtils {

    /**
     * Assert that the content of a file is equal to that in a byte[].
     *
     * @param b0   the expected contents
     * @param file the file to check
     * @throws IOException If an I/O error occurs while reading the file contents
     */
    public static void assertEqualContent(final byte[] b0, final File file) throws IOException {
        assertEqualContent(b0, file.toPath());
    }

    /**
     * Assert that the content of a file is equal to that in a byte[].
     *
     * @param b0   the expected contents
     * @param file the file to check
     * @throws IOException If an I/O error occurs while reading the file contents
     */
    public static void assertEqualContent(final byte[] b0, final Path file) throws IOException {
        int count = 0, numRead = 0;
        final byte[] b1 = new byte[b0.length];
        try (InputStream is = Files.newInputStream(file)) {
            while (count < b0.length && numRead >= 0) {
                numRead = is.read(b1, count, b0.length);
                count += numRead;
            }
            assertEquals(b0.length, count, "Different number of bytes: ");
            for (int i = 0; i < count; i++) {
                assertEquals(b0[i], b1[i], "byte " + i + " differs");
            }
        }
    }

    /**
     * Assert that the content of a file is equal to that in a char[].
     *
     * @param c0   the expected contents
     * @param file the file to check
     * @throws IOException If an I/O error occurs while reading the file contents
     */
    public static void assertEqualContent(final char[] c0, final File file) throws IOException {
        assertEqualContent(c0, file.toPath());
    }

    /**
     * Assert that the content of a file is equal to that in a char[].
     *
     * @param c0   the expected contents
     * @param file the file to check
     * @throws IOException If an I/O error occurs while reading the file contents
     */
    public static void assertEqualContent(final char[] c0, final Path file) throws IOException {
        int count = 0, numRead = 0;
        final char[] c1 = new char[c0.length];
        try (Reader ir = Files.newBufferedReader(file)) {
            while (count < c0.length && numRead >= 0) {
                numRead = ir.read(c1, count, c0.length);
                count += numRead;
            }
            assertEquals(c0.length, count, "Different number of chars: ");
            for (int i = 0; i < count; i++) {
                assertEquals(c0[i], c1[i], "char " + i + " differs");
            }
        }
    }

    /**
     * Assert that the content of two files is the same.
     */
    private static void assertEqualContent(final File f0, final File f1)
            throws IOException {
        /* This doesn't work because the filesize isn't updated until the file
         * is closed.
        assertTrue( "The files " + f0 + " and " + f1 +
                    " have differing file sizes (" + f0.length() +
                    " vs " + f1.length() + ")", ( f0.length() == f1.length() ) );
        */
        try (InputStream is0 = Files.newInputStream(f0.toPath())) {
            try (InputStream is1 = Files.newInputStream(f1.toPath())) {
                final byte[] buf0 = new byte[1024];
                final byte[] buf1 = new byte[1024];
                int n0 = 0;
                int n1;

                while (-1 != n0) {
                    n0 = is0.read(buf0);
                    n1 = is1.read(buf1);
                    assertEquals(n0, n1,
                            "The files " + f0 + " and " + f1 +
                            " have differing number of bytes available (" + n0 + " vs " + n1 + ")");

                    assertArrayEquals(buf0, buf1, "The files " + f0 + " and " + f1 + " have different content");
                }
            }
        }
    }

    public static void checkFile(final File file, final File referenceFile)
            throws Exception {
        assertTrue(file.exists(), "Check existence of output file");
        assertEqualContent(referenceFile, file);
    }

    public static void checkWrite(final OutputStream output) {
        try {
            new java.io.PrintStream(output).write(0);
        } catch (final Throwable t) {
            fail("The copy() method closed the stream when it shouldn't have. " + t.getMessage());
        }
    }

    public static void checkWrite(final Writer output) {
        try {
            new java.io.PrintWriter(output).write('a');
        } catch (final Throwable t) {
            fail("The copy() method closed the stream when it shouldn't have. " + t.getMessage());
        }
    }

    public static void createFile(final File file, final long size) throws IOException {
        if (!file.getParentFile().exists()) {
            throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
        }
        try (BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
            generateTestData(output, size);
        }
    }

    public static void createFile(final Path file, final long size) throws IOException {
        if (!Files.exists(file.getParent())) {
            throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
        }
        try (BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(file))) {
            generateTestData(output, size);
        }
    }

    public static void createLineBasedFile(final File file, final String[] data) throws IOException {
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
        }
        try (PrintWriter output = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8))) {
            for (final String element : data) {
                output.println(element);
            }
        }
    }

    public static void deleteFile(final File file) {
        if (file.exists()) {
            assertTrue(file.delete(), "Couldn't delete file: " + file);
        }
    }

    public static void generateTestData(final File file, final long size) throws IOException, FileNotFoundException {
        try (BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
            generateTestData(output, size);
        }
    }

    public static byte[] generateTestData(final long size) {
        try {
            try (ByteArrayOutputStream baout = new ByteArrayOutputStream()) {
                generateTestData(baout, size);
                return baout.toByteArray();
            }
        } catch (final IOException ioe) {
            throw new IllegalStateException("This should never happen: " + ioe.getMessage(), ioe);
        }
    }

    public static void generateTestData(final OutputStream out, final long size) throws IOException {
        for (int i = 0; i < size; i++) {
            // output.write((byte)'X');
            // nice varied byte pattern compatible with Readers and Writers
            out.write((byte) (i % 127 + 1));
        }
    }

    public static File newFile(final File testDirectory, final String filename) throws IOException {
        final File destination = new File(testDirectory, filename);
        /*
        assertTrue( filename + "Test output data file shouldn't previously exist",
                    !destination.exists() );
        */
        if (destination.exists()) {
            FileUtils.forceDelete(destination);
        }
        return destination;
    }

    /**
     * Sleeps for a guaranteed number of milliseconds unless interrupted.
     *
     * This method exists because Thread.sleep(100) can sleep for 0, 70, 100 or 200ms or anything else
     * it deems appropriate. Read the docs on Thread.sleep for further details.
     *
     * @param millis the number of milliseconds to sleep.
     * @throws InterruptedException if interrupted.
     */
    public static void sleep(final long millis) throws InterruptedException {
        ThreadUtils.sleep(Duration.ofMillis(millis));
    }

    /**
     * Sleeps and swallows InterruptedException.
     *
     * @param millis the number of milliseconds to sleep.
     */
    public static void sleepQuietly(final long millis) {
        try {
            sleep(millis);
        } catch (final InterruptedException ignored){
            // ignore InterruptedException.
        }
    }

    private TestUtils() {

    }

}