How to use hashFile method in Cypress

Best JavaScript code snippet using cypress

index.js

Source:index.js Github

copy

Full Screen

1var fs = require('fs-extra');2var ProgressBar = require('progress');3var s3 = require('s3');4var sass = require('node-sass');5var sha1 = require('crypto-js/sha1');6var cdn = function(options) {7 if(!options || !options.accessKeyId || !options.secretAccessKey || !options.bucket || !options.cdnUrl) {8 throw 'S3 accessKeyId, secretAccessKey, bucket, and cdnUrl must be set in options'9 }10 this.accessKeyId = options.accessKeyId;11 this.secretAccessKey = options.secretAccessKey;12 this.bucket = options.bucket;13 this.ignore = options.ignore || [];14 this.hashFile = options.hashFile || (__dirname + '/cdn-hash.json');15 this.cdnUrl = options.cdnUrl;16 this.envList = options.envList || ['production'];17 this.client = s3.createClient({18 s3Options: {19 accessKeyId: this.accessKeyId,20 secretAccessKey: this.secretAccessKey21 }22 });23}24cdn.prototype.upload = function(assetDir, callback = () => {}) {25 if(!assetDir) {26 throw 'upload() requires param assetDir';27 }28 //Get existing hash or set a new one if it doesn't exist29 var hash = this.getHash() || this.setHash();30 //TODO: tmpDir never gets removed if anything fails before the cleanup phase31 var tmpDir = `/tmp/${hash}`;32 console.log(`Copying ${assetDir} to ${tmpDir}`);33 fs.copy(assetDir, tmpDir, (err) => {34 if(err) {35 console.log('ERROR: ', err);36 return false;37 }38 var promises = [];39 this.ignore.forEach((ignoredFile) => {40 var ignoredPath = `${tmpDir}/${ignoredFile}`; 41 console.log(`Removing ignored file: ${ignoredPath}`);42 promises.push(new Promise((resolve, reject) => {43 //TODO: This should stat the file and note whether it's deleting or skipping44 fs.remove(ignoredPath, (err) => {45 if(err) {46 reject(err);47 } else {48 resolve(ignoredPath);49 }50 });51 }));52 })53 Promise.all(promises).then((values) => {54 console.log(`Copying ${tmpDir} to ${this.bucket}`);55 var bar;56 var uploader = this.client.uploadDir({57 localDir: tmpDir,58 s3Params: {59 Bucket: this.bucket,60 Prefix: `${hash}`61 }62 }).on('error', (err) => {63 console.log('ERROR: ', err);64 }).on('progress', () => {65 if(uploader.progressAmount > 0) {66 if(!bar) {67 //TODO: uploader.progressTotal sometimes changes the units it reports68 bar = new ProgressBar('Uploading ' + Math.round(uploader.progressTotal / 1024) + 'MB to S3 (' + this.bucket + ') - [:bar] :percent, ETA :etas', {69 complete: '=',70 incomplete: ' ',71 total: 5072 });73 }74 bar.update(uploader.progressAmount / uploader.progressTotal);75 }76 }).on('end', () => {77 console.log('Upload finished!');78 console.log(`Removing temp dir: ${tmpDir}`);79 fs.remove(tmpDir, (err) => {80 if(err) {81 console.log('ERROR: ', err);82 } else {83 fs.writeJson(this.hashFile, { hash: hash }, {});84 }85 callback();86 });87 });88 }).catch((err) => {89 console.log('ERROR: ', err);90 });91 });92}93cdn.prototype.clean = function(callback = () => {}) {94 var hash = require(this.hashFile).hash;95 var prefixes = [];96 this.client.listObjects({97 s3Params: {98 Bucket: this.bucket,99 Delimiter: '/'100 }101 }).on('data', (data) => {102 prefixes = prefixes.concat(data.CommonPrefixes.map(p => p.Prefix));103 }).on('end', () => {104 var deletedPrefixes = prefixes.filter(p => p !== hash + '/');105 var promises = [];106 console.log(`Found ${deletedPrefixes.length} old directories`);107 deletedPrefixes.forEach((prefix) => {108 console.log('Deleting: ' + prefix);109 promises.push(new Promise((resolve, reject) => {110 var deleter = this.client.deleteDir({111 Bucket: this.bucket,112 Prefix: prefix113 }).on('error', (err) => {114 reject(err);115 }).on('end', () => {116 resolve(prefix);117 })118 }));119 });120 Promise.all(promises).then((values) => {121 callback();122 }).catch((err) => {123 console.log('ERROR: ', err);124 });125 });126}127cdn.prototype.getHash = function() {128 var result = false;129 try {130 var stat = fs.statSync(this.hashFile);131 if(stat.isFile()) {132 let hashFile = require(this.hashFile);133 if(hashFile.hash) {134 result = hashFile.hash;135 }136 }137 } catch(noHashFile) {}138 return result;139}140cdn.prototype.generateHash = function() {141 return sha1('SterlingMalloryArcher' + Math.random()).toString().substring(0, 7);142}143cdn.prototype.setHash = function(hash = this.generateHash()) {144 fs.writeJsonSync(this.hashFile, { hash: hash });145 return hash;146}147cdn.prototype.getUrl = function(path) {148 var hash = this.getHash();149 var result;150 if(hash && this.envList.indexOf(process.env.NODE_ENV) > -1) {151 result = `${this.cdnUrl}/${hash}${path}`;152 } else {153 result = path;154 }155 return result;156}157cdn.prototype.helpers = {158 sass: function(path) {159 return sass.types.String(`url('${this.getUrl(path.getValue())}')`);160 }161}...

Full Screen

Full Screen

StudIPInterface.js

Source:StudIPInterface.js Github

copy

Full Screen

1const fetch = require('node-fetch');2const fs = require('fs');3class StudIPInterface {4 constructor(apiURL, userData = {name, password}) {5 this.url = apiURL;6 this.userData = userData;7 this.foundFiles = null;8 this.hashFile = 'hashFile.json';9 this.downloadPrefix = 'files/';10 if (!fs.existsSync(this.downloadPrefix)) {11 fs.mkdirSync(this.downloadPrefix);12 } 13 }14 async downloadFoundFiles() {15 if (!this.foundFiles) return;16 const newFiles = this.testForNewFiles(this.foundFiles);17 console.info('Downloading ' + newFiles.length + ' new files.')18 const paths = [];19 20 for (const file of newFiles) {21 if (!fs.existsSync(this.downloadPrefix + file.folder_id)) {22 fs.mkdirSync(this.downloadPrefix + file.folder_id);23 }24 25 const data = await this.apiRequest('/file/' + file.id + '/download', 'file');26 let buffer = Buffer.from(data);27 const path = this.downloadPrefix + file.folder_id + '/' + file.name28 fs.writeFile(path, buffer, "binary", () => {});29 paths.push(path)30 }31 this.foundFiles = null;32 return paths;33 }34 testForNewFiles(fileList) { 35 try {36 const info = fs.statSync(this.hashFile)37 console.log('hashfile exists')38 } catch {39 console.log('hashfile does not exists')40 return [];41 }42 const hashFile = JSON.parse(fs.readFileSync(this.hashFile));43 fileList = fileList.filter((file) => !hashFile.hashes.find((val) => val == getHash(file)));44 fileList.map((file) => {hashFile.hashes.push(getHash(file))});45 hashFile.lastModified = Date.now();46 fs.writeFileSync(this.hashFile, JSON.stringify(hashFile, false, 2))47 return fileList;48 function getHash(file) {49 return file.file_id + file.chdate + file.name50 }51 }52 async findFilesInCourse(fileName, courseId) {53 54 const res = await this.apiRequest('course/' + courseId + '/top_folder');55 let allFiles = await this.getAllFilesInFolder(res.id, true);56 let re = new RegExp(fileName, '');57 this.foundFiles = allFiles.filter((file) => {58 return re.test(file.name);59 })60 return allFiles;61 }62 async getAllFilesInFolder(folderId, recursive = false) {63 const files = await this.apiRequest('folder/' + folderId + '/files');64 65 const allFiles = [];66 if(!files) return allFiles;67 for (const file in files.collection)68 allFiles.push(files.collection[file]);69 console.info('Found ' + allFiles.length + ' file/s!')70 if (recursive) {71 const res = await this.getAllFoldersInFolder(folderId);72 for (const folder in res.collection) {73 const recursiveFiles = await this.getAllFilesInFolder(res.collection[folder].id, true);74 allFiles.push(...recursiveFiles); 75 }76 }77 78 return allFiles; 79 }80 async getAllFoldersInFolder(folderId) {81 const res = await this.apiRequest('folder/' + folderId + '/subfolders');82 return res;83 }84 async apiRequest(path, type) {85 let response = await fetch(this.url + path, {86 method:'GET',87 headers: {88 'Authorization': 'Basic ' + Buffer.from(this.userData.name + ":" + this.userData.password).toString('base64')89 },90 })91 if (!response.ok)92 return ; 93 switch(type) {94 case 'text':95 response = await response.text(); 96 break; 97 case 'file':98 response = await response.arrayBuffer();99 break;100 default:101 response = await response.json(); 102 }103 104 return response;105 }106}...

Full Screen

Full Screen

cache-busting.js

Source:cache-busting.js Github

copy

Full Screen

...7 *8 * @param string fileName9 * @returns string10 */11function hashFile(file) {12 // Get file name13 var fileName = file.replace(/\.[^/.]+$/, "");14 // Get file extension15 var re = /(?:\.([^.]+))?$/;16 var fileExtension = re.exec(file)[1];17 var filePath = path.join(buildDir, file);18 var fileHash = revHash(fs.readFileSync(filePath));19 var fileNewName = `${fileName}.${fileHash}.${fileExtension}`;20 var fileNewPath = path.join(buildDir, fileNewName);21 var fileNewRelativePath = path.join('build', fileNewName);22 //Rename file23 console.log("cache-busting.js:hashFile:Renaming " + filePath + " to " + fileNewPath);24 fs.renameSync(filePath, fileNewPath);25 var serviceWorkerData = fs.readFileSync(serviceWorkerPath, 'utf8'); 26 var serviceWorkerModifiedData = serviceWorkerData.replace(file, fileNewName);27 fs.writeFileSync(serviceWorkerPath, serviceWorkerModifiedData, 'utf8');28 return fileNewRelativePath;29}30var rootDir = path.resolve(__dirname, '../');31var appDir = path.resolve(__dirname, './');32var source = path.resolve(appDir, 'www');33var destination = path.resolve(rootDir, 'release');34var buildDir = path.join(source, 'build');35var indexPath = path.join(source, 'index.html');36var serviceWorkerPath = path.join(source, 'service-worker.js');37$ = cheerio.load(fs.readFileSync(indexPath, 'utf-8'));38$('head link[href="build/main.css"]').attr('href', hashFile('main.css'));39$('body script[src="build/main.js"]').attr('src', hashFile('main.js'));40$('body script[src="build/polyfills.js"]').attr('src', hashFile('polyfills.js'));41$('body script[src="build/vendor.js"]').attr('src', hashFile('vendor.js'));42fs.writeFileSync(indexPath, $.html());43if(!fs.existsSync(destination)){44 fs.ensureDirSync(rootDir+'/release');45}46var adminBuildExists = fs.existsSync(destination+'/admin');47if(adminBuildExists){48 fs.ensureDirSync(source+'/admin');49 fs.copySync(destination+'/admin', source+'/admin');50}51fs.emptyDirSync(destination);52fs.copySync(source,destination);53if(adminBuildExists){54 fs.moveSync(source+'/admin', destination+'/admin', { overwrite: true });55}

Full Screen

Full Screen

hash.js

Source:hash.js Github

copy

Full Screen

...27hash.md5 = function(data, cb) {28 hashData(forge.md.md5.create(), data, cb);29};30hash.file.md5 = function(file, cb) {31 hashFile(forge.md.md5.create(), file, cb);32};33hash.sha1 = function(data, cb) {34 hashData(forge.md.sha1.create(), data, cb);35};36hash.file.sha1 = function(file, cb) {37 hashFile(forge.md.sha1.create(), file, cb);38};39hash.sha256 = function(data, cb) {40 hashData(forge.md.sha256.create(), data, cb);41};42hash.file.sha256 = function(file, cb) {43 hashFile(forge.md.sha256.create(), file, cb);44};45hash.sha384 = function(data, cb) {46 hashData(forge.md.sha384.create(), data, cb);47};48hash.file.sha384 = function(file, cb) {49 hashFile(forge.md.sha384.create(), file, cb);50};51hash.sha512 = function(data, cb) {52 hashData(forge.md.sha512.create(), data, cb);53};54hash.file.sha512 = function(file, cb) {55 hashFile(forge.md.sha512.create(), file, cb);56};57hash.hmac = function(type, key, data, cb) {58 var hmac = forge.hmac.create();59 hmac.start(type, key);60 hashData(hmac, data, cb);61};62hash.file.hmac = function(type, key, file, cb) {63 var hmac = forge.hmac.create();64 hmac.start(type, key);65 hashFile(hmac, file, cb);66};...

Full Screen

Full Screen

TimeStampController.js

Source:TimeStampController.js Github

copy

Full Screen

1/**2 * TimeStampController3 *4 * @description :: Server-side actions for handling incoming requests.5 * @help :: See https://sailsjs.com/docs/concepts/actions6 */7const axios = require('axios');8module.exports = {9 10 stamp: async function (req, res) {11 if(!req.body.hashFile) return res.badRequest("Se esperaba el parametro hashFile");12 const hashFile = req.body.hashFile;13 await axios.post(sails.config.custom.tsaUrl + 'stamp', {14 file_hash: hashFile15 })16 .then((response) => { 17 if(response.status == 200 && response.data.tx_hash !== undefined){ 18 return res.status(200).json({19 status: 'success',20 infoStamp : response.data21 });22 } else {23 return res.badRequest(res)24 }25 })26 .catch((error) => { 27 return res.badRequest(error)28 });29 },30 verify: async function (req, res) {31 if(!req.body.comprobanteOTS) return res.badRequest("Se esperaba el parametro comprobanteOTS");32 if(!req.body.hashFile) return res.badRequest("Se esperaba el parametro hashFile");33 34 const comprobanteOTS = req.body.comprobanteOTS; 35 const hashFile = req.body.hashFile;36 const urlVerify = sails.config.custom.tsaUrl + 'verify/'+comprobanteOTS+'/'+hashFile;37 38 await axios.get(urlVerify)39 .then( response => { 40 41 return res.status(200).json({42 status: 'success',43 verifyInfo: response.data44 });45 })46 .catch(function (error) { 47 return res.badRequest(error.toString());48 }); 49 }...

Full Screen

Full Screen

hashfile_test.js

Source:hashfile_test.js Github

copy

Full Screen

1var fixture = require('../support/fixture')2describe('hashfile', function () {3 var hashFile = require('../../lib/hashfile').hashFile4 var hashFiles = require('../../lib/hashfile').hashFiles5 describe('hashFile()', function () {6 it('works', function () {7 return hashFile(fixture('files/file1.txt'))8 .then(function (res) {9 expect(res).toEqual('ce57c01c8bda67ce22ded81b28657213a99e69b3')10 })11 })12 it('works again', function () {13 return hashFile(fixture('files/file2.txt'))14 .then(function (res) {15 expect(res).toEqual('d06a59c73d2363d6c0692de0e3d7629a9480f901')16 })17 })18 it('can handle not founds', function () {19 return hashFile('ayylmao')20 .then(function (res) {21 expect(res).toEqual(null)22 })23 })24 it('can handle directories', function () {25 return hashFile(fixture('files/'))26 .then(function (res) {27 expect(res).toEqual(null)28 })29 })30 })31 describe('hashFiles()', function () {32 beforeEach(function () {33 var files = [34 'file1.txt',35 'file2.txt'36 ]37 return hashFiles(fixture('files'), files)38 .then(function (res) {39 this.result = res...

Full Screen

Full Screen

hashFile.test.js

Source:hashFile.test.js Github

copy

Full Screen

...5const HASH_MD5 = "3858f62230ac3c915f300c664312c63f";6const HASH_SHA1 = "8843d7f92416211de9ebb963ff4ce28125932878";7describe('hashFile', () => {8 it('should throw an error when first argument is not a file or file path', () => {9 expect(() => { hashFile("e") }).toThrowError("Invalid frist argument, provide a file or a full local path.")10 });11 it('should return with empty values when no algorithm was defined', () => {12 return expect(hashFile(TEST_FILE)).resolves.toStrictEqual({ sha256: undefined, sha1: undefined, md5: undefined, sha512: undefined });13 });14 it('should return with a hash when second parameter is a valid algo', () => {15 return expect(hashFile(TEST_FILE, "sha256")).resolves.toStrictEqual({ sha256: HASH_SHA256, sha1: undefined, md5: undefined, sha512: undefined });16 });17 it('should return with chekcums when second parameter is a valid array of algorithms', () => {18 return expect(hashFile(TEST_FILE, ["sha256", "md5", "sha1", "sha512"], null)).resolves.toStrictEqual({ sha256: HASH_SHA256, sha1: HASH_SHA1, md5: HASH_MD5, sha512: HASH_SHA512 });19 });20 it('onProgress callback should return with progress', done => {21 function callback(percent) {22 expect(percent).toEqual(0);23 done()24 }25 hashFile(TEST_FILE, "sha256", callback)26 });...

Full Screen

Full Screen

electron-ffmpeg-lib.spec.js

Source:electron-ffmpeg-lib.spec.js Github

copy

Full Screen

...23 it('hashFile', async () => {24 const [25 hashA, hashB, hashC26 ] = await Promise.all([27 hashFile(resource('fileA.txt')),28 hashFile(resource('fileB.txt')),29 hashFile(resource('fileC.txt')),30 ]);31 expect(hashA.equals(hashC)).true;32 expect(hashA.equals(hashB)).false;33 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const crypto = require('crypto');3const hash = crypto.createHash('sha256');4const input = fs.createReadStream('test.txt');5input.on('readable', () => {6 const data = input.read();7 if (data)8 hash.update(data);9 else {10 console.log(hash.digest('hex'));11 }12});13describe('Hash File', () => {14 it('should hash file', () => {15 const hash = Cypress.hashFile('test.txt')16 expect(hash).to.equal('9e107d9d372bb6826bd81d3542a419d6')17 })18})

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var hash = require('object-hash');3var cypress = require('cypress');4var hashFile = require('object-hash')5var files = fs.readdirSync('cypress/integration');6var hashFile = require('

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful