termux-app

Форк
0
396 строк · 18.4 Кб
1
package com.termux.shared.file.tests;
2

3
import android.content.Context;
4

5
import androidx.annotation.NonNull;
6

7
import com.termux.shared.errors.Errno;
8
import com.termux.shared.file.FileUtils;
9
import com.termux.shared.file.FileUtilsErrno;
10
import com.termux.shared.logger.Logger;
11
import com.termux.shared.errors.Error;
12

13
import java.io.File;
14
import java.nio.charset.Charset;
15
import java.util.Arrays;
16
import java.util.List;
17

18
public class FileUtilsTests {
19

20
    private static final String LOG_TAG = "FileUtilsTests";
21

22
    /**
23
     * Run basic tests for {@link FileUtils} class.
24
     *
25
     * Move tests need to be written, specially for failures.
26
     *
27
     * The log level must be set to verbose.
28
     *
29
     * Run at app startup like in an activity
30
     * FileUtilsTests.runTests(this, TermuxConstants.TERMUX_HOME_DIR_PATH + "/FileUtilsTests");
31
     *
32
     * @param context The {@link Context} for operations.
33
     */
34
    public static void runTests(@NonNull final Context context, @NonNull final String testRootDirectoryPath) {
35
        try {
36
            Logger.logInfo(LOG_TAG, "Running tests");
37
            Logger.logInfo(LOG_TAG, "testRootDirectoryPath: \"" + testRootDirectoryPath + "\"");
38

39
            String fileUtilsTestsDirectoryCanonicalPath = FileUtils.getCanonicalPath(testRootDirectoryPath, null);
40
            assertEqual("FileUtilsTests directory path is not a canonical path", testRootDirectoryPath, fileUtilsTestsDirectoryCanonicalPath);
41

42
            runTestsInner(testRootDirectoryPath);
43
            Logger.logInfo(LOG_TAG, "All tests successful");
44
        } catch (Exception e) {
45
            Logger.logErrorExtended(LOG_TAG, e.getMessage());
46
            Logger.showToast(context, e.getMessage() != null ? e.getMessage().replaceAll("(?s)\nFull Error:\n.*", "") : null, true);
47
        }
48
    }
49

50
    private static void runTestsInner(@NonNull final String testRootDirectoryPath) throws Exception {
51
        Error error;
52
        String label;
53
        String path;
54

55
        /*
56
         * - dir1
57
         *  - sub_dir1
58
         *  - sub_reg1
59
         *  - sub_sym1 (absolute symlink to dir2)
60
         *  - sub_sym2 (copy of sub_sym1 for symlink to dir2)
61
         *  - sub_sym3 (relative symlink to dir4)
62
         * - dir2
63
         *  - sub_reg1
64
         *  - sub_reg2 (copy of dir2/sub_reg1)
65
         * - dir3 (copy of dir1)
66
         * - dir4 (moved from dir3)
67
         */
68

69
        String dir1_label = "dir1";
70
        String dir1_path = testRootDirectoryPath + "/dir1";
71

72
        String dir1__sub_dir1_label = "dir1/sub_dir1";
73
        String dir1__sub_dir1_path = dir1_path + "/sub_dir1";
74

75
        String dir1__sub_dir2_label = "dir1/sub_dir2";
76
        String dir1__sub_dir2_path = dir1_path + "/sub_dir2";
77

78
        String dir1__sub_dir3_label = "dir1/sub_dir3";
79
        String dir1__sub_dir3_path = dir1_path + "/sub_dir3";
80

81
        String dir1__sub_dir3__sub_reg1_label = "dir1/sub_dir3/sub_reg1";
82
        String dir1__sub_dir3__sub_reg1_path = dir1__sub_dir3_path + "/sub_reg1";
83

84
        String dir1__sub_reg1_label = "dir1/sub_reg1";
85
        String dir1__sub_reg1_path = dir1_path + "/sub_reg1";
86

87
        String dir1__sub_sym1_label = "dir1/sub_sym1";
88
        String dir1__sub_sym1_path = dir1_path + "/sub_sym1";
89

90
        String dir1__sub_sym2_label = "dir1/sub_sym2";
91
        String dir1__sub_sym2_path = dir1_path + "/sub_sym2";
92

93
        String dir1__sub_sym3_label = "dir1/sub_sym3";
94
        String dir1__sub_sym3_path = dir1_path + "/sub_sym3";
95

96

97
        String dir2_label = "dir2";
98
        String dir2_path = testRootDirectoryPath + "/dir2";
99

100
        String dir2__sub_reg1_label = "dir2/sub_reg1";
101
        String dir2__sub_reg1_path = dir2_path + "/sub_reg1";
102

103
        String dir2__sub_reg2_label = "dir2/sub_reg2";
104
        String dir2__sub_reg2_path = dir2_path + "/sub_reg2";
105

106

107
        String dir3_label = "dir3";
108
        String dir3_path = testRootDirectoryPath + "/dir3";
109

110
        String dir4_label = "dir4";
111
        String dir4_path = testRootDirectoryPath + "/dir4";
112

113

114

115

116

117
        // Create or clear test root directory file
118
        label = "testRootDirectoryPath";
119
        error = FileUtils.clearDirectory(label, testRootDirectoryPath);
120
        assertEqual("Failed to create " + label + " directory file", null, error);
121

122
        if (!FileUtils.directoryFileExists(testRootDirectoryPath, false))
123
            throwException("The " + label + " directory file does not exist as expected after creation");
124

125

126
        // Create dir1 directory file
127
        error = FileUtils.createDirectoryFile(dir1_label, dir1_path);
128
        assertEqual("Failed to create " + dir1_label + " directory file", null, error);
129

130
        // Create dir2 directory file
131
        error = FileUtils.createDirectoryFile(dir2_label, dir2_path);
132
        assertEqual("Failed to create " + dir2_label + " directory file", null, error);
133

134

135

136

137

138
        // Create dir1/sub_dir1 directory file
139
        label = dir1__sub_dir1_label; path = dir1__sub_dir1_path;
140
        error = FileUtils.createDirectoryFile(label, path);
141
        assertEqual("Failed to create " + label + " directory file", null, error);
142
        if (!FileUtils.directoryFileExists(path, false))
143
            throwException("The " + label + " directory file does not exist as expected after creation");
144

145
        // Create dir1/sub_reg1 regular file
146
        label = dir1__sub_reg1_label; path = dir1__sub_reg1_path;
147
        error = FileUtils.createRegularFile(label, path);
148
        assertEqual("Failed to create " + label + " regular file", null, error);
149
        if (!FileUtils.regularFileExists(path, false))
150
            throwException("The " + label + " regular file does not exist as expected after creation");
151

152
        // Create dir1/sub_sym1 -> dir2 absolute symlink file
153
        label = dir1__sub_sym1_label; path = dir1__sub_sym1_path;
154
        error = FileUtils.createSymlinkFile(label, dir2_path, path);
155
        assertEqual("Failed to create " + label + " symlink file", null, error);
156
        if (!FileUtils.symlinkFileExists(path))
157
            throwException("The " + label + " symlink file does not exist as expected after creation");
158

159
        // Copy dir1/sub_sym1 symlink file to dir1/sub_sym2
160
        label = dir1__sub_sym2_label; path = dir1__sub_sym2_path;
161
        error = FileUtils.copySymlinkFile(label, dir1__sub_sym1_path, path, false);
162
        assertEqual("Failed to copy " + dir1__sub_sym1_label + " symlink file to " + label, null, error);
163
        if (!FileUtils.symlinkFileExists(path))
164
            throwException("The " + label + " symlink file does not exist as expected after copying it from " + dir1__sub_sym1_label);
165
        if (!new File(path).getCanonicalPath().equals(dir2_path))
166
            throwException("The " + label + " symlink file does not point to " + dir2_label);
167

168

169

170

171

172
        // Write "line1" to dir2/sub_reg1 regular file
173
        label = dir2__sub_reg1_label; path = dir2__sub_reg1_path;
174
        error = FileUtils.writeTextToFile(label, path, Charset.defaultCharset(), "line1", false);
175
        assertEqual("Failed to write string to " + label + " file with append mode false", null, error);
176
        if (!FileUtils.regularFileExists(path, false))
177
            throwException("The " + label + " file does not exist as expected after writing to it with append mode false");
178

179
        // Write "line2" to dir2/sub_reg1 regular file
180
        error = FileUtils.writeTextToFile(label, path, Charset.defaultCharset(), "\nline2", true);
181
        assertEqual("Failed to write string to " + label + " file with append mode true", null, error);
182

183
        // Read dir2/sub_reg1 regular file
184
        StringBuilder dataStringBuilder = new StringBuilder();
185
        error = FileUtils.readTextFromFile(label, path, Charset.defaultCharset(), dataStringBuilder, false);
186
        assertEqual("Failed to read from " + label + " file", null, error);
187
        assertEqual("The data read from " + label + " file in not as expected", "line1\nline2", dataStringBuilder.toString());
188

189
        // Copy dir2/sub_reg1 regular file to dir2/sub_reg2 file
190
        label = dir2__sub_reg2_label; path = dir2__sub_reg2_path;
191
        error = FileUtils.copyRegularFile(label, dir2__sub_reg1_path, path, false);
192
        assertEqual("Failed to copy " + dir2__sub_reg1_label + " regular file to " + label, null, error);
193
        if (!FileUtils.regularFileExists(path, false))
194
            throwException("The " + label + " regular file does not exist as expected after copying it from " + dir2__sub_reg1_label);
195

196

197

198

199

200
        // Copy dir1 directory file to dir3
201
        label = dir3_label; path = dir3_path;
202
        error = FileUtils.copyDirectoryFile(label, dir2_path, path, false);
203
        assertEqual("Failed to copy " + dir2_label + " directory file to " + label, null, error);
204
        if (!FileUtils.directoryFileExists(path, false))
205
            throwException("The " + label + " directory file does not exist as expected after copying it from " + dir2_label);
206

207
        // Copy dir1 directory file to dir3 again to test overwrite
208
        label = dir3_label; path = dir3_path;
209
        error = FileUtils.copyDirectoryFile(label, dir2_path, path, false);
210
        assertEqual("Failed to copy " + dir2_label + " directory file to " + label, null, error);
211
        if (!FileUtils.directoryFileExists(path, false))
212
            throwException("The " + label + " directory file does not exist as expected after copying it from " + dir2_label);
213

214
        // Move dir3 directory file to dir4
215
        label = dir4_label; path = dir4_path;
216
        error = FileUtils.moveDirectoryFile(label, dir3_path, path, false);
217
        assertEqual("Failed to move " + dir3_label + " directory file to " + label, null, error);
218
        if (!FileUtils.directoryFileExists(path, false))
219
            throwException("The " + label + " directory file does not exist as expected after copying it from " + dir3_label);
220

221

222

223

224

225
        // Create dir1/sub_sym3 -> dir4 relative symlink file
226
        label = dir1__sub_sym3_label; path = dir1__sub_sym3_path;
227
        error = FileUtils.createSymlinkFile(label, "../dir4", path);
228
        assertEqual("Failed to create " + label + " symlink file", null, error);
229
        if (!FileUtils.symlinkFileExists(path))
230
            throwException("The " + label + " symlink file does not exist as expected after creation");
231

232
        // Create dir1/sub_sym3 -> dirX relative dangling symlink file
233
        // This is to ensure that symlinkFileExists returns true if a symlink file exists but is dangling
234
        label = dir1__sub_sym3_label; path = dir1__sub_sym3_path;
235
        error = FileUtils.createSymlinkFile(label, "../dirX", path);
236
        assertEqual("Failed to create " + label + " symlink file", null, error);
237
        if (!FileUtils.symlinkFileExists(path))
238
            throwException("The " + label + " dangling symlink file does not exist as expected after creation");
239

240

241

242

243

244
        // Delete dir1/sub_sym2 symlink file
245
        label = dir1__sub_sym2_label; path = dir1__sub_sym2_path;
246
        error = FileUtils.deleteSymlinkFile(label, path, false);
247
        assertEqual("Failed to delete " + label + " symlink file", null, error);
248
        if (FileUtils.fileExists(path, false))
249
            throwException("The " + label + " symlink file still exist after deletion");
250

251
        // Check if dir2 directory file still exists after deletion of dir1/sub_sym2 since it was a symlink to dir2
252
        // When deleting a symlink file, its target must not be deleted
253
        label = dir2_label; path = dir2_path;
254
        if (!FileUtils.directoryFileExists(path, false))
255
            throwException("The " + label + " directory file has unexpectedly been deleted after deletion of " + dir1__sub_sym2_label);
256

257

258

259

260

261
        // Delete dir1 directory file
262
        label = dir1_label; path = dir1_path;
263
        error = FileUtils.deleteDirectoryFile(label, path, false);
264
        assertEqual("Failed to delete " + label + " directory file", null, error);
265
        if (FileUtils.fileExists(path, false))
266
            throwException("The " + label + " directory file still exist after deletion");
267

268

269
        // Check if dir2 directory file and dir2/sub_reg1 regular file still exist after deletion of
270
        // dir1 since there was a dir1/sub_sym1 symlink to dir2 in it
271
        // When deleting a directory, any targets of symlinks must not be deleted when deleting symlink files
272
        label = dir2_label; path = dir2_path;
273
        if (!FileUtils.directoryFileExists(path, false))
274
            throwException("The " + label + " directory file has unexpectedly been deleted after deletion of " + dir1_label);
275
        label = dir2__sub_reg1_label; path = dir2__sub_reg1_path;
276
        if (!FileUtils.fileExists(path, false))
277
            throwException("The " + label + " regular file has unexpectedly been deleted after deletion of " + dir1_label);
278

279

280

281

282

283
        // Delete dir2/sub_reg1 regular file
284
        label = dir2__sub_reg1_label; path = dir2__sub_reg1_path;
285
        error = FileUtils.deleteRegularFile(label, path, false);
286
        assertEqual("Failed to delete " + label + " regular file", null, error);
287
        if (FileUtils.fileExists(path, false))
288
            throwException("The " + label + " regular file still exist after deletion");
289

290

291
        List<String> ignoredSubFilePaths = Arrays.asList(dir1__sub_dir2_path, dir1__sub_dir3__sub_reg1_path);
292

293
        // Create dir1 directory file
294
        error = FileUtils.createDirectoryFile(dir1_label, dir1_path);
295
        assertEqual("Failed to create " + dir1_label + " directory file", null, error);
296

297
        // Test empty dir
298
        error = FileUtils.validateDirectoryFileEmptyOrOnlyContainsSpecificFiles(dir1_label, dir1_path, ignoredSubFilePaths, false);
299
        assertEqual("Failed to validate if " + dir1_label + " directory file is empty", null, error);
300

301

302
        // Create dir1/sub_dir3 directory file
303
        label = dir1__sub_dir3_label; path = dir1__sub_dir3_path;
304
        error = FileUtils.createDirectoryFile(label, path);
305
        assertEqual("Failed to create " + label + " directory file", null, error);
306
        if (!FileUtils.directoryFileExists(path, false))
307
            throwException("The " + label + " directory file does not exist as expected after creation");
308

309
        // Test parent dir existing of non existing ignored regular file
310
        error = FileUtils.validateDirectoryFileEmptyOrOnlyContainsSpecificFiles(dir1_label, dir1_path, ignoredSubFilePaths, false);
311
        assertErrnoEqual("Failed to validate if " + dir1_label + " directory file is empty with parent dir existing of non existing ignored regular file", FileUtilsErrno.ERRNO_NON_EMPTY_DIRECTORY_FILE, error);
312

313

314
        // Write "line1" to dir1/sub_dir3/sub_reg1 regular file
315
        label = dir1__sub_dir3__sub_reg1_label; path = dir1__sub_dir3__sub_reg1_path;
316
        error = FileUtils.writeTextToFile(label, path, Charset.defaultCharset(), "line1", false);
317
        assertEqual("Failed to write string to " + label + " file with append mode false", null, error);
318
        if (!FileUtils.regularFileExists(path, false))
319
            throwException("The " + label + " file does not exist as expected after writing to it with append mode false");
320

321
        // Test ignored regular file existing
322
        error = FileUtils.validateDirectoryFileEmptyOrOnlyContainsSpecificFiles(dir1_label, dir1_path, ignoredSubFilePaths, false);
323
        assertEqual("Failed to validate if " + dir1_label + " directory file is empty with ignored regular file existing", null, error);
324

325

326
        // Create dir1/sub_dir2 directory file
327
        label = dir1__sub_dir2_label; path = dir1__sub_dir2_path;
328
        error = FileUtils.createDirectoryFile(label, path);
329
        assertEqual("Failed to create " + label + " directory file", null, error);
330
        if (!FileUtils.directoryFileExists(path, false))
331
            throwException("The " + label + " directory file does not exist as expected after creation");
332

333
        // Test ignored dir file existing
334
        error = FileUtils.validateDirectoryFileEmptyOrOnlyContainsSpecificFiles(dir1_label, dir1_path, ignoredSubFilePaths, false);
335
        assertEqual("Failed to validate if " + dir1_label + " directory file is empty with ignored dir file existing", null, error);
336

337

338
        // Create dir1/sub_dir1 directory file
339
        label = dir1__sub_dir1_label; path = dir1__sub_dir1_path;
340
        error = FileUtils.createDirectoryFile(label, path);
341
        assertEqual("Failed to create " + label + " directory file", null, error);
342
        if (!FileUtils.directoryFileExists(path, false))
343
            throwException("The " + label + " directory file does not exist as expected after creation");
344

345
        // Test non ignored dir file existing
346
        error = FileUtils.validateDirectoryFileEmptyOrOnlyContainsSpecificFiles(dir1_label, dir1_path, ignoredSubFilePaths, false);
347
        assertErrnoEqual("Failed to validate if " + dir1_label + " directory file is empty with non ignored dir file existing", FileUtilsErrno.ERRNO_NON_EMPTY_DIRECTORY_FILE, error);
348

349

350
        // Delete dir1 directory file
351
        label = dir1_label; path = dir1_path;
352
        error = FileUtils.deleteDirectoryFile(label, path, false);
353
        assertEqual("Failed to delete " + label + " directory file", null, error);
354

355

356
        FileUtils.getFileType("/dev/ptmx", false);
357
        FileUtils.getFileType("/dev/null", false);
358
    }
359

360

361

362
    public static void assertEqual(@NonNull final String message, final String expected, final Error actual) throws Exception {
363
        String actualString = actual != null ? actual.getMessage() : null;
364
        if (!equalsRegardingNull(expected, actualString))
365
            throwException(message + "\nexpected: \"" + expected + "\"\nactual: \"" + actualString + "\"\nFull Error:\n" + (actual != null ? actual.toString() : ""));
366
    }
367

368
    public static void assertEqual(@NonNull final String message, final String expected, final String actual) throws Exception {
369
        if (!equalsRegardingNull(expected, actual))
370
            throwException(message + "\nexpected: \"" + expected + "\"\nactual: \"" + actual + "\"");
371
    }
372

373
    private static boolean equalsRegardingNull(final String expected, final String actual) {
374
        if (expected == null) {
375
            return actual == null;
376
        }
377

378
        return isEquals(expected, actual);
379
    }
380

381
    public static void assertErrnoEqual(@NonNull final String message, final Errno expected, final Error actual) throws Exception {
382
        if ((expected == null && actual != null) || (expected != null && !expected.equalsErrorTypeAndCode(actual)))
383
            throwException(message + "\nexpected: \"" + expected + "\"\nactual: \"" + actual + "\"\nFull Error:\n" + (actual != null ? actual.toString() : ""));
384
    }
385

386

387

388
    private static boolean isEquals(String expected, String actual) {
389
        return expected.equals(actual);
390
    }
391

392
    public static void throwException(@NonNull final String message) throws Exception {
393
            throw new Exception(message);
394
    }
395

396
}
397

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.