UNPKG

als-file-list

Version:

Generates filtered and sorted list of all file paths in a directory and its subdirectories.

189 lines (164 loc) 9.3 kB
const SimpleTest = require('als-simple-test'); SimpleTest.showFullError = true let { describe, it, beforeEach, runTests, expect, delay, assert, beforeAll, afterAll } = SimpleTest let fileList = require('../dest/file-list') let fileListSync = require('../dest/file-list-sync') if(process.argv[2] === '--sync') { fileList === fileListSync console.log('Running sync version') } const { createTestDirectory, deleteTestDirectory } = require('./test-folder') const { join } = require('path') const dirPath = join(__dirname, 'test-folder') describe('fileList function tests', () => { beforeAll(() => createTestDirectory(dirPath)) afterAll(() => deleteTestDirectory(dirPath)) describe('Basic tests', () => { it('Validation', async () => { try { await fileList(5645) assert(false, 'Not valid srcDir parameter') } catch (error) { assert(true, 'Not valid srcDir parameter') } try { await fileList(dirPath, { level: 'asd' }) assert(false, 'Not valid level parameter') } catch (error) { assert(true, 'Not valid level parameter') } try { await fileList(dirPath, { select: {} }) assert(false, 'Not valid select parameter') } catch (error) { assert(true, 'Not valid select parameter') } try { await fileList(dirPath, { where: {} }) assert(false, 'Not valid where parameter') } catch (error) { assert(true, 'Not valid where parameter') } }) it('Non existing folder', async () => { const errors = [] const result = await fileList(join(__dirname, 'hello'), {}, errors) assert(errors.length === 1, 'Has error') assert(result.length === 0, 'No results') }) // Тестирование чтения файлов из директории it('should return an array of file paths', async () => { const errors = [] let time = performance.now() const result = await fileList(dirPath, {}, errors); time = performance.now() - time expect(result).is('An array of file paths').instanceof(Array); assert(result.length === 60, `Array has 60 (${result.length}) files - parsed in ${time}ms`) assert(errors.length === 0, 'No errors') }); // // Тестирование фильтрации по размеру файла it('should filter files by size', async () => { let time = performance.now() const result = await fileList(dirPath, { select: 'size', where: (file, stats, isDir) => isDir || stats.size > 48 }); time = performance.now() - time expect(result.every(file => file.size > 48)).is('Filtered by size').equalTo(true); assert(result.length === 32, `Has to be 32(${result.length}) filtered files from 60` + ` time: ${time}`) }); // Тестирование обработки ошибок it('should handle file access errors', async () => { const errors = []; const result = await fileList(dirPath, { where: () => dgg }, errors); assert(errors.length > 0, `There is error ${errors.length}`) assert(result.length === 60, `Still getting all resources ${result.length}`) }); // Тестирование глубины обхода директорий it('should respect the level parameter', async () => { let time = performance.now() const result = await fileList(dirPath, { level: 1 }); time = performance.now() - time assert(result.length === 4, `Respecting level parameter (${result.length}/4)` + ` time: ${time}`) }); // Тестирование наличия определенных свойств в результате it('should include specified properties in the result', async () => { const result = await fileList(dirPath, { select: 'size mtimeMs' }); expect(result.every(file => file.hasOwnProperty('size') && file.hasOwnProperty('mtimeMs'))).is('Include specified properties').equalTo(true); const result1 = await fileList(dirPath, { select: ' ' }); expect(result1.every(file => !file.hasOwnProperty('size') && !file.hasOwnProperty('mtimeMs'))).is('Not include specified properties').equalTo(true); const result2 = await fileList(dirPath, { select: 'mtime' }); expect(result.every(file => !file.hasOwnProperty('mtime'))).is('Result not include mtime by default').equalTo(true); expect(result2.every(file => file.hasOwnProperty('mtime'))).is('Now it includes mtime').equalTo(true); }); }) describe('Tests for limit,sort,skip', () => { // Тестирование limit it('should respect the limit parameter', async () => { const result = await fileList(dirPath, { limit: 10 }); assert(result.length === 10, `Returns only 10 files ${result.length}`); }); // Тестирование sort и sortType // it('should correctly sort files by name ascending', async () => { // const resultAsc = await fileList(dirPath, { sort: 'relativePath', sortType: 'asc' }); // const resultDesc = await fileList(dirPath, { sort: 'relativePath', sortType: 'desc' }); // assert(resultAsc.length > 0, `resultAsc not empty ${resultAsc.length}`) // assert(resultDesc.length > 0, `resultDesc not empty ${resultDesc.length}`) // expect(resultAsc).isNot('Asc no equal to Desc').sameAs(resultDesc) // expect(resultAsc).is('Asc equal to reversed Desc').sameAs(resultDesc.reverse()) // }); // Тестирование skip it('should skip the specified number of files', async () => { const result = await fileList(dirPath, { skip: 5 }); assert(result.length === 55, `Has to be 55/60 - 5 skiped. (result:${result.length})`) // проверить, что первые 5 файлов пропущены }); // Комбинация limit и skip it('should correctly apply skip and then limit', async () => { const all = await fileList(dirPath); const result = await fileList(dirPath, { skip: 5, limit: 5 }); assert(result.length === 5, 'Returns 5 files after skipping 5'); assert(all[5] === result[0] && all[9] === result[4], 'The right elements') }); // Комбинация sort, skip, и limit it('should correctly apply sort, then skip and limit', async () => { const allSorted = await fileList(dirPath, { sort: 'relativePath'}); const result = await fileList(dirPath, { sort: 'relativePath', skip: 5, limit: 5 }); assert(result.length === 5, 'Returns 5 files after skipping 5'); for (let i = 0; i < result.length; i++) { assert(result[i].relativePath === allSorted[i + 5].relativePath, `File at index ${i} is correct`); } }); }) describe('Combined tests', () => { // Комбинированный тест it('should correctly apply combination of where, select, sort, skip, and limit', async () => { const result = await fileList(dirPath, { where: (file, stats, isDir) => isDir || stats.size > 48, select: 'size mtimeMs', sort: 'size', skip: 2, limit: 3 }); // Проверка, что возвращено правильное количество файлов expect(result.length).is(`Expected length 3 (result: ${result.length})`).equalTo(3); // Проверка, что все файлы соответствуют условию where result.forEach(file => { expect(file).hasProperty('size'); expect(file.size).is('Size check').above(48); }); // Проверка наличия выбранных свойств result.forEach(file => { expect(file).hasProperty('size'); expect(file).hasProperty('mtimeMs'); }); // Проверка корректности сортировки for (let i = 0; i < result.length - 1; i++) { expect(result[i].size).is(`File at index ${i}`).atMost(result[i + 1].size); } }); // Тестирование на пограничные значения it('should handle edge values for skip and limit', async () => { const all = await fileList(dirPath); const result = await fileList(dirPath, { skip: all.length, limit: all.length }); assert(result.length === 0, 'No files should be returned'); }); // Проверка сортировки по числовым значениям it('should correctly sort files by size', async () => { const result = await fileList(dirPath, { select:'size', sort: 'size' }); for (let i = 0; i < result.length - 1; i++) { expect(result[i].size).is(`File at index ${i} size`).atMost(result[i + 1].size); } }); }) }) runTests()