Best JavaScript code snippet using cypress
verify_spec.js
Source:verify_spec.js
...69 })70 })71 it('adds --no-sandbox when user is root', () => {72 // make it think the executable exists73 createfs({74 alreadyVerified: false,75 executable: mockfs.file({ mode: 0o777 }),76 packageVersion,77 })78 process.geteuid.returns(0) // user is root79 util.exec.resolves({80 stdout: '222',81 stderr: '',82 })83 return verify.start()84 .then(() => {85 expect(util.exec).to.be.calledWith(executablePath, ['--no-sandbox', '--smoke-test', '--ping=222'])86 })87 })88 it('adds --no-sandbox when user is non-root', () => {89 // make it think the executable exists90 createfs({91 alreadyVerified: false,92 executable: mockfs.file({ mode: 0o777 }),93 packageVersion,94 })95 process.geteuid.returns(1000) // user is non-root96 util.exec.resolves({97 stdout: '222',98 stderr: '',99 })100 return verify.start()101 .then(() => {102 expect(util.exec).to.be.calledWith(executablePath, ['--no-sandbox', '--smoke-test', '--ping=222'])103 })104 })105 it('is noop when binary is already verified', () => {106 // make it think the executable exists and is verified107 createfs({108 alreadyVerified: true,109 executable: mockfs.file({ mode: 0o777 }),110 packageVersion,111 })112 return verify.start().then(() => {113 // nothing should have been logged to stdout114 // since no verification took place115 expect(stdout.toString()).to.be.empty116 expect(util.exec).not.to.be.called117 })118 })119 it('logs warning when installed version does not match verified version', () => {120 createfs({121 alreadyVerified: true,122 executable: mockfs.file({ mode: 0o777 }),123 packageVersion: 'bloop',124 })125 return verify126 .start()127 .then(() => {128 throw new Error('should have caught error')129 })130 .catch(() => {131 return snapshot(132 'warning installed version does not match verified version 1',133 normalize(stdout.toString()),134 )135 })136 })137 it('logs error and exits when executable cannot be found', () => {138 return verify139 .start()140 .then(() => {141 throw new Error('should have caught error')142 })143 .catch((err) => {144 logger.error(err)145 snapshot('executable cannot be found 1', normalize(stdout.toString()))146 })147 })148 it('logs error when child process hangs', () => {149 createfs({150 alreadyVerified: false,151 executable: mockfs.file({ mode: 0o777 }),152 packageVersion,153 })154 sinon.stub(cp, 'spawn').callsFake(mockSpawn((cp) => {155 cp.stderr.write('some stderr')156 cp.stdout.write('some stdout')157 }))158 util.exec.restore()159 return verify160 .start({ smokeTestTimeout: 1 })161 .catch((err) => {162 logger.error(err)163 })164 .then(() => {165 snapshot(normalize(slice(stdout.toString())))166 })167 })168 it('logs error when child process returns incorrect stdout (stderr when exists)', () => {169 createfs({170 alreadyVerified: false,171 executable: mockfs.file({ mode: 0o777 }),172 packageVersion,173 })174 sinon.stub(cp, 'spawn').callsFake(mockSpawn((cp) => {175 cp.stderr.write('some stderr')176 cp.stdout.write('some stdout')177 cp.emit('exit', 0, null)178 cp.end()179 }))180 util.exec.restore()181 return verify182 .start()183 .catch((err) => {184 logger.error(err)185 })186 .then(() => {187 snapshot(normalize(slice(stdout.toString())))188 })189 })190 it('logs error when child process returns incorrect stdout (stdout when no stderr)', () => {191 createfs({192 alreadyVerified: false,193 executable: mockfs.file({ mode: 0o777 }),194 packageVersion,195 })196 sinon.stub(cp, 'spawn').callsFake(mockSpawn((cp) => {197 cp.stdout.write('some stdout')198 cp.emit('exit', 0, null)199 cp.end()200 }))201 util.exec.restore()202 return verify203 .start()204 .catch((err) => {205 logger.error(err)206 })207 .then(() => {208 snapshot(normalize(slice(stdout.toString())))209 })210 })211 it('sets ELECTRON_ENABLE_LOGGING without mutating process.env', () => {212 createfs({213 alreadyVerified: false,214 executable: mockfs.file({ mode: 0o777 }),215 packageVersion,216 })217 expect(process.env.ELECTRON_ENABLE_LOGGING).to.be.undefined218 util.exec.resolves()219 sinon.stub(util, 'stdoutLineMatches').returns(true)220 return verify221 .start()222 .then(() => {223 expect(process.env.ELECTRON_ENABLE_LOGGING).to.be.undefined224 const stdioOptions = util.exec.firstCall.args[2]225 expect(stdioOptions).to.include({226 timeout: verify.VERIFY_TEST_RUNNER_TIMEOUT_MS,227 })228 expect(stdioOptions.env).to.include({229 ELECTRON_ENABLE_LOGGING: true,230 })231 })232 })233 describe('with force: true', () => {234 beforeEach(() => {235 createfs({236 alreadyVerified: true,237 executable: mockfs.file({ mode: 0o777 }),238 packageVersion,239 })240 })241 it('shows full path to executable when verifying', () => {242 return verify.start({ force: true }).then(() => {243 snapshot('verification with executable 1', normalize(stdout.toString()))244 })245 })246 it('clears verified version from state if verification fails', () => {247 util.exec.restore()248 sinon249 .stub(util, 'exec')250 .withArgs(executablePath)251 .rejects({252 code: 1,253 stderr: 'an error about dependencies',254 })255 return verify256 .start({ force: true })257 .then(() => {258 throw new Error('Should have thrown')259 })260 .catch((err) => {261 logger.error(err)262 })263 .then(() => {264 return fs.pathExistsAsync(binaryStatePath)265 })266 .then((exists) => {267 return expect(exists).to.eq(false)268 })269 .then(() => {270 return snapshot(271 'fails verifying Cypress 1',272 normalize(slice(stdout.toString())),273 )274 })275 })276 })277 describe('smoke test with DEBUG output', () => {278 beforeEach(() => {279 const stdoutWithDebugOutput = stripIndent`280 some debug output281 date: more debug output282 222283 after that more text284 `285 util.exec.withArgs(executablePath).resolves({286 stdout: stdoutWithDebugOutput,287 })288 createfs({289 alreadyVerified: false,290 executable: mockfs.file({ mode: 0o777 }),291 packageVersion,292 })293 })294 it('finds ping value in the verbose output', () => {295 return verify.start().then(() => {296 snapshot('verbose stdout output 1', normalize(stdout.toString()))297 })298 })299 })300 describe('smoke test retries on bad display with our Xvfb', () => {301 let restore302 beforeEach(() => {303 restore = mockedEnv({304 DISPLAY: 'test-display',305 })306 createfs({307 alreadyVerified: false,308 executable: mockfs.file({ mode: 0o777 }),309 packageVersion,310 })311 util.exec.restore()312 sinon.spy(logger, 'warn')313 })314 afterEach(() => {315 restore()316 })317 it('successfully retries with our Xvfb on Linux', () => {318 // initially we think the user has everything set319 xvfb.isNeeded.returns(false)320 sinon.stub(util, 'isPossibleLinuxWithIncorrectDisplay').returns(true)321 sinon.stub(util, 'exec').callsFake(() => {322 const firstSpawnError = new Error('')323 // this message contains typical Gtk error shown if X11 is incorrect324 // like in the case of DISPLAY=987325 firstSpawnError.stderr = stripIndent`326 [some noise here] Gtk: cannot open display: 987327 and maybe a few other lines here with weird indent328 `329 firstSpawnError.stdout = ''330 // the second time the binary returns expected ping331 util.exec.withArgs(executablePath).resolves({332 stdout: '222',333 })334 return Promise.reject(firstSpawnError)335 })336 return verify.start().then(() => {337 expect(util.exec).to.have.been.calledTwice338 // user should have been warned339 expect(logger.warn).to.have.been.calledWithMatch(340 'This is likely due to a misconfigured DISPLAY environment variable.',341 )342 })343 })344 it('fails on both retries with our Xvfb on Linux', () => {345 // initially we think the user has everything set346 xvfb.isNeeded.returns(false)347 sinon.stub(util, 'isPossibleLinuxWithIncorrectDisplay').returns(true)348 sinon.stub(util, 'exec').callsFake(() => {349 os.platform.returns('linux')350 expect(xvfb.start).to.not.have.been.called351 const firstSpawnError = new Error('')352 // this message contains typical Gtk error shown if X11 is incorrect353 // like in the case of DISPLAY=987354 firstSpawnError.stderr = stripIndent`355 [some noise here] Gtk: cannot open display: 987356 and maybe a few other lines here with weird indent357 `358 firstSpawnError.stdout = ''359 // the second time it runs, it fails for some other reason360 const secondMessage = stripIndent`361 [some noise here] Gtk: cannot open display: 987362 some other error363 again with364 some weird indent365 `366 util.exec.withArgs(executablePath).rejects(new Error(secondMessage))367 return Promise.reject(firstSpawnError)368 })369 return verify.start().then(() => {370 throw new Error('Should have failed')371 })372 .catch((e) => {373 expect(util.exec).to.have.been.calledTwice374 // second time around we should have called Xvfb375 expect(xvfb.start).to.have.been.calledOnce376 expect(xvfb.stop).to.have.been.calledOnce377 // user should have been warned378 expect(logger.warn).to.have.been.calledWithMatch('DISPLAY was set to: "test-display"')379 snapshot('tried to verify twice, on the first try got the DISPLAY error', e.message)380 })381 })382 })383 it('logs an error if Cypress executable does not exist', () => {384 createfs({385 alreadyVerified: false,386 executable: false,387 packageVersion,388 })389 return verify390 .start()391 .then(() => {392 throw new Error('Should have thrown')393 })394 .catch((err) => {395 stdout = Stdout.capture()396 logger.error(err)397 return snapshot('no Cypress executable 1', normalize(stdout.toString()))398 })399 })400 it('logs an error if Cypress executable does not have permissions', () => {401 mockfs.restore()402 createfs({403 alreadyVerified: false,404 executable: mockfs.file({ mode: 0o666 }),405 packageVersion,406 })407 return verify408 .start()409 .then(() => {410 throw new Error('Should have thrown')411 })412 .catch((err) => {413 stdout = Stdout.capture()414 logger.error(err)415 return snapshot(416 'Cypress non-executable permissions 1',417 normalize(stdout.toString()),418 )419 })420 })421 it('logs and runs when current version has not been verified', () => {422 createfs({423 alreadyVerified: false,424 executable: mockfs.file({ mode: 0o777 }),425 packageVersion,426 })427 return verify.start().then(() => {428 return snapshot(429 'current version has not been verified 1',430 normalize(stdout.toString()),431 )432 })433 })434 it('logs and runs when installed version is different than package version', () => {435 createfs({436 alreadyVerified: false,437 executable: mockfs.file({ mode: 0o777 }),438 packageVersion: '7.8.9',439 })440 return verify.start().then(() => {441 return snapshot(442 'different version installed 1',443 normalize(stdout.toString()),444 )445 })446 })447 it('is silent when logLevel is silent', () => {448 createfs({449 alreadyVerified: false,450 executable: mockfs.file({ mode: 0o777 }),451 packageVersion,452 })453 process.env.npm_config_loglevel = 'silent'454 return verify.start().then(() => {455 return snapshot(456 'silent verify 1',457 normalize(`[no output]${stdout.toString()}`),458 )459 })460 })461 it('turns off Opening Cypress...', () => {462 createfs({463 alreadyVerified: true,464 executable: mockfs.file({ mode: 0o777 }),465 packageVersion: '7.8.9',466 })467 return verify468 .start({469 welcomeMessage: false,470 })471 .then(() => {472 return snapshot('no welcome message 1', normalize(stdout.toString()))473 })474 })475 it('logs error when fails smoke test unexpectedly without stderr', () => {476 createfs({477 alreadyVerified: false,478 executable: mockfs.file({ mode: 0o777 }),479 packageVersion,480 })481 util.exec.restore()482 sinon.stub(util, 'exec').rejects({483 stderr: '',484 stdout: '',485 message: 'Error: EPERM NOT PERMITTED',486 })487 return verify488 .start()489 .then(() => {490 throw new Error('Should have thrown')491 })492 .catch((err) => {493 stdout = Stdout.capture()494 logger.error(err)495 return snapshot('fails with no stderr 1', normalize(stdout.toString()))496 })497 })498 describe('on linux', () => {499 beforeEach(() => {500 xvfb.isNeeded.returns(true)501 createfs({502 alreadyVerified: false,503 executable: mockfs.file({ mode: 0o777 }),504 packageVersion,505 })506 })507 it('starts xvfb', () => {508 return verify.start().then(() => {509 expect(xvfb.start).to.be.called510 })511 })512 it('stops xvfb on spawned process close', () => {513 return verify.start().then(() => {514 expect(xvfb.stop).to.be.called515 })516 })517 it('logs error and exits when starting xvfb fails', () => {518 const err = new Error('test without xvfb')519 xvfb.start.restore()520 err.nonZeroExitCode = true521 err.stack = 'xvfb? no dice'522 sinon.stub(xvfb._xvfb, 'startAsync').rejects(err)523 return verify.start()524 .then(() => {525 throw new Error('should have thrown')526 })527 .catch((err) => {528 expect(xvfb.stop).to.be.calledOnce529 logger.error(err)530 snapshot('xvfb fails 1', normalize(slice(stdout.toString())))531 })532 })533 })534 describe('when running in CI', () => {535 beforeEach(() => {536 createfs({537 alreadyVerified: false,538 executable: mockfs.file({ mode: 0o777 }),539 packageVersion,540 })541 util.isCi.returns(true)542 })543 it('uses verbose renderer', () => {544 return verify.start().then(() => {545 snapshot('verifying in ci 1', normalize(stdout.toString()))546 })547 })548 it('logs error when binary not found', () => {549 mockfs({})550 return verify551 .start()552 .then(() => {553 throw new Error('Should have thrown')554 })555 .catch((err) => {556 logger.error(err)557 snapshot('error binary not found in ci 1', normalize(stdout.toString()))558 })559 })560 })561 describe('when env var CYPRESS_RUN_BINARY', () => {562 it('can validate and use executable', () => {563 const envBinaryPath = '/custom/Contents/MacOS/Cypress'564 const realEnvBinaryPath = `/real${envBinaryPath}`565 process.env.CYPRESS_RUN_BINARY = envBinaryPath566 createfs({567 alreadyVerified: false,568 executable: mockfs.file({ mode: 0o777 }),569 packageVersion,570 customDir: '/real/custom',571 })572 util.exec573 .withArgs(realEnvBinaryPath, ['--no-sandbox', '--smoke-test', '--ping=222'])574 .resolves(spawnedProcess)575 return verify.start().then(() => {576 expect(util.exec.firstCall.args[0]).to.equal(realEnvBinaryPath)577 snapshot('valid CYPRESS_RUN_BINARY 1', normalize(stdout.toString()))578 })579 })580 _.each(['darwin', 'linux', 'win32'], (platform) => {...
FileSystemInfo.unittest.js
Source:FileSystemInfo.unittest.js
1"use strict";2const { createFsFromVolume, Volume } = require("memfs");3const util = require("util");4const FileSystemInfo = require("../lib/FileSystemInfo");5const { buffersSerializer } = require("../lib/util/serialization");6describe("FileSystemInfo", () => {7 const files = [8 "/path/file.txt",9 "/path/nested/deep/file.txt",10 "/path/nested/deep/ignored.txt",11 "/path/context+files/file.txt",12 "/path/context+files/sub/file.txt",13 "/path/context+files/sub/ignored.txt",14 "/path/node_modules/package/file.txt",15 "/path/cache/package-1234/file.txt",16 "/path/circular/circular/file2.txt",17 "/path/nested/deep/symlink/file.txt",18 "/path/context+files/sub/symlink/file.txt",19 "/path/context/sub/symlink/file.txt",20 "/path/missing.txt"21 ];22 const directories = [23 "/path/context+files",24 "/path/context",25 "/path/missing",26 "/path/node_modules/package",27 "/path/node_modules/missing",28 "/path/cache/package-1234",29 "/path/cache/package-missing"30 ];31 const missing = [32 "/path/package.json",33 "/path/file2.txt",34 "/path/context+files/file2.txt",35 "/path/node_modules/package.txt",36 "/path/node_modules/package/missing.txt",37 "/path/cache/package-2345",38 "/path/cache/package-1234/missing.txt",39 "/path/ignored.txt"40 ];41 const ignored = [42 "/path/nested/deep/ignored.txt",43 "/path/context+files/sub/ignored.txt",44 "/path/context/sub/ignored.txt",45 "/path/ignored.txt",46 "/path/node_modules/package/ignored.txt",47 "/path/cache/package-1234/ignored.txt"48 ];49 const managedPaths = ["/path/node_modules"];50 const immutablePaths = ["/path/cache"];51 const createFs = () => {52 const fs = createFsFromVolume(new Volume());53 fs.mkdirpSync("/path/context+files/sub");54 fs.mkdirpSync("/path/context/sub");55 fs.mkdirpSync("/path/nested/deep");56 fs.mkdirpSync("/path/node_modules/package");57 fs.mkdirpSync("/path/cache/package-1234");58 fs.mkdirpSync("/path/folder/context");59 fs.mkdirpSync("/path/folder/context+files");60 fs.mkdirpSync("/path/folder/nested");61 fs.writeFileSync("/path/file.txt", "Hello World");62 fs.writeFileSync("/path/file2.txt", "Hello World2");63 fs.writeFileSync("/path/nested/deep/file.txt", "Hello World");64 fs.writeFileSync("/path/nested/deep/ignored.txt", "Ignored");65 fs.writeFileSync("/path/context+files/file.txt", "Hello World");66 fs.writeFileSync("/path/context+files/file2.txt", "Hello World2");67 fs.writeFileSync("/path/context+files/sub/file.txt", "Hello World");68 fs.writeFileSync("/path/context+files/sub/file2.txt", "Hello World2");69 fs.writeFileSync("/path/context+files/sub/file3.txt", "Hello World3");70 fs.writeFileSync("/path/context+files/sub/ignored.txt", "Ignored");71 fs.writeFileSync("/path/context/file.txt", "Hello World");72 fs.writeFileSync("/path/context/file2.txt", "Hello World2");73 fs.writeFileSync("/path/context/sub/file.txt", "Hello World");74 fs.writeFileSync("/path/context/sub/file2.txt", "Hello World2");75 fs.writeFileSync("/path/context/sub/file3.txt", "Hello World3");76 fs.writeFileSync("/path/context/sub/ignored.txt", "Ignored");77 fs.writeFileSync(78 "/path/node_modules/package/package.json",79 JSON.stringify({ name: "package", version: "1.0.0" })80 );81 fs.writeFileSync("/path/node_modules/package/file.txt", "Hello World");82 fs.writeFileSync("/path/node_modules/package/ignored.txt", "Ignored");83 fs.writeFileSync(84 "/path/cache/package-1234/package.json",85 JSON.stringify({ name: "package", version: "1.0.0" })86 );87 fs.writeFileSync("/path/cache/package-1234/file.txt", "Hello World");88 fs.writeFileSync("/path/cache/package-1234/ignored.txt", "Ignored");89 fs.symlinkSync("/path", "/path/circular", "dir");90 fs.writeFileSync("/path/folder/context/file.txt", "Hello World");91 fs.writeFileSync("/path/folder/context+files/file.txt", "Hello World");92 fs.writeFileSync("/path/folder/nested/file.txt", "Hello World");93 fs.symlinkSync("/path/folder/context", "/path/context/sub/symlink", "dir");94 fs.symlinkSync(95 "/path/folder/context+files",96 "/path/context+files/sub/symlink",97 "dir"98 );99 fs.symlinkSync("/path/folder/nested", "/path/nested/deep/symlink", "dir");100 return fs;101 };102 const createFsInfo = fs => {103 const logger = {104 error: (...args) => {105 throw new Error(util.format(...args));106 }107 };108 const fsInfo = new FileSystemInfo(fs, {109 logger,110 managedPaths,111 immutablePaths,112 hashFunction: "sha256"113 });114 for (const method of ["warn", "info", "log", "debug"]) {115 fsInfo.logs = [];116 fsInfo[method] = [];117 logger[method] = (...args) => {118 const msg = util.format(...args);119 fsInfo[method].push(msg);120 fsInfo.logs.push(`[${method}] ${msg}`);121 };122 }123 fsInfo.addFileTimestamps(new Map(ignored.map(i => [i, "ignore"])));124 return fsInfo;125 };126 const createSnapshot = (fs, options, callback) => {127 const fsInfo = createFsInfo(fs);128 fsInfo.createSnapshot(129 Date.now() + 10000,130 files,131 directories,132 missing,133 options,134 (err, snapshot) => {135 if (err) return callback(err);136 snapshot.name = "initial snapshot";137 // create another one to test the caching138 fsInfo.createSnapshot(139 Date.now() + 10000,140 files,141 directories,142 missing,143 options,144 (err, snapshot2) => {145 if (err) return callback(err);146 snapshot2.name = "cached snapshot";147 callback(null, snapshot, snapshot2);148 }149 );150 }151 );152 };153 const clone = object => {154 const serialized = buffersSerializer.serialize(object, {});155 return buffersSerializer.deserialize(serialized, {});156 };157 const expectSnapshotsState = (158 fs,159 snapshot,160 snapshot2,161 expected,162 callback163 ) => {164 expectSnapshotState(fs, snapshot, expected, err => {165 if (err) return callback(err);166 if (!snapshot2) return callback();167 expectSnapshotState(fs, snapshot2, expected, callback);168 });169 };170 const expectSnapshotState = (fs, snapshot, expected, callback) => {171 const fsInfo = createFsInfo(fs);172 const details = snapshot => `${fsInfo.logs.join("\n")}173${util.inspect(snapshot, false, Infinity, true)}`;174 fsInfo.checkSnapshotValid(snapshot, (err, valid) => {175 if (err) return callback(err);176 if (valid !== expected) {177 return callback(178 new Error(`Expected snapshot to be ${179 expected ? "valid" : "invalid"180 } but it is ${valid ? "valid" : "invalid"}:181${details(snapshot)}`)182 );183 }184 // Another try to check if direct caching works185 fsInfo.checkSnapshotValid(snapshot, (err, valid) => {186 if (err) return callback(err);187 if (valid !== expected) {188 return callback(189 new Error(`Expected snapshot lead to the same result when directly cached:190${details(snapshot)}`)191 );192 }193 // Another try to check if indirect caching works194 fsInfo.checkSnapshotValid(clone(snapshot), (err, valid) => {195 if (err) return callback(err);196 if (valid !== expected) {197 return callback(198 new Error(`Expected snapshot lead to the same result when indirectly cached:199${details(snapshot)}`)200 );201 }202 callback();203 });204 });205 });206 };207 const updateFile = (fs, filename) => {208 const oldContent = fs.readFileSync(filename, "utf-8");209 if (filename.endsWith(".json")) {210 const data = JSON.parse(oldContent);211 fs.writeFileSync(212 filename,213 JSON.stringify({214 ...data,215 version: data.version + ".1"216 })217 );218 } else {219 fs.writeFileSync(220 filename,221 oldContent + "!"222 );223 }224 };225 for (const [name, options] of [226 ["timestamp", { timestamp: true }],227 ["hash", { hash: true }],228 ["tsh", { timestamp: true, hash: true }]229 ]) {230 describe(`${name} mode`, () => {231 it("should always accept an empty snapshot", done => {232 const fs = createFs();233 const fsInfo = createFsInfo(fs);234 fsInfo.createSnapshot(235 Date.now() + 10000,236 [],237 [],238 [],239 options,240 (err, snapshot) => {241 if (err) return done(err);242 const fs = createFs();243 expectSnapshotState(fs, snapshot, true, done);244 }245 );246 });247 it("should accept a snapshot when fs is unchanged", done => {248 const fs = createFs();249 createSnapshot(fs, options, (err, snapshot, snapshot2) => {250 if (err) return done(err);251 expectSnapshotsState(fs, snapshot, snapshot2, true, done);252 });253 });254 const ignoredFileChanges = [255 "/path/nested/deep/ignored.txt",256 "/path/context+files/sub/ignored.txt"257 ];258 for (const fileChange of [259 "/path/file.txt",260 "/path/file2.txt",261 "/path/nested/deep/file.txt",262 "/path/context+files/file.txt",263 "/path/context+files/file2.txt",264 "/path/context+files/sub/file.txt",265 "/path/context+files/sub/file2.txt",266 "/path/context+files/sub/file3.txt",267 "/path/context/file.txt",268 "/path/context/file2.txt",269 "/path/context/sub/file.txt",270 "/path/context/sub/file2.txt",271 "/path/context/sub/file3.txt",272 "/path/node_modules/package/package.json",273 "/path/folder/context/file.txt",274 "/path/folder/context+files/file.txt",275 "/path/folder/nested/file.txt",276 ...(name !== "timestamp" ? ignoredFileChanges : []),277 ...(name === "hash" ? ["/path/context/sub/ignored.txt"] : [])278 ]) {279 it(`should invalidate the snapshot when ${fileChange} is changed`, done => {280 const fs = createFs();281 createSnapshot(fs, options, (err, snapshot, snapshot2) => {282 if (err) return done(err);283 updateFile(fs, fileChange);284 expectSnapshotsState(fs, snapshot, snapshot2, false, done);285 });286 });287 }288 for (const fileChange of [289 "/path/node_modules/package/file.txt",290 "/path/node_modules/package/ignored.txt",291 "/path/cache/package-1234/package.json",292 "/path/cache/package-1234/file.txt",293 "/path/cache/package-1234/ignored.txt",294 ...(name === "timestamp" ? ignoredFileChanges : []),295 ...(name !== "hash" ? ["/path/context/sub/ignored.txt"] : [])296 ]) {297 it(`should not invalidate the snapshot when ${fileChange} is changed`, done => {298 const fs = createFs();299 createSnapshot(fs, options, (err, snapshot, snapshot2) => {300 if (err) return done(err);301 updateFile(fs, fileChange);302 expectSnapshotsState(fs, snapshot, snapshot2, true, done);303 });304 });305 }306 for (const newFile of [307 "/path/package.json",308 "/path/file2.txt",309 "/path/context+files/file2.txt",310 "/path/node_modules/package.txt"311 ]) {312 it(`should invalidate the snapshot when ${newFile} is created`, done => {313 const fs = createFs();314 createSnapshot(fs, options, (err, snapshot, snapshot2) => {315 if (err) return done(err);316 fs.writeFileSync(newFile, "New file");317 expectSnapshotsState(fs, snapshot, snapshot2, false, done);318 });319 });320 }321 for (const newFile of [322 "/path/node_modules/package/missing.txt",323 "/path/cache/package-1234/missing.txt",324 "/path/cache/package-2345",325 "/path/ignored.txt"326 ]) {327 it(`should not invalidate the snapshot when ${newFile} is created`, done => {328 const fs = createFs();329 createSnapshot(fs, options, (err, snapshot, snapshot2) => {330 if (err) return done(err);331 fs.writeFileSync(newFile, "New file");332 expectSnapshotsState(fs, snapshot, snapshot2, true, done);333 });334 });335 }336 if (name !== "timestamp") {337 it("should not invalidate snapshot when only timestamps have changed", done => {338 const fs = createFs();339 createSnapshot(fs, options, (err, snapshot, snapshot2) => {340 if (err) return done(err);341 const fs = createFs();342 expectSnapshotsState(fs, snapshot, snapshot2, true, done);343 });344 });345 }346 });347 }...
Platform.js
Source:Platform.js
1let minimatch = require("minimatch-browser");2let bluebird = require("bluebird");3let path = require("vendor/path-browser");4let fsWeb = require("vendor/fs-web");5let screenOffsets = require("utils/dom/screenOffsets");6let parentNodes = require("utils/dom/parentNodes");7let {on} = require("utils/dom/domEvents");8let loadScript = require("utils/dom/loadScript");9let loadCss = require("utils/dom/loadCss");10let contextMenu = require("modules/contextMenu");11let createFs = require("modules/fs");12let Common = require("platforms/common/Platform");13let clipboard = require("platform/modules/clipboard");14let jsonStore = require("platform/modules/jsonStore");15let Snippets = require("platform/modules/Snippets");16let lsp = require("platform/modules/lsp");17class Platform extends Common {18 constructor() {19 super();20 21 this.systemInfo = {22 newline: "\n",23 homeDir: "/",24 pathSeparator: "/",25 multiPathSeparator: ":",26 };27 28 this.clipboard = clipboard;29 this.isMainWindow = true;30 this.path = path;31 32 this.useFileUploader = true;33 }34 35 async init(config) {36 config = {37 dev: false,38 resourcePrefix: "",39 localStoragePrefix: "treefrog.",40 fsPrefix: "treefrogFs",41 lspUrl: null,42 test: false,43 ...config,44 };45 46 this.config = config;47 48 this.jsonStore = jsonStore(config.localStoragePrefix);49 50 await Promise.all([51 !config.test && loadCss(config.resourcePrefix + "css/global.css"),52 !config.test && loadCss(config.resourcePrefix + "js/main.css"),53 loadScript(config.resourcePrefix + "vendor/tree-sitter/tree-sitter.js"),54 ]);55 56 this.fs = this.createFs("files");57 this.backupFs = this.createFs("backups");58 59 this.snippets = new Snippets(this.createFs("snippets"));60 61 await this.snippets.init();62 63 if (config.lspUrl) {64 this.lsp = lsp(config.lspUrl);65 }66 }67 68 createFs(key) {69 let fs = fsWeb(this.config.fsPrefix + "-" + key);70 71 return createFs({72 fs,73 path,74 minimatch,75 76 async mkdirp(path) {77 let dirs = path.substr(1).split("/").filter(Boolean);78 79 for (let i = 1; i <= dirs.length; i++) {80 let path = "/" + dirs.slice(0, i).join("/");81 82 if (!await fs.exists(path)) {83 await fs.mkdir(path);84 }85 }86 },87 88 cwd() {89 return "/";90 },91 92 watch(path, handler) {93 return fs.watch(path, handler);94 },95 });96 }97 98 async save(path, code) {99 let node = this.fs(path);100 101 await node.parent.mkdirp();102 await node.write(code);103 }104 105 saveAs() {106 let name = (prompt("Filename:") || "").trim();107 108 if (!name) {109 return null;110 }111 112 return name[0] === "/" ? name : "/" + name;113 }114 115 backup(document) {116 let key = encodeURIComponent(document.url);117 118 this.backupFs(key).write(document.string);119 }120 121 removeBackup(document) {122 let key = encodeURIComponent(document.url);123 124 this.backupFs(key).delete();125 }126 127 async filesFromDropEvent(e) {128 return bluebird.map([...e.dataTransfer.files], async function(file) {129 return {130 path: path.resolve("/", file.name),131 code: await file.text(),132 };133 });134 }135 136 getFilesToOpenOnStartup() {137 return [];138 }139 140 openDialogWindow(app, dialog, dialogOptions, windowOptions) {141 app.openDialogWindow(dialog, dialogOptions, windowOptions);142 }143 144 showMessageBox(app, config) {145 return app.showMessageBox(config);146 }147 148 showContextMenu(e, app, items, noCancel=false) {149 contextMenu(app, items, {150 x: e.clientX,151 y: e.clientY,152 }, noCancel);153 }154 155 showContextMenuForElement(app, element, items, noCancel=false) {156 let {x, y, height} = screenOffsets(element);157 let coords = {x, y: y + height};158 159 contextMenu(app, items, coords, noCancel);160 }161 162 handleIpcMessages(channel, handler) {163 // noop164 }165 166 get isWindows() {167 return false;168 }169 170 setTitle(title) {171 // noop172 }173 174 loadTreeSitterLanguage(name) {175 return TreeSitter.Language.load(this.config.resourcePrefix + "vendor/tree-sitter/langs/tree-sitter-" + name + ".wasm");176 }177 178 closeWindow() {179 // noop180 }181}...
readwrite.js
Source:readwrite.js
1'use strict';2const createFS = require('nhdfs').createFS;3const fs = createFS({service:"namenode", port:9000});4//const fs = createFS({service:"nameservice1"});5//const fs = createFS({service:"nameservice1", configurationPath:'/opt//hadoop/conf/hdfs-site.xml'});6//const fs = createFS({service:"nameservice1", user:"testuser", configurationPath:'/opt/hadoop/conf/hdfs-site.xml'});7//const fs = createFS();8const name = "writertest";9async function write() {10 const out = fs.createWriteStream(name);11 out.on('error', (err) => {12 console.log(err);13 });14 for (let i = 0; i <= 1000; ++i ) {15 var buf = Buffer.from(`{name: 'line ${i}', msg: 'hello world number ${i}}', num: ${i}}\n`, 'utf8');16 out.write(buf);17 }18 out.end(`{name: 'last line 1001', msg: 'later on world number 1001', num: 1001}`);19 return new Promise((resolve, reject) => {20 out.on('finish', () => {21 setTimeout(resolve, 1000);22 })23 });24}25async function read() {26 console.log("starting reading");27 const ins = fs.createReadStream(name);28 ins.on('error', (err) => {29 console.log(err);30 });31 ins.on('data', (data) => {32 console.log(`on data ${data.length}`);33 let s = data.toString('utf8'); 34 console.log(s);35 })36 return new Promise((resolve, reject) => {37 ins.on('end', () => {38 ins.close();39 resolve();40 })41 });42}43write().then( () => {44 read();45}).then ( () => {46 console.log("done");47}).catch( (err) => {48 console.log(err);...
zadanie4.js
Source:zadanie4.js
1//funkcja z listy2function createFs(n) { // tworzy tablicÄ n funkcji3 var fs = []; // i-ta funkcja z tablicy ma zwróciÄ i4 for (var i = 0; i < n; i++) {5 fs[i] =6 function () {7 return i;8 };9 };10 return fs;11}12var myfs = createFs(10);13console.log(myfs[0]()); // zerowa funkcja miaÅa zwróciÄ 014console.log(myfs[2]()); // druga miaÅa zwróciÄ 215console.log(myfs[7]());16//co robi Babel?17function createFs(n) { // tworzy tablicÄ n funkcji18 var fs = []; // i-ta funkcja z tablicy ma zwróciÄ i19 var _loop = function _loop(i){20 fs[i] = function(){21 return i;22 };23 };24 for( var i = 0; i<n; i++){25 _loop(i);26 };27 return fs;28 }29 var myfs = createFs(10);30 console.log( myfs[0]() ); // zerowa funkcja miaÅa zwróciÄ 031 console.log( myfs[2]() ); // druga miaÅa zwróciÄ 232 console.log( myfs[7]() );33//let dziaÅa w danym bloku kodu34//var dziaÅa globalnie35// tak dziaÅa z letem36function createFs(n) { // tworzy tablicÄ n funkcji37 var fs = []; // i-ta funkcja z tablicy ma zwróciÄ i38 for (let i = 0; i < n; i++) {39 fs[i] =40 function () {41 return i;42 };43 };44 return fs;45}46var myfs = createFs(10);47console.log(myfs[0]()); // zerowa funkcja miaÅa zwróciÄ 048console.log(myfs[2]()); // druga miaÅa zwróciÄ 2...
workdir.js
Source:workdir.js
1'use strict';2const createFS = require('nhdfs').createFS;3const fs = createFS({service:"namenode", port:9000});4//const fs = createFS({service:"nameservice1"});5//const fs = createFS({service:"nameservice1", configurationPath:'/opt//hadoop/conf/hdfs-site.xml'});6//const fs = createFS({service:"nameservice1", user:"testuser", configurationPath:'/opt/hadoop/conf/hdfs-site.xml'});7//const fs = createFS();8const tmpWorkDir = 'testWorkDir';9var curDir = "";10fs.getWorkingDirectory()11.then( async (workDir) => {12 console.log(`working dir=${workDir}`);13 curDir = workDir;14 await fs.mkdir(tmpWorkDir);15 var i = await fs.exists(tmpWorkDir);16 console.log(`${tmpWorkDir} exists=${i}`);17 i = await fs.isDirectory(tmpWorkDir);18 console.log(`${tmpWorkDir} is directory=${i}`);19 i = await fs.isFile(tmpWorkDir);20 console.log(`${tmpWorkDir} is file=${i}`);21 let fullPath = `${curDir}/${tmpWorkDir}`; //needs to be full path22 console.log(`working dir to set=${fullPath}`);23 await fs.setWorkingDirectory(fullPath);24 let nwd = await fs.getWorkingDirectory(); 25 console.log(`working dir=${nwd}`);26 await fs.setWorkingDirectory(curDir);27 nwd = await fs.getWorkingDirectory(); 28 console.log(`working dir=${nwd}`);29 await fs.delete(fullPath);30 i = await fs.exists(fullPath);31 console.log(`${fullPath} exists=${i}`);32})33.catch( (err) => {34 console.log(err);...
fsops.js
Source:fsops.js
1'use strict';2const createFS = require('nhdfs').createFS;3//const fs = createFS({service:"namenode", port:9000});4const fs = createFS({service:"localhost", port:9000});5//const fs = createFS({service:"nameservice1"});6//const fs = createFS({service:"nameservice1", configurationPath:'/opt//hadoop/conf/hdfs-site.xml'});7//const fs = createFS({service:"nameservice1", user:"testuser", configurationPath:'/opt/hadoop/conf/hdfs-site.xml'});8//const fs = createFS();9fs.list(".").then((list) => {10 list.forEach((element) => {11 console.log(element);12 });13})14.catch( (err) => {15 console.log(err);16})17.then ( async () => {18 await fs.mkdir('dir1');19 let r = await fs.isDirectory('dir1');20 console.log(`dir1=${r}`);21})22.then ( async () => {23 await fs.mkdir('file1');24 let r = await fs.isFile('file1');25 console.log(`file1=${r}`);26})27.then ( async () => {28 let r = await fs.exists('file1');29 console.log(`file1=${r}`);30})31.then ( async () => {32 let r = await fs.exists('filexxx');33 console.log(`filexxx=${r}`);34})35.then ( async () => {36 let dbs = await fs.getDefaultBlockSize();37 console.log(`Default Block Size: ${dbs}`);38 let capacity = await fs.getCapacity();39 console.log(`capacity: ${capacity}`);40 let used = await fs.getUsed();41 console.log(`used: ${used}`);42})43.catch( (err) => {44 console.log(err);...
zad4.js
Source:zad4.js
1function createFs(n) {2 var fs = [];3 var _loop = function _loop(i) {4 fs[i] = function () {5 return i; // nowy kontekst6 };7 };8 for (var i = 0; i < n; i++) {9 _loop(i);10 };11 return fs;12}13var myfs = createFs(10);14console.log(myfs[0]()); // zerowa funkcja miaÅa zwróciÄ 015console.log(myfs[2]()); // druga miaÅa zwróciÄ 216console.log(myfs[7]());17/*18OryginaÅ:19function createFs(n) { // tworzy tablicÄ n funkcji20 var fs = []; // i-ta funkcja z tablicy ma zwróciÄ i21 for (var i = 0; i < n; i++) { // tu należy doistawiÄ let22 fs[i] =23 function () {24 return i;25 };26 };27 return fs;28}29var30Zmienne zadeklarowane za pomocÄ
var dziaÅajÄ
w kontekÅcie funkcji.31let32Deklaracja zmiennej za pomocÄ
let sprawia, że zmienna dziaÅa w kontekÅcie blokowym, np. wewnÄ
trz pÄtli.33*/34/* Z babel:35function createFs(n) {36 // tworzy tablicÄ n funkcji37 var fs = []; // i-ta funkcja z tablicy ma zwróciÄ i38 var _loop = function _loop(i) {39 // tu należy doistawiÄ let40 fs[i] = function () {41 return i;42 };43 };44 for (var i = 0; i < n; i++) {45 _loop(i);46 };47 return fs;48}...
Using AI Code Generation
1describe('Create file system', () => {2 it('Create file system', () => {3 cy.createfs('test', 'test', 'test')4 })5})6describe('Delete file system', () => {7 it('Delete file system', () => {8 cy.deletefs('test')9 })10})11describe('List file system', () => {12 it('List file system', () => {13 cy.listfs()14 })15})
Using AI Code Generation
1var fs = require('fs');2var path = require('path');3var dir = './cypress/fixtures/';4if (!fs.existsSync(dir)){5 fs.mkdirSync(dir);6}7var dir2 = './cypress/fixtures/abc/';8if (!fs.existsSync(dir2)){9 fs.mkdirSync(dir2);10}11fs.writeFile('./cypress/fixtures/abc/abc.json', '{"abc": "123"}', function(err) {12 if(err) {13 return console.log(err);14 }15 console.log("The file was saved!");16}); 17describe('My First Test', function() {18 it('Does not do much!', function() {19 cy.contains('type').click()20 cy.url().should('include', '/commands/actions')21 cy.get('.action-email')22 .type('
Using AI Code Generation
1import { createfs } from 'cypress-fs-preprocessor'2createfs({3})4{5 "fsPreprocessor": {6 "createfs": {7 }8 }9}10const { createfs } = require('cypress-fs-preprocessor')11module.exports = (on, config) => {12 on('file:preprocessor', createfs({13 }))14}
Using AI Code Generation
1describe('test createfs', function() {2 it('createfs', function() {3 cy.createfs('testfs')4 })5})6Cypress.Commands.add('createfs', (name, options = {}) => {7 cy.log('createfs')8 cy.task('createfs', { name, options })9})10const createfs = require('createfs')11module.exports = (on, config) => {12 on('task', {13 createfs: ({ name, options }) => {14 return createfs(name, options)15 }16 })17}18"devDependencies": {19}20{21}22const createfs = require('createfs')23module.exports = (on, config) => {24 on('task', {25 createfs: ({ name, options }) => {26 return createfs(name, options)27 }28 })29}30{31}32Cypress.Commands.add('createfs', (name, options = {}) => {33 cy.log('createfs')34 cy.task('createfs', { name, options })35})36const createfs = require('createfs')37Cypress.Commands.add('createfs', (name, options = {}) => {38 cy.log('createfs')39 cy.task('createfs', { name, options })40})41{42 {
Using AI Code Generation
1describe('Test Suite', function() {2 it('Test Case', function() {3 cy.createfs('test.txt', 'Hello World!')4 })5})6describe('Test Suite', function() {7 it('Test Case', function() {8 cy.createfs('cypress/fixtures/test.txt', 'Hello World!')9 })10})11Cypress createfs() method to
Using AI Code Generation
1var cypress = require('cypress');2cypress.createfs({3}, function(err) {4 if (err) {5 console.log(err);6 } else {7 console.log('Done!');8 }9});10var cypress = require('cypress');11cypress.extract({12}, function(err) {13 if (err) {14 console.log(err);15 } else {16 console.log('Done!');17 }18});19var cypress = require('cypress');20cypress.compress({21}, function(err) {22 if (err) {23 console.log(err);24 } else {25 console.log('Done!');26 }27});28var cypress = require('cypress');29cypress.createfs({30}, function(err) {31 if (err) {32 console.log(err);33 } else {34 console.log('Done!');35 }36});37var cypress = require('cypress');38cypress.extract({39}, function(err) {40 if (err) {41 console.log(err);42 } else {43 console.log('Done!');44 }45});46var cypress = require('cypress');47cypress.compress({48}, function(err) {49 if (err) {50 console.log(err);51 } else {52 console.log('
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!