How to use service.deleteDirectory method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

FileClerkServiceTest.js

Source:FileClerkServiceTest.js Github

copy

Full Screen

1const should = require('should');2const moment = require('moment-timezone');3const { wait } = require('prolly');4const FileService = require('../../lib/services/FileService');5const FileClerk = require('../../lib/services/FileClerkService');6describe('FileClerkService', () => {7 const home = './test/fixtures';8 before(async () => {9 await FileService.createDirectory(home);10 });11 after(async () => {12 await FileService.deleteDirectory(home);13 });14 describe('organize', () => {15 const srcDir = `${home}/Pictures/INCOMING`;16 const targetDir = `${home}/PictureDestination`;17 beforeEach(async () => {18 await FileService.createFile(`${srcDir}/01.mp4`);19 await FileService.createFile(`${srcDir}/02.png`);20 await FileService.createFile(`${srcDir}/03/04.png`);21 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);22 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);23 await FileService.createFile(`${srcDir}/05/06/07.png`);24 await FileService.createFile(`${srcDir}/05/06/07.jpg`);25 await FileService.createFile(`${srcDir}/05/07/10.mp4`);26 await FileService.createDirectory(`${srcDir}/05/08/09`);27 await FileService.createFile(`${srcDir}/png/1.arf`);28 await FileService.createFile(`${srcDir}/png/2.arf`);29 await FileService.createFile(`${srcDir}/png/3.arf`);30 });31 afterEach(async () => {32 await FileService.deleteDirectory(srcDir);33 await FileService.deleteDirectory(targetDir);34 });35 it('should organize with no parameters', async () => {36 const files = await FileClerk.organize(srcDir, targetDir);37 files.should.be.an.Array().of.length(10);38 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);39 remainingDirs.should.be.an.Array().of.length(3);40 const remainingFiles = await FileService.listFilesRecursive(srcDir);41 remainingFiles.should.be.an.Array().of.length(0);42 const newDirs = await FileService.listDirectoriesRecursive(targetDir);43 newDirs.should.be.an.Array().of.length(6);44 const newFiles = await FileService.listFilesRecursive(targetDir);45 newFiles.should.be.an.Array().of.length(10);46 });47 it('should organize with list of extension filters', async () => {48 const opts = {49 extensions: ['jpg', 'png'],50 };51 const files = await FileClerk.organize(srcDir, targetDir, opts);52 files.should.be.an.Array().of.length(4);53 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);54 remainingDirs.should.be.an.Array().of.length(8);55 const remainingFiles = await FileService.listFilesRecursive(srcDir);56 remainingFiles.should.be.an.Array().of.length(6);57 const newDirs = await FileService.listDirectoriesRecursive(targetDir);58 newDirs.should.be.an.Array().of.length(3);59 const newFiles = await FileService.listFilesRecursive(targetDir);60 newFiles.should.be.an.Array().of.length(4);61 });62 it('should organize with list of includes regex strings', async () => {63 const testDir = `${srcDir}/regextest`;64 await FileService.createFile(`${testDir}/includes/01.mp4`);65 await FileService.createFile(`${testDir}/includes/02.png`);66 await FileService.createFile(`${testDir}/includes/03/04.jpg`);67 await FileService.createFile(`${testDir}/other/includes/02.png`);68 await FileService.createFile(`${testDir}/other/includes/shouldmatch/02.png`);69 const opts = {70 extensions: ['png', 'jpg'],71 includes: ['^includes', 'shouldmatch'],72 };73 const files = await FileClerk.organize(testDir, targetDir, opts);74 files.should.be.an.Array().of.length(3);75 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);76 remainingDirs.should.be.an.Array().of.length(3);77 const remainingFiles = await FileService.listFilesRecursive(testDir);78 remainingFiles.should.be.an.Array().of.length(2);79 const newDirs = await FileService.listDirectoriesRecursive(targetDir);80 newDirs.should.be.an.Array().of.length(5);81 const newFiles = await FileService.listFilesRecursive(targetDir);82 newFiles.should.be.an.Array().of.length(3);83 });84 it('should organize with list of excludes regex strings', async () => {85 const testDir = `${srcDir}/regextest`;86 await FileService.createFile(`${testDir}/includes/01.mp4`);87 await FileService.createFile(`${testDir}/includes/02.png`);88 await FileService.createFile(`${testDir}/includes/excludes/04.jpg`);89 await FileService.createFile(`${testDir}/includes/03.png`);90 await FileService.createFile(`${testDir}/includes/shouldmatch/03.png`);91 const opts = {92 excludes: ['excludes', '03'],93 };94 const files = await FileClerk.organize(testDir, targetDir, opts);95 files.should.be.an.Array().of.length(2);96 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);97 remainingDirs.should.be.an.Array().of.length(3);98 const remainingFiles = await FileService.listFilesRecursive(testDir);99 remainingFiles.should.be.an.Array().of.length(3);100 const newDirs = await FileService.listDirectoriesRecursive(targetDir);101 newDirs.should.be.an.Array().of.length(1);102 const newFiles = await FileService.listFilesRecursive(targetDir);103 newFiles.should.be.an.Array().of.length(2);104 });105 it('should organize with list of includes and excludes regex strings', async () => {106 const testDir = `${srcDir}/regextest`;107 await FileService.createFile(`${testDir}/includes/01.mp4`);108 await FileService.createFile(`${testDir}/includes/02.png`);109 await FileService.createFile(`${testDir}/includes/excludes/04.jpg`);110 await FileService.createFile(`${testDir}/other/includes/02.png`);111 await FileService.createFile(`${testDir}/other/includes/shouldmatch/02.png`);112 const opts = {113 extensions: ['png', 'jpg', 'mp4'],114 includes: ['^includes', 'shouldmatch'],115 excludes: ['excludes', '02'],116 };117 const files = await FileClerk.organize(testDir, targetDir, opts);118 files.should.be.an.Array().of.length(1);119 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);120 remainingDirs.should.be.an.Array().of.length(5);121 const remainingFiles = await FileService.listFilesRecursive(testDir);122 remainingFiles.should.be.an.Array().of.length(4);123 const newDirs = await FileService.listDirectoriesRecursive(targetDir);124 newDirs.should.be.an.Array().of.length(1);125 const newFiles = await FileService.listFilesRecursive(targetDir);126 newFiles.should.be.an.Array().of.length(1);127 });128 it('should organize with list of includes and excludes RegExp objects', async () => {129 const testDir = `${srcDir}/regextest`;130 await FileService.createFile(`${testDir}/includes/01.mp4`);131 await FileService.createFile(`${testDir}/includes/02.png`);132 await FileService.createFile(`${testDir}/includes/excludes/04.jpg`);133 await FileService.createFile(`${testDir}/other/includes/02.png`);134 await FileService.createFile(`${testDir}/other/includes/shouldmatch/02.png`);135 const opts = {136 extensions: ['png', 'jpg', 'mp4'],137 includes: [new RegExp('^includes'), new RegExp('shouldmatch')],138 excludes: [new RegExp('excludes'), new RegExp('02')],139 };140 const files = await FileClerk.organize(testDir, targetDir, opts);141 files.should.be.an.Array().of.length(1);142 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);143 remainingDirs.should.be.an.Array().of.length(5);144 const remainingFiles = await FileService.listFilesRecursive(testDir);145 remainingFiles.should.be.an.Array().of.length(4);146 const newDirs = await FileService.listDirectoriesRecursive(targetDir);147 newDirs.should.be.an.Array().of.length(1);148 const newFiles = await FileService.listFilesRecursive(targetDir);149 newFiles.should.be.an.Array().of.length(1);150 });151 it('should organize with a user-defined sourceFilter', async () => {152 const testDir = `${srcDir}/user-defined-filter`;153 await FileService.createFile(`${testDir}/includes/catchwithuserfilter.mp4`);154 await FileService.createFile(`${testDir}/includes/01.mp4`);155 await FileService.createFile(`${testDir}/includes/02.png`);156 await FileService.createFile(`${testDir}/includes/excludes/04.jpg`);157 await FileService.createFile(`${testDir}/other/includes/02.png`);158 await FileService.createFile(`${testDir}/other/includes/shouldmatch/02.png`);159 const opts = {160 extensions: ['png', 'jpg', 'mp4'],161 includes: [new RegExp('^includes'), new RegExp('shouldmatch')],162 excludes: [new RegExp('excludes'), new RegExp('02')],163 sourceFilter: ({ name }) => name !== 'catchwithuserfilter',164 };165 const files = await FileClerk.organize(testDir, targetDir, opts);166 files.should.be.an.Array().of.length(1);167 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);168 remainingDirs.should.be.an.Array().of.length(5);169 const remainingFiles = await FileService.listFilesRecursive(testDir);170 remainingFiles.should.be.an.Array().of.length(5);171 const newDirs = await FileService.listDirectoriesRecursive(targetDir);172 newDirs.should.be.an.Array().of.length(1);173 const newFiles = await FileService.listFilesRecursive(targetDir);174 newFiles.should.be.an.Array().of.length(1);175 });176 it('should organize with multiple user-defined sourceFilters', async () => {177 const testDir = `${srcDir}/user-defined-filter`;178 await FileService.createFile(`${testDir}/includes/also-catch-with-user-filter.mp4`);179 await FileService.createFile(`${testDir}/includes/catchwithuserfilter.mp4`);180 await FileService.createFile(`${testDir}/includes/01.mp4`);181 await FileService.createFile(`${testDir}/includes/02.png`);182 await FileService.createFile(`${testDir}/includes/excludes/04.jpg`);183 await FileService.createFile(`${testDir}/other/includes/02.png`);184 await FileService.createFile(`${testDir}/other/includes/shouldmatch/02.png`);185 const opts = {186 extensions: ['png', 'jpg', 'mp4'],187 includes: [new RegExp('^includes'), new RegExp('shouldmatch')],188 excludes: [new RegExp('excludes'), new RegExp('02')],189 sourceFilter: [190 ({ name }) => name !== 'catchwithuserfilter',191 ({ name }) => name !== 'also-catch-with-user-filter',192 ],193 };194 const files = await FileClerk.organize(testDir, targetDir, opts);195 files.should.be.an.Array().of.length(1);196 const remainingDirs = await FileService.listDirectoriesRecursive(testDir);197 remainingDirs.should.be.an.Array().of.length(5);198 const remainingFiles = await FileService.listFilesRecursive(testDir);199 remainingFiles.should.be.an.Array().of.length(6);200 const newDirs = await FileService.listDirectoriesRecursive(targetDir);201 newDirs.should.be.an.Array().of.length(1);202 const newFiles = await FileService.listFilesRecursive(targetDir);203 newFiles.should.be.an.Array().of.length(1);204 });205 it('should simulate organize w/dry run param', async () => {206 await FileService.createDirectory(targetDir);207 const opts = {208 extensions: ['jpg', 'png'],209 dryRun: true,210 };211 const files = await FileClerk.organize(srcDir, targetDir, opts);212 files.should.be.an.Array().of.length(4);213 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);214 remainingDirs.should.be.an.Array().of.length(9);215 const remainingFiles = await FileService.listFilesRecursive(srcDir);216 remainingFiles.should.be.an.Array().of.length(10);217 const newFiles = await FileService.listFilesRecursive(targetDir);218 newFiles.should.be.an.Array().of.length(0);219 });220 });221 describe('organizeByDate', () => {222 const srcDir = `${home}/Pictures/INCOMING`;223 const targetDir = `${home}/PictureDestination`;224 beforeEach(async () => {225 await FileService.createFile(`${srcDir}/01.mp4`);226 await FileService.createFile(`${srcDir}/02.png`);227 await FileService.createFile(`${srcDir}/03/04.png`);228 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);229 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);230 await FileService.createFile(`${srcDir}/05/06/07.png`);231 await FileService.createFile(`${srcDir}/05/06/07.jpg`);232 await FileService.createFile(`${srcDir}/05/07/10.mp4`);233 await FileService.createDirectory(`${srcDir}/05/08/09`);234 await FileService.createFile(`${srcDir}/png/1.arf`);235 await FileService.createFile(`${srcDir}/png/2.arf`);236 await FileService.createFile(`${srcDir}/png/3.arf`);237 });238 afterEach(async () => {239 await FileService.deleteDirectory(srcDir);240 await FileService.deleteDirectory(targetDir);241 });242 it('should organize by creation date (no params)', async () => {243 const now = moment();244 const resultPathShouldContain = ['YYYY-MM-DD'].map(f => now.format(f)).join('/');245 const files = await FileClerk.organizeByDate(srcDir, targetDir);246 files.should.be.an.Array().of.length(10);247 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);248 remainingDirs.should.be.an.Array().of.length(3);249 const remainingFiles = await FileService.listFilesRecursive(srcDir);250 remainingFiles.should.be.an.Array().of.length(0);251 const newDirs = await FileService.listDirectoriesRecursive(targetDir);252 newDirs.should.be.an.Array().of.length(1);253 const newFiles = await FileService.listFilesRecursive(targetDir);254 newFiles.should.be.an.Array().of.length(10);255 newFiles.forEach(({ path, filename }) => {256 should((new RegExp(`^${targetDir}/${resultPathShouldContain}/${filename}$`)).test(path)).be.true();257 });258 });259 it('should organize by creation date (default format) w/extensions', async () => {260 const opts = {261 extensions: ['jpg', 'png'],262 };263 const now = moment();264 const resultPathShouldContain = ['YYYY-MM-DD'].map(f => now.format(f)).join('/');265 const files = await FileClerk.organizeByDate(srcDir, targetDir, opts);266 files.should.be.an.Array().of.length(4);267 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);268 remainingDirs.should.be.an.Array().of.length(8);269 const remainingFiles = await FileService.listFilesRecursive(srcDir);270 remainingFiles.should.be.an.Array().of.length(6);271 const newDirs = await FileService.listDirectoriesRecursive(targetDir);272 newDirs.should.be.an.Array().of.length(1);273 const newFiles = await FileService.listFilesRecursive(targetDir);274 newFiles.should.be.an.Array().of.length(4);275 newFiles.forEach(({ path, filename }) => {276 should((new RegExp(`^${targetDir}/${resultPathShouldContain}/${filename}$`)).test(path)).be.true();277 });278 });279 it('should organize by creation date (custom formats)', async () => {280 const opts = {281 extensions: ['jpg', 'png'],282 dateFormat: ['YYYY', 'YYYY-MM', 'YYYY-MM-DD'],283 };284 const now = moment();285 const resultPathShouldContain = opts.dateFormat.map(f => now.format(f)).join('/');286 const files = await FileClerk.organizeByDate(srcDir, targetDir, opts);287 files.should.be.an.Array().of.length(4);288 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);289 remainingDirs.should.be.an.Array().of.length(8);290 const remainingFiles = await FileService.listFilesRecursive(srcDir);291 remainingFiles.should.be.an.Array().of.length(6);292 const newDirs = await FileService.listDirectoriesRecursive(targetDir);293 newDirs.should.be.an.Array().of.length(3);294 const newFiles = await FileService.listFilesRecursive(targetDir);295 newFiles.should.be.an.Array().of.length(4);296 newFiles.forEach(({ path, filename }) => {297 should((new RegExp(`^${targetDir}/${resultPathShouldContain}/${filename}$`)).test(path)).be.true();298 });299 });300 it('should organize by creation date (default to use earliest of all File.stats dates)', async () => {301 const opts = {302 extensions: ['jpg', 'png'],303 dateFormat: ['YYYY-MM-DDTHH:mm:ss.SSSZ'],304 };305 const filename = 'mytest.jpg';306 const tsSourceDir = `${srcDir}/timestamp-src`;307 const tsTargetDir = `${srcDir}/timestamp-target`;308 const srcFile = `${tsSourceDir}/${filename}`;309 const startTime = moment().valueOf();310 await wait(10);311 await FileService.createFile(srcFile);312 await wait(10);313 const [{ target: middleTarget }] =314 await FileClerk.organizeByDate(tsSourceDir, tsTargetDir, opts);315 const { ctime: middleCtime } = await FileService.stat(middleTarget);316 const m1 = middleTarget.match(new RegExp(`([^/]*)/${filename}$`));317 const middleTargetDirTime = moment(m1[1]).valueOf();318 await wait(10);319 const [{ target: lastTarget }]320 = await FileClerk.organizeByDate(tsTargetDir, tsSourceDir, opts);321 const { ctime: latestCtime } = await FileService.stat(lastTarget);322 const m2 = lastTarget.match(new RegExp(`([^/]*)/${filename}$`));323 const latestTargetDirTime = moment(m2[1]).valueOf();324 const middleCTime = moment(middleCtime).valueOf();325 const latestCTime = moment(latestCtime).valueOf();326 latestTargetDirTime.should.be.eql(middleTargetDirTime);327 latestTargetDirTime.should.be.lessThan(latestCTime);328 latestTargetDirTime.should.be.lessThan(middleCTime);329 latestTargetDirTime.should.be.greaterThan(startTime);330 });331 it('should organize by creation date (client-defined timezone)', async () => {332 const tzStr = 'Antarctica/South_Pole';333 const timezone = moment.tz(tzStr).format('Z');334 const opts = {335 extensions: ['jpg', 'png'],336 dateFormat: ['Z'],337 timeZone: tzStr,338 };339 const filename = 'mytest.jpg';340 const tsSourceDir = `${srcDir}/timestamp-src`;341 const tsTargetDir = `${srcDir}/timestamp-target`;342 const srcFile = `${tsSourceDir}/${filename}`;343 await FileService.createFile(srcFile);344 const [{ target }] = await FileClerk.organizeByDate(tsSourceDir, tsTargetDir, opts);345 const tzMatch = target.match(new RegExp(`([^/]*)/${filename}$`));346 tzMatch[1].should.be.a.String().eql(timezone);347 });348 it('should organize by creation date (client-defined date property)', async () => {349 const opts = {350 extensions: ['jpg', 'png'],351 dateFormat: ['YYYY-MM-DDTHH:mm:ss.SSSZ'],352 dateProperty: 'ctime',353 };354 const filename = 'mytest.jpg';355 const tsSourceDir = `${srcDir}/timestamp-src`;356 const tsTargetDir = `${srcDir}/timestamp-target`;357 const srcFile = `${tsSourceDir}/${filename}`;358 const startTime = moment().valueOf();359 await wait(10);360 await FileService.createFile(srcFile);361 await wait(10);362 const [{ target: middleTarget }] =363 await FileClerk.organizeByDate(tsSourceDir, tsTargetDir, opts);364 const { ctime: middleCtime } = await FileService.stat(middleTarget);365 const m1 = middleTarget.match(new RegExp(`([^/]*)/${filename}$`));366 const middleTargetDirTime = moment(m1[1]).valueOf();367 await wait(10);368 const [{ target: lastTarget }]369 = await FileClerk.organizeByDate(tsTargetDir, tsSourceDir, opts);370 const { ctime: latestCtime } = await FileService.stat(lastTarget);371 const m2 = lastTarget.match(new RegExp(`([^/]*)/${filename}$`));372 const latestTargetDirTime = moment(m2[1]).valueOf();373 const middleCTime = moment(middleCtime).valueOf();374 const latestCTime = moment(latestCtime).valueOf();375 latestTargetDirTime.should.be.greaterThan(middleTargetDirTime);376 latestTargetDirTime.should.be.lessThan(latestCTime);377 latestTargetDirTime.should.be.eql(middleCTime);378 latestTargetDirTime.should.be.greaterThan(startTime);379 });380 });381 describe('organizeByExtension', () => {382 const srcDir = `${home}/Pictures/INCOMING`;383 const targetDir = `${home}/PictureDestination`;384 beforeEach(async () => {385 await FileService.createFile(`${srcDir}/01.mp4`);386 await FileService.createFile(`${srcDir}/02.png`);387 await FileService.createFile(`${srcDir}/03/04.png`);388 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);389 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);390 await FileService.createFile(`${srcDir}/05/06/a.rose.by.any.other.name`);391 await FileService.createFile(`${srcDir}/05/06/no_extension`);392 await FileService.createFile(`${srcDir}/05/06/07.PNG`);393 await FileService.createFile(`${srcDir}/05/06/07.jpg`);394 await FileService.createFile(`${srcDir}/05/07/10.MP4`);395 await FileService.createDirectory(`${srcDir}/05/08/09`);396 await FileService.createFile(`${srcDir}/png/1`);397 await FileService.createFile(`${srcDir}/png/1.arf`);398 await FileService.createFile(`${srcDir}/png/2.arf`);399 await FileService.createFile(`${srcDir}/png/3.arf`);400 });401 afterEach(async () => {402 await FileService.deleteDirectory(srcDir);403 await FileService.deleteDirectory(targetDir);404 });405 it('should organize by file extension (no params)', async () => {406 const files = await FileClerk.organizeByExtension(srcDir, targetDir);407 files.should.be.an.Array().of.length(13);408 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);409 remainingDirs.should.be.an.Array().of.length(3);410 const remainingFiles = await FileService.listFilesRecursive(srcDir);411 remainingFiles.should.be.an.Array().of.length(0);412 const newDirs = await FileService.listDirectoriesRecursive(targetDir);413 newDirs.should.be.an.Array().of.length(6);414 const newFiles = await FileService.listFilesRecursive(targetDir);415 newFiles.should.be.an.Array().of.length(13);416 });417 it('should organize by file extension, and filter on extensions irrespective of leading dot (.)', async () => {418 const opts = {419 extensions: ['JPG', '.png', ''],420 };421 const files = await FileClerk.organizeByExtension(srcDir, targetDir, opts);422 files.should.be.an.Array().of.length(6);423 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);424 remainingDirs.should.be.an.Array().of.length(9);425 const remainingFiles = await FileService.listFilesRecursive(srcDir);426 remainingFiles.should.be.an.Array().of.length(7);427 const newDirs = await FileService.listDirectoriesRecursive(targetDir);428 newDirs.should.be.an.Array().of.length(3);429 const newFiles = await FileService.listFilesRecursive(targetDir);430 newFiles.should.be.an.Array().of.length(6);431 });432 });433 describe('organizeByAlphabetical', () => {434 const srcDir = `${home}/Pictures/INCOMING`;435 const targetDir = `${home}/PictureDestination`;436 beforeEach(async () => {437 await FileService.createFile(`${srcDir}/1.mp4`);438 await FileService.createFile(`${srcDir}/02.png`);439 await FileService.createFile(`${srcDir}/03/~&.png`);440 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);441 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);442 await FileService.createFile(`${srcDir}/05/06/a.png`);443 await FileService.createFile(`${srcDir}/05/06/!#b.jpg`);444 await FileService.createFile(`${srcDir}/05/07/10.mp4`);445 await FileService.createDirectory(`${srcDir}/05/08/09`);446 await FileService.createFile(`${srcDir}/png/1.arf`);447 await FileService.createFile(`${srcDir}/png/2.arf`);448 await FileService.createFile(`${srcDir}/png/3.arf`);449 });450 afterEach(async () => {451 await FileService.deleteDirectory(srcDir);452 await FileService.deleteDirectory(targetDir);453 });454 it('should organize by alphabetical (no params)', async () => {455 const files = await FileClerk.organizeByAlphabetical(srcDir, targetDir);456 files.should.be.an.Array().of.length(10);457 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);458 remainingDirs.should.be.an.Array().of.length(3);459 const remainingFiles = await FileService.listFilesRecursive(srcDir);460 remainingFiles.should.be.an.Array().of.length(0);461 const newDirs = await FileService.listDirectoriesRecursive(targetDir);462 newDirs.should.be.an.Array().of.length(6);463 const newFiles = await FileService.listFilesRecursive(targetDir);464 newFiles.should.be.an.Array().of.length(10);465 });466 it('should organize by alphabetical (w/Extension filters)', async () => {467 const opts = {468 extensions: ['jpg', 'png', 'mp4'],469 };470 const files = await FileClerk.organizeByAlphabetical(srcDir, targetDir, opts);471 files.should.be.an.Array().of.length(7);472 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);473 remainingDirs.should.be.an.Array().of.length(4);474 const remainingFiles = await FileService.listFilesRecursive(srcDir);475 remainingFiles.should.be.an.Array().of.length(3);476 const newDirs = await FileService.listDirectoriesRecursive(targetDir);477 newDirs.should.be.an.Array().of.length(4);478 const newFiles = await FileService.listFilesRecursive(targetDir);479 newFiles.should.be.an.Array().of.length(7);480 });481 it('should organize by alphabetical w/Custom Symbol and Case', async () => {482 const opts = {483 extensions: ['jpg', 'png', 'mp4'],484 upperCase: true,485 symbolDir: '#',486 };487 const files = await FileClerk.organizeByAlphabetical(srcDir, targetDir, opts);488 files.should.be.an.Array().of.length(7);489 const remainingDirs = await FileService.listDirectoriesRecursive(srcDir);490 remainingDirs.should.be.an.Array().of.length(4);491 const remainingFiles = await FileService.listFilesRecursive(srcDir);492 remainingFiles.should.be.an.Array().of.length(3);493 const newDirs = await FileService.listDirectoriesRecursive(targetDir);494 newDirs.should.be.an.Array().of.length(5);495 const newFiles = await FileService.listFilesRecursive(targetDir);496 newFiles.should.be.an.Array().of.length(7);497 });498 });...

Full Screen

Full Screen

FileStructureService.spec.js

Source:FileStructureService.spec.js Github

copy

Full Screen

1/*global beforeEach:true, describe:true, it:true */2'use strict';3// Angular:4var angular = require('angular');5require('angular-mocks');6// Test Utilities:7var chai = require('chai');8var dirtyChai = require('dirty-chai');9var sinon = require('sinon');10// Test setup:11var expect = chai.expect;12chai.use(dirtyChai);13// Testing:14require('./FileStructureService');15var fileStructureService;16// Mocks:17var MockHttpResponseInterceptor = require('./HttpResponseInterceptor.mock');18var MockPersistentStateService = require('./PersistentStateService.mock');19describe('FileStructureService.js:', function () {20 var $httpBackend;21 var httpResponseInterceptor;22 var persistentStateService;23 beforeEach(function () {24 angular.mock.module('Core');25 angular.mock.module(function ($provide, $httpProvider) {26 httpResponseInterceptor = new MockHttpResponseInterceptor();27 $provide.factory('httpResponseInterceptor', function () {28 return httpResponseInterceptor;29 });30 persistentStateService = new MockPersistentStateService();31 $provide.factory('persistentStateService', function () {32 return persistentStateService;33 });34 $provide.factory('PageObjectParserService', function () {35 return {};36 });37 $httpProvider.interceptors.push('httpResponseInterceptor');38 });39 angular.mock.inject(function (_$httpBackend_, _fileStructureService_) {40 $httpBackend = _$httpBackend_;41 fileStructureService = _fileStructureService_;42 });43 });44 describe('FileStructureService.getFileStructure:', function () {45 it('should get the current file structure from the server:', function (done) {46 var fileStructureMock = {47 directory: {48 directories: []49 }50 };51 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);52 sinon.stub(persistentStateService, 'get').returns({});53 $httpBackend.whenGET('/page-objects/file-structure').respond({});54 fileStructureService.getFileStructure('page-objects')55 .then(function (fileStructure) {56 expect(fileStructure).to.equal(fileStructureMock);57 done();58 })59 .catch(done.fail);60 $httpBackend.flush();61 });62 it('should update the "open" state of the directories:', function (done) {63 var directory = {64 path: '/path/to/open/directory',65 directories: []66 };67 var fileStructureMock = {68 directory: {69 directories: [directory]70 }71 };72 var openDirectories = {73 '/path/to/open/directory': true74 };75 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);76 sinon.stub(persistentStateService, 'get').returns(openDirectories);77 $httpBackend.whenGET('/page-objects/file-structure').respond({});78 fileStructureService.getFileStructure('page-objects')79 .then(function () {80 expect(directory.open).to.be.true();81 done();82 })83 .catch(done.fail);84 $httpBackend.flush();85 });86 });87 describe('FileStructureService.addDirectory:', function () {88 it('should make a request to add a new directory:', function (done) {89 var fileStructureMock = {90 directory: {91 directories: []92 }93 };94 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);95 sinon.stub(persistentStateService, 'get').returns({});96 $httpBackend.whenPOST('/page-objects/directory').respond({});97 fileStructureService.addDirectory('page-objects')98 .then(function (fileStructure) {99 expect(fileStructure).to.equal(fileStructureMock);100 done();101 })102 .catch(done.fail);103 $httpBackend.flush();104 });105 it('should update the "open" state of the directories:', function (done) {106 var directory = {107 path: '/path/to/open/directory',108 directories: []109 };110 var fileStructureMock = {111 directory: {112 directories: [directory]113 }114 };115 var openDirectories = {116 '/path/to/open/directory': true117 };118 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);119 sinon.stub(persistentStateService, 'get').returns(openDirectories);120 $httpBackend.whenPOST('/page-objects/directory').respond({});121 fileStructureService.addDirectory('page-objects')122 .then(function () {123 expect(directory.open).to.be.true();124 done();125 })126 .catch(done.fail);127 $httpBackend.flush();128 });129 });130 describe('FileStructureService.copyFile:', function () {131 it('should make a request to copy a file:', function (done) {132 var fileStructureMock = {133 directory: {134 directories: []135 }136 };137 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);138 sinon.stub(persistentStateService, 'get').returns({});139 $httpBackend.whenPOST('/page-objects/file/copy').respond({});140 fileStructureService.copyFile('page-objects')141 .then(function (fileStructure) {142 expect(fileStructure).to.equal(fileStructureMock);143 done();144 })145 .catch(done.fail);146 $httpBackend.flush();147 });148 it('should update the "open" state of the directories:', function (done) {149 var directory = {150 path: '/path/to/open/directory',151 directories: []152 };153 var fileStructureMock = {154 directory: {155 directories: [directory]156 }157 };158 var openDirectories = {159 '/path/to/open/directory': true160 };161 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);162 sinon.stub(persistentStateService, 'get').returns(openDirectories);163 $httpBackend.whenPOST('/page-objects/file/copy').respond({});164 fileStructureService.copyFile('page-objects')165 .then(function () {166 expect(directory.open).to.be.true();167 done();168 })169 .catch(done.fail);170 $httpBackend.flush();171 });172 });173 describe('FileStructureService.deleteDirectory:', function () {174 it('should make a request to delete a directory:', function (done) {175 var fileStructureMock = {176 directory: {177 directories: []178 }179 };180 var options = {};181 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);182 sinon.stub(persistentStateService, 'get').returns({});183 $httpBackend.whenDELETE('/page-objects/directory').respond({});184 fileStructureService.deleteDirectory('page-objects', options)185 .then(function (fileStructure) {186 expect(fileStructure).to.equal(fileStructureMock);187 done();188 })189 .catch(done.fail);190 $httpBackend.flush();191 });192 it('should update the "open" state of the directories:', function (done) {193 var directory = {194 path: '/path/to/open/directory',195 directories: []196 };197 var fileStructureMock = {198 directory: {199 directories: [directory]200 }201 };202 var openDirectories = {203 '/path/to/open/directory': true204 };205 var options = {};206 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);207 sinon.stub(persistentStateService, 'get').returns(openDirectories);208 $httpBackend.whenDELETE('/page-objects/directory').respond({});209 fileStructureService.deleteDirectory('page-objects', options)210 .then(function () {211 expect(directory.open).to.be.true();212 done();213 })214 .catch(done.fail);215 $httpBackend.flush();216 });217 });218 describe('FileStructureService.deleteFile:', function () {219 it('should make a request to delete a file:', function (done) {220 var fileStructureMock = {221 directory: {222 directories: []223 }224 };225 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);226 sinon.stub(persistentStateService, 'get').returns({});227 $httpBackend.whenDELETE('/page-objects/file').respond({});228 fileStructureService.deleteFile('page-objects')229 .then(function (fileStructure) {230 expect(fileStructure).to.equal(fileStructureMock);231 done();232 })233 .catch(done.fail);234 $httpBackend.flush();235 });236 it('should update the "open" state of the directories:', function (done) {237 var directory = {238 path: '/path/to/open/directory',239 directories: []240 };241 var fileStructureMock = {242 directory: {243 directories: [directory]244 }245 };246 var openDirectories = {247 '/path/to/open/directory': true248 };249 sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);250 sinon.stub(persistentStateService, 'get').returns(openDirectories);251 $httpBackend.whenDELETE('/page-objects/file').respond({});252 fileStructureService.deleteFile('page-objects')253 .then(function () {254 expect(directory.open).to.be.true();255 done();256 })257 .catch(done.fail);258 $httpBackend.flush();259 });260 });261 // describe('FileStructureService.editDirectoryPath:', function () {262 // it('should make a request to edit the path of a directory:', function (done) {263 // var fileStructureMock = {264 // directory: {265 // directories: []266 // }267 // };268 // var options = {};269 //270 // sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);271 // sinon.stub(persistentStateService, 'get').returns({});272 //273 // $httpBackend.whenPATCH('/page-objects/directory/path').respond({});274 //275 // fileStructureService.editDirectoryPath('page-objects', options)276 // .then(function (fileStructure) {277 // expect(options.isDirectory).to.be.true();278 // expect(fileStructure).to.equal(fileStructureMock);279 // done();280 // })281 // .catch(done.fail);282 //283 // $httpBackend.flush();284 // });285 //286 // it('should update the "open" state of the directories:', function (done) {287 // var directory = {288 // path: '/path/to/open/directory',289 // directories: []290 // };291 // var fileStructureMock = {292 // directory: {293 // directories: [directory]294 // }295 // };296 // var openDirectories = {297 // '/path/to/open/directory': true298 // };299 // var options = {};300 //301 // sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);302 // sinon.stub(persistentStateService, 'get').returns(openDirectories);303 //304 // $httpBackend.whenPATCH('/page-objects/directory/path').respond({});305 //306 // fileStructureService.editDirectoryPath('page-objects', options)307 // .then(function () {308 // expect(directory.open).to.be.true();309 // done();310 // })311 // .catch(done.fail);312 //313 // $httpBackend.flush();314 // });315 // });316 //317 // describe('FileStructureService.editFilePath:', function () {318 // it('should make a request to edit the path of a file:', function (done) {319 // var fileStructureMock = {320 // directory: {321 // directories: []322 // }323 // };324 //325 // sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);326 // sinon.stub(persistentStateService, 'get').returns({});327 //328 // $httpBackend.whenPATCH('/page-objects/file/path').respond({});329 //330 // fileStructureService.editFilePath('page-objects')331 // .then(function (fileStructure) {332 // expect(fileStructure).to.equal(fileStructureMock);333 // done();334 // })335 // .catch(done.fail);336 //337 // $httpBackend.flush();338 // });339 //340 // it('should update the "open" state of the directories:', function (done) {341 // var directory = {342 // path: '/path/to/open/directory',343 // directories: []344 // };345 // var fileStructureMock = {346 // directory: {347 // directories: [directory]348 // }349 // };350 // var openDirectories = {351 // '/path/to/open/directory': true352 // };353 //354 // sinon.stub(httpResponseInterceptor, 'response').returns(fileStructureMock);355 // sinon.stub(persistentStateService, 'get').returns(openDirectories);356 //357 // $httpBackend.whenPATCH('/page-objects/file/path').respond({});358 //359 // fileStructureService.editFilePath('page-objects')360 // .then(function () {361 // expect(directory.open).to.be.true();362 // done();363 // })364 // .catch(done.fail);365 //366 // $httpBackend.flush();367 // });368 // });369 describe('FileStructureService.toggleOpenDirectory:', function () {370 it('should toggle the "open" state of a given directory path:', function () {371 var openDirectories = {372 'toggle/open/to/closed': true373 };374 sinon.stub(persistentStateService, 'get').returns(openDirectories);375 sinon.stub(persistentStateService, 'set');376 fileStructureService.toggleOpenDirectory('toggle/open/to/closed');377 fileStructureService.toggleOpenDirectory('toggle/closed/to/open');378 expect(openDirectories['toggle/closed/to/open']).to.be.true();379 expect(openDirectories['toggle/open/to/closed']).to.be.undefined();380 persistentStateService.get.restore();381 persistentStateService.set.restore();382 });383 });...

Full Screen

Full Screen

fileservice-directory-tests.js

Source:fileservice-directory-tests.js Github

copy

Full Screen

1// 2// Copyright (c) Microsoft and contributors. All rights reserved.3// 4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7// http://www.apache.org/licenses/LICENSE-2.08// 9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// 13// See the License for the specific language governing permissions and14// limitations under the License.15// 16var assert = require('assert');17var guid = require('node-uuid');1819// Lib includes20var testutil = require('../../framework/util');21var SR = testutil.libRequire('common/util/sr');2223var azure = testutil.libRequire('azure-storage');2425var Constants = azure.Constants;26var HttpConstants = Constants.HttpConstants;2728var shareNamesPrefix = 'share-';29var directoryNamesPrefix = 'dir-';30var fileNamesPrefix = 'file-';3132var fileService;33var shareName;34var directoryName;3536describe('FileDirectory', function () {37 before(function (done) {38 fileService = azure.createFileService()39 .withFilter(new azure.ExponentialRetryPolicyFilter());4041 shareName = getName(shareNamesPrefix);42 fileService.createShareIfNotExists(shareName, function (createError) {43 assert.equal(createError, null);44 done();45 });46 });4748 after(function (done) {49 fileService.deleteShareIfExists(shareName, function (deleteError) {50 assert.equal(deleteError, null);51 done();52 });53 });5455 beforeEach(function (done) {56 directoryName = getName(directoryNamesPrefix);57 done();58 });5960 describe('doesDirectoryExist', function () {61 it('should work', function (done) {62 fileService.doesDirectoryExist(shareName, directoryName, function (existsError, exists) {63 assert.equal(existsError, null);64 assert.strictEqual(exists, false);6566 fileService.createDirectory(shareName, directoryName, function (createError, directory1, createDirectoryResponse) {67 assert.equal(createError, null);68 assert.notEqual(directory1, null);69 assert.equal(createDirectoryResponse.statusCode, HttpConstants.HttpResponseCodes.Created);7071 fileService.doesDirectoryExist(shareName, directoryName, function (existsError, exists) {72 assert.equal(existsError, null);73 assert.strictEqual(exists, true);74 done();75 });76 });77 });78 });7980 it('base directory', function (done) {81 fileService.doesDirectoryExist(shareName, '', function (existsError, exists) {82 assert.equal(existsError, null);83 assert.strictEqual(exists, true);84 done();85 });86 });87 });8889 describe('createDirectory', function () {90 it('should detect incorrect directory names', function (done) {91 assert.throws(function () { fileService.createDirectory(shareName, null, function () { }); },92 /Required argument directory for function createDirectory is not defined/);9394 assert.throws(function () { fileService.createDirectory(shareName, '', function () { }); },95 /Required argument directory for function createDirectory is not defined/);9697 done();98 });99100 it('should work', function (done) {101 fileService.createDirectory(shareName, directoryName, function (createError, directory1, createDirectoryResponse) {102 assert.equal(createError, null);103 assert.notEqual(directory1, null);104 if (directory1) {105 assert.notEqual(directory1.name, null);106 assert.notEqual(directory1.etag, null);107 assert.notEqual(directory1.lastModified, null);108 }109110 assert.equal(createDirectoryResponse.statusCode, HttpConstants.HttpResponseCodes.Created);111112 // creating again will result in a duplicate error113 fileService.createDirectory(shareName, directoryName, function (createError2, directory2) {114 assert.equal(createError2.code, Constants.StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS);115 assert.equal(directory2, null);116117 fileService.deleteDirectory(shareName, directoryName, function (deleteError) {118 assert.equal(deleteError, null);119 done();120 });121 });122 });123 });124125 it('should work when the directory name starts and ends with slash', function (done) {126 var directoryNameWithSlash = '/' + getName(directoryNamesPrefix) + '/';127 fileService.createDirectory(shareName, directoryNameWithSlash, function (createError, directory1, createDirectoryResponse) {128 assert.equal(createError, null);129 assert.notEqual(directory1, null);130 if (directory1) {131 assert.notEqual(directory1.name, null);132 assert.notEqual(directory1.etag, null);133 assert.notEqual(directory1.lastModified, null);134 }135136 assert.equal(createDirectoryResponse.statusCode, HttpConstants.HttpResponseCodes.Created);137138 // creating again will result in a duplicate error139 fileService.createDirectory(shareName, directoryNameWithSlash, function (createError2, directory2) {140 assert.equal(createError2.code, Constants.StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS);141 assert.equal(directory2, null);142143 fileService.deleteDirectory(shareName, directoryNameWithSlash, function (deleteError) {144 assert.equal(deleteError, null);145 done();146 });147 });148 });149 });150 });151152 describe('createDirectoryIfNotExists', function() {153 it('should create a directory if not exists', function (done) {154 fileService.createDirectoryIfNotExists(shareName, directoryName, function (createError, created) {155 assert.equal(createError, null);156 assert.equal(created, true);157158 fileService.doesDirectoryExist(shareName, directoryName, function (existsError, exists) {159 assert.equal(existsError, null);160 assert.equal(exists, true);161162 fileService.createDirectoryIfNotExists(shareName, directoryName, function (createError2, created2) {163 assert.equal(createError2, null);164 assert.equal(created2, false);165166 fileService.deleteDirectory(shareName, directoryName, function (deleteError) {167 assert.equal(deleteError, null);168169 fileService.doesDirectoryExist(shareName, directoryName, function (existsError, exists) {170 assert.equal(existsError, null);171 assert.strictEqual(exists, false);172 done();173 });174 });175 });176 });177 });178 });179180 it('should throw if called without a callback', function (done) {181 assert.throws(function () { fileService.createDirectoryIfNotExists('name'); },182 Error183 );184185 done();186 });187 });188189 describe('deleteDirectoryIfExists', function() {190 it('should delete a directory if exists', function (done) {191 fileService.doesDirectoryExist(shareName, directoryName, function(existsError, exists){192 assert.equal(existsError, null);193 assert.strictEqual(exists, false);194195 fileService.deleteDirectoryIfExists(shareName, directoryName, function (deleteError, deleted) {196 assert.equal(deleteError, null);197 assert.strictEqual(deleted, false);198199 fileService.createDirectory(shareName, directoryName, function (createError, directory1, createDirectoryResponse) {200 assert.equal(createError, null);201 assert.notEqual(directory1, null);202 assert.notEqual(directory1.name, null);203 assert.notEqual(directory1.etag, null);204 assert.notEqual(directory1.lastModified, null);205206 assert.equal(createDirectoryResponse.statusCode, HttpConstants.HttpResponseCodes.Created);207208 // delete if exists should succeed209 fileService.deleteDirectoryIfExists(shareName, directoryName, function (deleteError2, deleted2) {210 assert.equal(deleteError2, null);211 assert.strictEqual(deleted2, true);212213 fileService.doesDirectoryExist(shareName, directoryName, function(existsError, exists){214 assert.equal(existsError, null);215 assert.strictEqual(exists, false);216 done();217 });218 });219 });220 });221 });222 });223224 it('should throw if called without a callback', function (done) {225 assert.throws(function () { fileService.deleteDirectoryIfExists('name'); },226 Error227 );228 done();229 });230 });231232 describe('getDirectoryProperties', function () {233 it('should work', function (done) {234 fileService.createDirectoryIfNotExists(shareName, directoryName, function (createError, created) {235 assert.equal(createError, null);236 assert.equal(created, true);237238 fileService.getDirectoryProperties(shareName, directoryName, function (getError, directory2, getResponse) {239 assert.equal(getError, null);240 assert.notEqual(directory2, null);241 assert.notEqual(getResponse, null);242 assert.equal(getResponse.isSuccessful, true);243244 assert.notEqual(directory2.name, null);245 assert.notEqual(directory2.etag, null);246 assert.notEqual(directory2.lastModified, null);247 assert.notEqual(directory2.requestId, null);248249 fileService.deleteDirectory(shareName, directoryName, function (deleteError) {250 assert.equal(deleteError, null);251 done();252 });253 });254 });255 });256257 it('base directory', function (done) {258 fileService.getDirectoryProperties(shareName, '', function (getError, directory2, getResponse) {259 assert.equal(getError, null);260 assert.notEqual(directory2, null);261 assert.notEqual(getResponse, null);262 assert.equal(getResponse.isSuccessful, true);263264 assert.equal(directory2.name, '');265 assert.notEqual(directory2.etag, null);266 assert.notEqual(directory2.lastModified, null);267 assert.notEqual(directory2.requestId, null);268269 done();270 });271 });272 });273274 describe('listFilesAndDirectories', function () {275 var files;276 var directories;277278 var directoryName1 = getName(directoryNamesPrefix);279 var directoryName2 = getName(directoryNamesPrefix);280 var fileName1 = getName(fileNamesPrefix);281 var fileName2 = getName(fileNamesPrefix);282 var fileText1 = 'hello1';283 var fileText2 = 'hello2';284285 var listFilesAndDirectories = function (shareName, directoryName, token, callback) {286 fileService.listFilesAndDirectoriesSegmented(shareName, directoryName, token, function(error, result) {287 assert.equal(error, null);288 files.push.apply(files, result.entries.files);289 directories.push.apply(directories, result.entries.directories);290 var token = result.continuationToken;291 if(token) {292 listFilesAndDirectories(shareName, directoryName, token, callback);293 }294 else {295 callback();296 }297 });298 };299300 beforeEach(function (done) {301 files = [];302 directories = [];303304 fileService.createDirectoryIfNotExists(shareName, directoryName, function (createError, created) {305 assert.equal(createError, null);306 assert.equal(created, true);307 done();308 });309 });310311 it('empty', function (done) {312 listFilesAndDirectories(shareName, directoryName, null, function() {313 assert.equal(files.length, 0);314 done();315 });316 });317318 it('singleDirectory', function (done) {319 fileService.createDirectory(shareName, directoryName + '/' + directoryName1, function (dirErr1) {320 assert.equal(dirErr1, null);321322 // Test listing 1 file323 listFilesAndDirectories(shareName, directoryName, null, function() {324 assert.equal(directories.length, 1);325 assert.equal(directories[0].name, directoryName1);326 done();327 });328 });329 });330331 it('singleFile', function (done) {332 fileService.createFile(shareName, directoryName, fileName1, 0, function (fileErr1) {333 assert.equal(fileErr1, null);334335 // Test listing 1 file336 listFilesAndDirectories(shareName, directoryName, null, function() {337 assert.equal(files.length, 1);338 assert.equal(files[0].name, fileName1);339 done();340 });341 });342 });343344 it('multipleDirectoryAndFile', function (done) {345 fileService.createDirectory(shareName, directoryName + '/' + directoryName1, function (dirErr1) {346 assert.equal(dirErr1, null);347348 fileService.createDirectory(shareName, directoryName + '/' + directoryName2, function (dirErr2) {349 assert.equal(dirErr2, null);350351 fileService.createFile(shareName, directoryName, fileName1, 0, function (fileErr1) {352 assert.equal(fileErr1, null);353354 fileService.createFile(shareName, directoryName, fileName2, 0, function (fileErr2) {355 assert.equal(fileErr2, null);356357 // Test listing 1 file358 listFilesAndDirectories(shareName, directoryName, null, function() {359 assert.equal(directories.length, 2);360 assert.equal(directories[0].name, directoryName1);361 assert.equal(directories[1].name, directoryName2);362 assert.equal(files.length, 2);363 assert.equal(files[0].name, fileName1);364 assert.equal(files[1].name, fileName2);365 done();366 });367 });368 });369 });370 });371 });372373 it('multipleLevelsDirectory', function (done) {374 fileService.createFile(shareName, directoryName, fileName1, 0, function (fileErr1) {375 assert.equal(fileErr1, null);376377 var nextDirectory = directoryName + "/next";378 var dotdotDirectory = nextDirectory + "/..";379380 listFilesAndDirectories(shareName, dotdotDirectory, null, function() {381 assert.equal(directories.length, 0);382 assert.equal(files.length, 1);383 assert.equal(files[0].name, fileName1);384385 files = [];386 directories = [];387388 fileService.createDirectory(shareName, nextDirectory, function(dirErr2) {389 assert.equal(dirErr2, null);390391 listFilesAndDirectories(shareName, dotdotDirectory, null, function() {392 assert.equal(directories.length, 1);393 assert.equal(directories[0].name, "next");394 assert.equal(files.length, 1);395 assert.equal(files[0].name, fileName1);396 done();397 });398 });399 });400 });401 });402 });403});404405function getName (prefix) {406 return prefix + guid.v1().toLowerCase(); ...

Full Screen

Full Screen

CollationServiceTest.js

Source:CollationServiceTest.js Github

copy

Full Screen

1require('should');2const FileService = require('../../lib/services/FileService');3const CollationService = require('../../lib/services/CollationService');4describe('CollationService', () => {5 const home = './test/fixtures';6 before(async () => {7 await FileService.createDirectory(home);8 });9 after(async () => {10 await FileService.deleteDirectory(home);11 });12 describe('getCopyPairs', () => {13 const srcDir = `${home}/synchronize`;14 const targetDir = `${home}/synchronize/target`;15 before(async () => {16 await FileService.createFile(`${srcDir}/01.mp4`);17 await FileService.createFile(`${srcDir}/02.png`);18 await FileService.createFile(`${srcDir}/03/04.png`);19 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);20 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);21 await FileService.createFile(`${srcDir}/05/06/07.png`);22 await FileService.createFile(`${srcDir}/05/06/07.jpg`);23 await FileService.createDirectory(`${srcDir}/05/08/09`);24 });25 after(async () => {26 await FileService.deleteDirectory(`${srcDir}`);27 });28 it('should get Source / Target pairs for all files in a directory', async () => {29 const files = await CollationService.getCopyPairs(`${srcDir}/03`, targetDir);30 files.should.be.an.Array().of.length(1);31 files[0].should.be.an.Array().of.length(2);32 });33 it('should get Source / Target pairs for all files in a directory (recursive)', async () => {34 const opts = { recursive: true };35 const files = await CollationService.getCopyPairs(`${srcDir}`, targetDir, opts);36 files.should.be.an.Array().of.length(6);37 files.forEach(f => f.should.be.an.Array().of.length(2));38 });39 it('should get Source / Target pairs for all files in a directory (w/Source Filter)', async () => {40 const opts = {41 recursive: true,42 sourceFilter: ({ extension }) => extension === 'png',43 };44 const files = await CollationService.getCopyPairs(`${srcDir}`, targetDir, opts);45 files.should.be.an.Array().of.length(3);46 files.forEach(f => f.should.be.an.Array().of.length(2));47 });48 it('should get Source / Target pairs for all files in a directory (w/Custom Target Path Generator)', async () => {49 const opts = {50 recursive: true,51 collateFn: f => `${f.extension}/${f.filename}`,52 };53 const files = await CollationService.getCopyPairs(`${srcDir}`, targetDir, opts);54 files.should.be.an.Array().of.length(6);55 files.forEach(f => f.should.be.an.Array().of.length(2));56 files.forEach(([{ extension, filename }, t]) => {57 t.should.have.property('path').is.a.String().eql(`${targetDir}/${extension}/${filename}`);58 });59 });60 });61 describe('collate', () => {62 const srcDir = `${home}/sort`;63 const targetDir = `${home}/collated`;64 beforeEach(async () => {65 await FileService.createFile(`${srcDir}/01.mp4`);66 await FileService.createFile(`${srcDir}/02.png`);67 await FileService.createFile(`${srcDir}/03/04.png`);68 await FileService.createFile(`${srcDir}/03/sub/another.mp4`);69 await FileService.createDirectory(`${srcDir}/03/sub/donotfind.dir`);70 await FileService.createFile(`${srcDir}/05/06/a.rose.by.any.other.name.png`);71 await FileService.createFile(`${srcDir}/05/06/no_extension`);72 await FileService.createFile(`${srcDir}/05/06/07.png`);73 await FileService.createFile(`${srcDir}/05/06/07.jpg`);74 await FileService.createFile(`${srcDir}/05/07/10.mp4`);75 await FileService.createDirectory(`${srcDir}/05/08/09`);76 await FileService.createFile(`${srcDir}/png/1.arf`);77 await FileService.createFile(`${srcDir}/png/2.arf`);78 await FileService.createFile(`${srcDir}/png/3.arf`);79 });80 afterEach(async () => {81 await FileService.deleteDirectory(srcDir);82 await FileService.deleteDirectory(targetDir);83 });84 it('should move directories by default', async () => {85 const files = await CollationService.collate(`${srcDir}/05/06`, targetDir);86 files.should.be.an.Array().of.length(4);87 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);88 remainingDirs.should.be.an.Array().of.length(4);89 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);90 remainingFiles.should.be.an.Array().of.length(1);91 });92 it('should move directories but not overwrite, and rename by default', async () => {93 await FileService.createFile(`${targetDir}/07.png`);94 await FileService.createFile(`${srcDir}/05/06/08.png`);95 await FileService.createFile(`${targetDir}/a.rose.by.any.other.name.png`);96 await FileService.createFile(`${targetDir}/no_extension`);97 const files = await CollationService.collate(`${srcDir}/05/06`, targetDir);98 files.should.be.an.Array().of.length(5);99 files.forEach((f) => {100 f.should.be.an.Object().has.property('success').eql(true);101 f.should.be.an.Object().not.has.property('error');102 });103 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);104 remainingDirs.should.be.an.Array().of.length(4);105 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);106 remainingFiles.should.be.an.Array().of.length(1);107 });108 it('should move directories but not overwrite, and fail if rename disabled', async () => {109 await FileService.createFile(`${targetDir}/07.png`);110 await FileService.createFile(`${srcDir}/05/06/08.png`);111 await FileService.createFile(`${targetDir}/a.rose.by.any.other.name.png`);112 await FileService.createFile(`${targetDir}/no_extension`);113 const opts = {114 rename: false,115 };116 const files = await CollationService.collate(`${srcDir}/05/06`, targetDir, opts);117 files.should.be.an.Array().of.length(5);118 files[0].should.be.an.Object().has.property('targetExists').eql(false);119 files[1].should.be.an.Object().has.property('targetExists').eql(true);120 files[1].should.be.an.Object().has.property('success').eql(false);121 files[1].should.be.an.Object().has.property('error').of.type('string');122 files[2].should.be.an.Object().has.property('targetExists').eql(false);123 files[3].should.be.an.Object().has.property('success').eql(false);124 files[3].should.be.an.Object().has.property('error').of.type('string');125 files[4].should.be.an.Object().has.property('success').eql(false);126 files[4].should.be.an.Object().has.property('error').of.type('string');127 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);128 remainingDirs.should.be.an.Array().of.length(4);129 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);130 remainingFiles.should.be.an.Array().of.length(4);131 });132 it('should move directories but not overwrite, and fail if rename disabled (dry run)', async () => {133 await FileService.createFile(`${targetDir}/07.png`);134 await FileService.createFile(`${srcDir}/05/06/08.png`);135 await FileService.createFile(`${targetDir}/a.rose.by.any.other.name.png`);136 await FileService.createFile(`${targetDir}/no_extension`);137 const opts = {138 rename: false,139 dryRun: true,140 };141 const files = await CollationService.collate(`${srcDir}/05/06`, targetDir, opts);142 files.should.be.an.Array().of.length(5);143 files[0].should.be.an.Object().has.property('targetExists').eql(false);144 files[1].should.be.an.Object().has.property('targetExists').eql(true);145 files[1].should.be.an.Object().has.property('success').eql(false);146 files[1].should.be.an.Object().has.property('error').of.type('string');147 files[2].should.be.an.Object().has.property('targetExists').eql(false);148 files[3].should.be.an.Object().has.property('success').eql(false);149 files[3].should.be.an.Object().has.property('error').of.type('string');150 files[4].should.be.an.Object().has.property('success').eql(false);151 files[4].should.be.an.Object().has.property('error').of.type('string');152 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);153 remainingDirs.should.be.an.Array().of.length(4);154 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);155 remainingFiles.should.be.an.Array().of.length(6);156 });157 it('should move directories and, optionally, overwrite', async () => {158 await FileService.createFile(`${targetDir}/07.png`);159 await FileService.createFile(`${srcDir}/05/06/08.png`);160 const opts = {161 overwrite: true,162 };163 const files = await CollationService.collate(`${srcDir}/05/06`, targetDir, opts);164 files.should.be.an.Array().of.length(5);165 files[1].should.be.an.Object().has.property('success').eql(true);166 files[1].should.be.an.Object().not.has.property('error');167 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);168 remainingDirs.should.be.an.Array().of.length(4);169 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);170 remainingFiles.should.be.an.Array().of.length(1);171 });172 it('should move and clean directories recursively (but not the source directory, or directories that were untouched)', async () => {173 const opts = { recursive: true };174 const files = await CollationService.collate(`${srcDir}/05`, targetDir, opts);175 files.should.be.an.Array().of.length(5);176 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);177 remainingDirs.should.be.an.Array().of.length(2);178 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);179 remainingFiles.should.be.an.Array().of.length(0);180 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);181 newFiles.should.be.an.Array().of.length(5);182 });183 it('should move and NOT clean directories', async () => {184 const opts = { recursive: true, cleanDirs: false };185 const files = await CollationService.collate(`${srcDir}/05`, targetDir, opts);186 files.should.be.an.Array().of.length(5);187 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);188 remainingDirs.should.be.an.Array().of.length(4);189 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);190 remainingFiles.should.be.an.Array().of.length(0);191 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);192 newFiles.should.be.an.Array().of.length(5);193 });194 it('should copy and NOT clean directories', async () => {195 const opts = { copy: true, recursive: true, cleanDirs: true };196 const files = await CollationService.collate(`${srcDir}/05`, targetDir, opts);197 files.should.be.an.Array().of.length(5);198 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);199 remainingDirs.should.be.an.Array().of.length(4);200 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);201 remainingFiles.should.be.an.Array().of.length(5);202 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);203 newFiles.should.be.an.Array().of.length(5);204 });205 it('should collate with custom filters', async () => {206 const opts = {207 recursive: true,208 cleanDirs: true,209 sourceFilter: ({ extension }) => extension === 'arf',210 };211 const files = await CollationService.collate(`${srcDir}`, targetDir, opts);212 files.should.be.an.Array().of.length(3);213 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}`);214 remainingDirs.should.be.an.Array().of.length(8);215 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}`);216 remainingFiles.should.be.an.Array().of.length(9);217 const newDirs = await FileService.listDirectoriesRecursive(`${targetDir}`);218 newDirs.should.be.an.Array().of.length(1);219 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);220 newFiles.should.be.an.Array().of.length(3);221 });222 it('should collate with custom collation function', async () => {223 const opts = {224 recursive: true,225 cleanDirs: true,226 sourceFilter: ({ extension }) => extension === 'arf',227 collateFn: ({ name, filename }) => `${name}/${filename}`,228 };229 const files = await CollationService.collate(`${srcDir}`, targetDir, opts);230 files.should.be.an.Array().of.length(3);231 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}`);232 remainingDirs.should.be.an.Array().of.length(8);233 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}`);234 remainingFiles.should.be.an.Array().of.length(9);235 const newDirs = await FileService.listDirectoriesRecursive(`${targetDir}`);236 newDirs.should.be.an.Array().of.length(3);237 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);238 newFiles.should.be.an.Array().of.length(3);239 });240 it('should simulate collation w/dry run param', async () => {241 await FileService.createDirectory(targetDir);242 const opts = { recursive: true, cleanDirs: true, dryRun: true };243 const files = await CollationService.collate(`${srcDir}/05`, targetDir, opts);244 files.should.be.an.Array().of.length(5);245 const remainingDirs = await FileService.listDirectoriesRecursive(`${srcDir}/05`);246 remainingDirs.should.be.an.Array().of.length(4);247 const remainingFiles = await FileService.listFilesRecursive(`${srcDir}/05`);248 remainingFiles.should.be.an.Array().of.length(5);249 const newFiles = await FileService.listFilesRecursive(`${targetDir}`);250 newFiles.should.be.an.Array().of.length(0);251 });252 /*253 it.only('should simulate collation w/dry run param', async () => {254 const opts = {255 recursive: true,256 cleanDirs: true,257 dryRun: true,258 sourceFilter: ({ extension }) => extension === 'jpg',259 collateFn: ({ filename }) => `${filename}`,260 };261 const results = await CollationService.collate('/mnt/g/Pictures/INCOMING', targetDir, opts);262 console.log(results);263 }).timeout(400000);264 */265 });...

Full Screen

Full Screen

files.js

Source:files.js Github

copy

Full Screen

1const fs = require('fs')2const { expect } = require('chai')3const express = require('express')4const { Subject } = require('rxjs')5const { config } = require('../lib/config')6const { SettingsService } = require('../lib/services/settings')7const { FileService } = require('../lib/services/files')8const pictureDirectory = __dirname + '/assets/images'9const directoryContents = require('./fixtures/directoryContents')10const { db } = require('./connection/database')11// mock directoryContents12directoryContents.contents.forEach(d => d.directory = pictureDirectory + d.relativeDirectory)13updatedDirectoryContents = directoryContents.contents.map(d => {14 if (d.imageName === 'testFile.jpg') {15 return {16 imageName: 'testFile2.jpg',17 directory: d.directory,18 relativeDirectory: d.relativeDirectory,19 shown: false,20 hidden: false,21 rotate: 022 }23 }24 return d25}).sort((a, b) => (a.relativeDirectory + a.imageName > b.relativeDirectory + b.imageName) ? 1 : -1)26// stub dialog27class Dialog {28 showOpenDialogSync(properties) {29 return [pictureDirectory]30 }31}32// stub slideshow33class SlideShowService {34 imageHistory = { images: [] }35 stopShow() {}36 start() {}37 deleteFromHistory() {}38 next() {}39}40// stub server41class ServerService {42 startStaticFileServer(dir, port) {}43}44// stub event45let subject = new Subject()46const event = {47 sender: {48 send: (eventType, message) => {49 return subject.next(message)50 }51 },52 latest: ''53}54// stub rimraf55let rimraf = (directory, cb) => {56 cb()57}58let removeTemporaryFile = path => {59 if (fs.existsSync(path)) {60 fs.unlinkSync(path)61 }62}63describe('Files service', () => {64 let settingsService65 before(() => {66 const settingsPath = './test/assets/settings.json'67 settingsService = new SettingsService(fs, settingsPath, config)68 const slideShowService = new SlideShowService()69 const serverService = new ServerService(express)70 const dialog = new Dialog71 fileService = new FileService(72 db,73 config,74 { fs, rimraf, dialog },75 { slideShowService, serverService, settingsService}76 )77 }) 78 79 beforeEach(() => {80 subject = new Subject()81 })82 describe('database', () => {83 it('Should empty the database', done => {84 db.remove({ }, { multi: true }, (err, numRemoved) => {85 db.loadDatabase(err => {86 expect(err).to.be.null87 done()88 });89 });90 })91 })92 describe('files', () => {93 it ('Should select the picture directory', async () => {94 await fileService.pickDirectory(event)95 expect(settingsService.get('pictureDirectory')).to.equal(pictureDirectory)96 })97 it ('Should read the picture directory', () => {98 removeTemporaryFile(pictureDirectory + '/testFile2.jpg')99 fs.writeFileSync(pictureDirectory + '/testFile.jpg')100 let entries = fileService.readDirectory(pictureDirectory)101 expect(entries).to.eql(directoryContents.contents)102 })103 it ('Should scan the picture directory for changes', done => {104 fs.writeFileSync(pictureDirectory + '/testFile2.jpg')105 removeTemporaryFile(pictureDirectory + '/testFile.jpg')106 subject.subscribe({107 next: message => {108 expect(message).to.equal('Scan complete!')109 db.find({}, ((err, entries) => {110 const entriesWithoutIds = entries.map(e => {111 delete e._id112 return e113 }).sort((a, b) => (a.relativeDirectory + a.imageName > b.relativeDirectory + b.imageName) ? 1 : -1)114 expect(entriesWithoutIds).to.eql(updatedDirectoryContents)115 done()116 }))117 }118 })119 fileService.scan(event)120 })121 it ('Should hide an image', done => {122 db.findOne({ imageName: 'testFile2.jpg'}, ((err, imageDetails) => {123 subject.subscribe({124 next: message => {125 expect(message).to.equal('Image hidden! You can unhide it from the settings/hidden menu.')126 db.find({ hidden: true }, ((err, entries) => {127 expect(entries.length).to.equal(1)128 expect(entries[0].imageName).to.eql('testFile2.jpg')129 done()130 }) )131 }132 })133 fileService.hideImage(event, imageDetails)134 }))135 })136 it ('Should hide a directory', done => {137 subject.subscribe({138 next: message => {139 expect(message).to.equal('Directory hidden! You can unhide it from the settings/hidden menu.')140 141 db.find({hidden: true }, ((err, entries) => {142 expect(entries.length).to.equal(9)143 done()144 }))145 }146 })147 fileService.hideDirectory(event, { directory: pictureDirectory + '/images1'})148 })149 it ('Should not hide the root directory!', done => {150 subject.subscribe({151 next: message => {152 expect(message).to.equal('You cannot hide a directory that is not part of the assigned picture directory')153 done()154 }155 })156 fileService.hideDirectory(event, { directory: '/' })157 })158 it ('Should not hide the root picture directory', done => {159 subject.subscribe({160 next: message => {161 expect(message).to.equal('You cannot hide the root picture folder!')162 done()163 }164 })165 fileService.hideDirectory(event, { directory: pictureDirectory })166 })167 it ('Should get the list of hidden files', done => {168 const result = updatedDirectoryContents.filter(d => {169 d.hidden = true170 return d.relativeDirectory === '/images1' || d.imageName === 'testFile2.jpg'171 })172 subject.subscribe({173 next: message => {174 message = message175 .map(m => {176 delete m._id177 return m178 })179 .sort((a, b) => (a.relativeDirectory + a.imageName > b.relativeDirectory + b.imageName) ? 1 : -1)180 expect(message.length).to.equal(9)181 expect(message).to.eql(result)182 done()183 }184 })185 fileService.getHiddenList(event)186 })187 it ('Should delete a directory', done => {188 subject.subscribe({189 next: message => {190 expect(message).to.equal('Deleted!')191 db.find({ relativeDirectory: 'images4'}, ((err, results) => {192 expect(results.length).to.equal(0)193 done()194 }))195 }196 })197 fileService.deleteDirectory(event, { directory: pictureDirectory + '/images4' })198 })199 it ('Should not delete the root directory!', done => {200 subject.subscribe({201 next: message => {202 expect(message).to.equal('You cannot delete a directory that is not part of the assigned picture directory')203 done()204 }205 })206 fileService.deleteDirectory(event, { directory: '/' })207 })208 it ('Should not delete the root picture directory', done => {209 subject.subscribe({210 next: message => {211 expect(message).to.equal('You cannot delete the root picture folder!')212 done()213 }214 })215 fileService.deleteDirectory(event, { directory: pictureDirectory })216 })217 it ('Should delete a file', done => {218 db.findOne({ imageName: 'testFile2.jpg'}, ((err, imageDetails) => {219 subject.subscribe({220 next: message => {221 expect(message).to.equal('Deleted!')222 db.find({ imageName: 'testFile2.jpg' }, ((err, entries) => {223 expect(entries.length).to.equal(0)224 done()225 }) )226 }227 })228 fileService.deleteImage(event, imageDetails)229 }))230 })231 it ('Should not delete a file with a bad path name', done => {232 subject.subscribe({233 next: message => {234 expect(message).to.equal('Image not found!')235 done()236 }237 })238 fileService.deleteImage(event, { directory: 'impossible directory', imageName: 'impossible image name'})239 })240 })...

Full Screen

Full Screen

FileServiceTest.js

Source:FileServiceTest.js Github

copy

Full Screen

1const should = require('should');2const FileService = require('../../lib/services/FileService');3describe('FileService', () => {4 const home = './test/fixtures';5 before(async () => {6 await FileService.createDirectory(home);7 });8 after(async () => {9 await FileService.deleteDirectory(home);10 });11 describe('stat', () => {12 const localDir = `${home}/listdirs`;13 before(async () => {14 await FileService.createFile(`${localDir}/01.mp4`);15 await FileService.createFile(`${localDir}/02.png`);16 await FileService.createDirectory(`${localDir}/03`);17 });18 after(async () => {19 await FileService.deleteDirectory(`${localDir}`);20 });21 it('should stat a directory at a specified path', async () => {22 const stat = await FileService.stat(localDir);23 stat.should.be.an.Object();24 stat.should.have.property('path').is.a.String().eql(localDir);25 stat.should.have.property('isDirectory').is.a.Boolean().is.true();26 });27 it('should stat a file at a specified path', async () => {28 const path = `${localDir}/02.png`;29 const stat = await FileService.stat(path);30 stat.should.be.an.Object();31 stat.should.have.property('path').is.a.String().eql(path);32 stat.should.have.property('isDirectory').is.a.Boolean().is.false();33 });34 it('should return null for a non-existent path', async () => {35 const path = `${localDir}/dir-${Date.now()}`;36 const stat = await FileService.stat(path);37 should(stat).be.Null();38 });39 });40 describe('listDirectories', () => {41 const localDir = `${home}/listdirs`;42 before(async () => {43 await FileService.createFile(`${localDir}/01.mp4`);44 await FileService.createFile(`${localDir}/02.png`);45 await FileService.createDirectory(`${localDir}/03`);46 });47 after(async () => {48 await FileService.deleteDirectory(`${localDir}`);49 });50 it('should list directories at specified path', async () => {51 const dirs = await FileService.listDirectories(localDir);52 dirs.should.be.an.Array().of.length(1);53 });54 });55 describe('createDirectory', () => {56 const localDir = `${home}/createdirs`;57 before(async () => {58 await FileService.createFile(`${localDir}/01.mp4`);59 await FileService.createFile(`${localDir}/02.png`);60 });61 after(async () => {62 await FileService.deleteDirectory(`${localDir}`);63 });64 it('should create a new directory at the specified path', async () => {65 const dirArr = [`${localDir}/create/2018-01-01`, `${localDir}/create/2018-01-02`, `${localDir}/create/2018-01-03`];66 await Promise.all(dirArr.map(d => FileService.createDirectory(d)));67 const dirs = await FileService.listDirectories(`${localDir}/create`);68 dirs.should.be.an.Array().of.length(3);69 });70 });71 describe('listFilesAndDirectories', () => {72 const localDir = `${home}/listfiles`;73 before(async () => {74 await FileService.createFile(`${localDir}/01.mp4`);75 await FileService.createFile(`${localDir}/02.png`);76 await FileService.createFile(`${localDir}/03/04.png`);77 await FileService.createFile(`${localDir}/05/06/07.png`);78 });79 after(async () => {80 await FileService.deleteDirectory(`${localDir}`);81 });82 it('should list files and Directories at the specified path (recursive)', async () => {83 const files = await FileService.listFilesAndDirectories(`${localDir}`);84 files.should.be.an.Array().of.length(4);85 });86 it('should list files and Directories at the specified path (recursive)', async () => {87 const files = await FileService.listFilesAndDirectories(`${localDir}`, { recursive: true });88 files.should.be.an.Array().of.length(7);89 });90 it('should throw an error if passed a file', async () => {91 const path = `${localDir}/01.mp4`;92 try {93 await FileService.listFilesAndDirectories(path);94 should(false).be.true();95 } catch (err) {96 err.should.be.Error();97 err.should.have.property('message').is.a.String().eql(`${path} is not a directory`);98 }99 });100 });101 describe('listFiles', () => {102 const localDir = `${home}/listfiles`;103 before(async () => {104 await FileService.createFile(`${localDir}/01.mp4`);105 await FileService.createFile(`${localDir}/02.png`);106 await FileService.createFile(`${localDir}/03/04.png`);107 await FileService.createFile(`${localDir}/05/06/07.png`);108 });109 after(async () => {110 await FileService.deleteDirectory(`${localDir}`);111 });112 it('should list files at the specified path', async () => {113 const files = await FileService.listFiles(`${localDir}`);114 files.should.be.an.Array().of.length(2);115 });116 });117 describe('listFilesRecursive', () => {118 const localDir = `${home}/recursive`;119 before(async () => {120 await FileService.createFile(`${localDir}/01.mp4`);121 await FileService.createFile(`${localDir}/02.png`);122 await FileService.createFile(`${localDir}/03/04.png`);123 await FileService.createFile(`${localDir}/05/06/07.png`);124 await FileService.createDirectory(`${localDir}/05/08/09`);125 });126 after(async () => {127 await FileService.deleteDirectory(`${localDir}`);128 });129 it('should list all files in an entire directory structure', async () => {130 const files = await FileService.listFilesRecursive(localDir);131 files.should.be.an.Array().of.length(4);132 });133 });134 describe('move', () => {135 const localDir = `${home}/move/src`;136 const targetDir = `${home}/move/target`;137 beforeEach(async () => {138 await FileService.createFile(`${localDir}/01.mp4`);139 await FileService.createFile(`${localDir}/02.png`);140 await FileService.createFile(`${localDir}/03/03.png`);141 });142 afterEach(async () => {143 await FileService.deleteDirectory(`${localDir}`);144 await FileService.deleteDirectory(`${targetDir}`);145 });146 it('should move files or paths from the source path to the target path', async () => {147 let files = await FileService.listFilesAndDirectories(localDir);148 files.should.be.an.Array().of.length(3);149 await Promise.all(files.map(({ filename, path }) => {150 const target = `${targetDir}/${filename}`;151 return FileService.move(path, target);152 }));153 files = await FileService.listFilesAndDirectories(localDir);154 files.should.be.an.Array().of.length(0);155 files = await FileService.listFilesAndDirectories(targetDir);156 files.should.be.an.Array().of.length(3);157 });158 it('should not overwrite by default', async () => {159 await FileService.createFile(`${targetDir}/02.png`);160 let files = await FileService.listFilesAndDirectories(localDir);161 files.should.be.an.Array().of.length(3);162 await Promise.all(files.map(async ({ filename, path }) => {163 const target = `${targetDir}/${filename}`;164 try {165 await FileService.move(path, target);166 } catch (err) {167 err.should.be.ok();168 }169 }));170 files = await FileService.listFilesAndDirectories(localDir);171 files.should.be.an.Array().of.length(1);172 files = await FileService.listFilesAndDirectories(targetDir);173 files.should.be.an.Array().of.length(3);174 });175 });...

Full Screen

Full Screen

afc-specs.js

Source:afc-specs.js Github

copy

Full Screen

...19 });20 it('should delete directory', async function () {21 ({server, socket} = await getServerWithFixtures(fixtures.AFC_SUCCESS_RESPONSE));22 service = new AfcService(socket);23 await service.deleteDirectory('something');24 });25 it('should list directory', async function () {26 ({server, socket} = await getServerWithFixtures(fixtures.AFC_LIST_DIR_RESPONSE));27 service = new AfcService(socket);28 const items = await service.listDirectory('/');29 items.should.contain('Photos');30 });31 it('should get file info', async function () {32 ({server, socket} = await getServerWithFixtures(fixtures.AFC_FILE_INFO_RESPONSE));33 service = new AfcService(socket);34 const info = await service.getFileInfo('Photos');35 info.birthtimeMs.should.be.equal(1494244521000);36 info.blocks.should.be.equal(0);37 info.mtimeMs.should.be.equal(1494244521000);...

Full Screen

Full Screen

delete-directory.js

Source:delete-directory.js Github

copy

Full Screen

1'use strict';2const middy = require('@middy/core');3const cors = require('@middy/http-cors');4const DirectoryService = require('../../services/directory-service');5const deleteDirectory = async (event) => {6 const { directory, path } = JSON.parse(event.body);7 try {8 const user = JSON.parse(event.requestContext.authorizer.user);9 const email = user.UserAttributes.find(attr => attr.Name === 'email').Value;10 const directoryService = new DirectoryService(email);11 await directoryService.deleteDirectory(directory, path ? path : '/');12 return {13 statusCode: 200,14 };15 } catch (err) {16 return {17 statusCode: err.statusCode,18 body: JSON.stringify(err)19 }20 }21}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6const client = wdio.remote(options);7async function main() {8 await client.init();9 await client.deleteDirectory('Private Documents');10 await client.end();11}12main();13[debug] [XCUITest] at XCUITestDriver.deleteDirectory (/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/lib/commands/file-movement.js:59:13)14[debug] [XCUITest] at process._tickCallback (internal/process/next_tick.js:68:7)15[debug] [BaseDriver] Event 'newSessionStarted' logged at 1554847371559 (16:22:51 GMT+0530 (IST))16[debug] [W3C] at XCUITestDriver.deleteDirectory (/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/lib/commands/file-movement.js:59:13)17[debug] [W3C] at process._tickCallback (internal/process/next_tick.js:68:7)18[HTTP] {}19* Appium version (or git revision) that exhibits the issue: 1.11.120* Last Appium version that did not exhibit the issue (if applicable):

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require(‘webdriverio’);2const opts = {3 capabilities: {4 }5};6async function main () {7 const client = await wdio.remote(opts);8 await client.deleteDirectory(‘/path/to/your/directory’);9 await client.deleteSession();10}11main();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var assert = require('assert');3 withCapabilities({4 build();5driver.manage().timeouts().implicitlyWait(5000);6driver.execute('mobile: createDirectory', { path: '/Documents/test' });7driver.execute('mobile: deleteDirectory', { path: '/Documents/test' });8driver.quit();9var webdriver = require('selenium-webdriver');10var assert = require('assert');11 withCapabilities({12 build();13driver.manage().timeouts().implicitlyWait(5000);14driver.execute('mobile: createFile', { path: '/Documents/test.txt' });15driver.execute('mobile: deleteFile', { path: '/Documents/test.txt' });16driver.quit();17var webdriver = require('selenium-webdriver');18var assert = require('assert');19 withCapabilities({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { remote } = require('webdriverio');2const { exec } = require('child_process');3const opts = {4 capabilities: {5 },6};7const client = remote(opts);8async function start() {9 try {10 await client.init();11 const deleteDirectory = await client.execute('mobile: deleteDirectory', {12 });13 console.log(deleteDirectory);14 } catch (err) {15 console.error(err);16 } finally {17 await client.deleteSession();18 }19}20start();21const { remote } = require('webdriverio');22const { exec } = require('child_process');23const opts = {24 capabilities: {25 },26};27const client = remote(opts);28async function start() {29 try {30 await client.init();31 const deleteDirectory = await client.execute('mobile: deleteDirectory', {32 });33 console.log(deleteDirectory);34 } catch (err) {35 console.error(err);36 } finally {37 await client.deleteSession();38 }39}40start();41const { remote } = require('webdriverio');42const { exec } = require('child_process');43const opts = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const should = chai.should();6const serverConfig = {7};8const desiredCaps = {9};10describe('delete directory', function () {11 this.timeout(300000);12 let driver;13 before(async function () {14 driver = wd.promiseChainRemote(serverConfig);15 await driver.init(desiredCaps);16 });17 it('should delete the directory', async function () {18 await driver.deleteDirectory('/Documents');19 });20});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const { assert } = require('chai');3const path = require('path');4const fs = require('fs');5const { exec } = require('child_process');6const { async } = require('asyncawait');7const { await } = require('asyncawait');8const { config } = require('./helpers/config');9describe('Delete Directory', function () {10 this.timeout(config.defaultTimeout);11 let driver;12 let allPassed = true;13 before(async(() => {14 driver = wd.promiseChainRemote(config.host, config.port);15 config.capabilities.app = path.resolve(config.defaultAppPath, config.defaultApp);16 await (driver.init(config.capabilities));17 }));18 after(async(() => {19 await (driver.quit());20 }));21 afterEach(function () {22 allPassed = allPassed && this.currentTest.state === 'passed';23 });24 it('should delete directory', async(() => {25 const path = '/Documents/MyFolder';26 const result = await (driver.execute('mobile: deleteDirectory', { path }));27 assert.equal(result, true);28 }));29});30Your name to display (optional):31Your name to display (optional):32Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const { execSync } = require('child_process');2const fs = require('fs');3const path = require('path');4const { remote } = require('webdriverio');5const { mkdirp } = require('fs-extra');6const { v4: uuidv4 } = require('uuid');7const dir = path.join(__dirname, uuidv4());8const file = path.join(dir, 'file');9async function main() {10 execSync('appium &', {stdio: 'ignore'});11 execSync('xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=00008020-001C3C3E0E28002E test > /dev/null 2>&1 &', {stdio: 'ignore'});12 await new Promise((resolve) => setTimeout(resolve, 10000));13 const client = await remote({14 capabilities: {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require("webdriverio");2const opts = {3 capabilities: {4 },5};6const client = wdio.remote(opts);7async function main() {8 await client.init();9 const {value} = await client.execute("mobile: deleteDirectory", {10 });11 console.log(value);12}13main();14const adb = require('appium-adb').adb;15const adbPath = '/Users/user/Library/Android/sdk/platform-tools/adb';16async function main() {17 const adbObj = await adb.createADB({18 });19 await adbObj.shell(['rm', '-r', '/data/user/0/com.myapp/files/MyFolder']);20}21main();22const wdio = require("webdriverio");23const opts = {24 capabilities: {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful