Best JavaScript code snippet using cypress
install_spec.js
Source:install_spec.js
1require('../../spec_helper')2const os = require('os')3const path = require('path')4const chalk = require('chalk')5const Promise = require('bluebird')6const mockfs = require('mock-fs')7const snapshot = require('snap-shot-it')8const stdout = require('../../support/stdout')9const fs = require(`${lib}/fs`)10const download = require(`${lib}/tasks/download`)11const install = require(`${lib}/tasks/install`)12const state = require(`${lib}/tasks/state`)13const unzip = require(`${lib}/tasks/unzip`)14const logger = require(`${lib}/logger`)15const util = require(`${lib}/util`)16const normalize = require('../../support/normalize')17const packageVersion = '1.2.3'18const downloadDestination = path.join(os.tmpdir(), 'cypress.zip')19const installDir = '/cache/Cypress/1.2.3'20describe('/lib/tasks/install', function () {21 require('mocha-banner').register()22 beforeEach(function () {23 this.stdout = stdout.capture()24 // allow simpler log message comparison without25 // chalk's terminal control strings26 chalk.enabled = false27 })28 afterEach(() => {29 stdout.restore()30 chalk.enabled = true31 })32 context('.start', function () {33 beforeEach(function () {34 logger.reset()35 // sinon.stub(os, 'tmpdir').returns('/tmp')36 sinon.stub(util, 'isCi').returns(false)37 sinon.stub(util, 'isPostInstall').returns(false)38 sinon.stub(util, 'pkgVersion').returns(packageVersion)39 sinon.stub(download, 'start').resolves(packageVersion)40 sinon.stub(unzip, 'start').resolves()41 sinon.stub(Promise, 'delay').resolves()42 sinon.stub(fs, 'removeAsync').resolves()43 sinon.stub(state, 'getVersionDir').returns('/cache/Cypress/1.2.3')44 sinon.stub(state, 'getBinaryDir').returns('/cache/Cypress/1.2.3/Cypress.app')45 sinon.stub(state, 'getBinaryPkgVersionAsync').resolves()46 sinon.stub(fs, 'ensureDirAsync').resolves(undefined)47 os.platform.returns('darwin')48 })49 describe('skips install', function () {50 it('when environment variable is set', function () {51 process.env.CYPRESS_INSTALL_BINARY = '0'52 return install.start()53 .then(() => {54 expect(download.start).not.to.be.called55 snapshot(56 'skip installation',57 normalize(this.stdout.toString())58 )59 })60 })61 })62 describe('override version', function () {63 it('warns when specifying cypress version in env', function () {64 const version = '0.12.1'65 process.env.CYPRESS_INSTALL_BINARY = version66 return install.start()67 .then(() => {68 expect(download.start).to.be.calledWithMatch({69 version,70 })71 expect(unzip.start).to.be.calledWithMatch({72 zipFilePath: downloadDestination,73 })74 snapshot(75 'specify version in env vars',76 normalize(this.stdout.toString())77 )78 })79 })80 it('can install local binary zip file without download', function () {81 const version = '/tmp/local/file.zip'82 process.env.CYPRESS_INSTALL_BINARY = version83 sinon.stub(fs, 'pathExistsAsync').withArgs(version).resolves(true)84 const installDir = state.getVersionDir()85 return install.start()86 .then(() => {87 expect(unzip.start).to.be.calledWithMatch({88 zipFilePath: version,89 installDir,90 })91 })92 })93 it('can install local binary zip file from relative path', function () {94 const version = './cypress-resources/file.zip'95 mockfs({96 [version]: 'asdf',97 })98 process.env.CYPRESS_INSTALL_BINARY = version99 const installDir = state.getVersionDir()100 return install.start()101 .then(() => {102 expect(download.start).not.to.be.called103 expect(unzip.start).to.be.calledWithMatch({104 zipFilePath: path.resolve(version),105 installDir,106 })107 })108 })109 describe('when version is already installed', function () {110 beforeEach(function () {111 state.getBinaryPkgVersionAsync.resolves(packageVersion)112 })113 it('doesn\'t attempt to download', function () {114 return install.start()115 .then(() => {116 expect(download.start).not.to.be.called117 expect(state.getBinaryPkgVersionAsync).to.be.calledWith('/cache/Cypress/1.2.3/Cypress.app')118 })119 })120 it('logs \'skipping install\' when explicit cypress install', function () {121 return install.start()122 .then(() => {123 return snapshot(124 'version already installed - cypress install',125 normalize(this.stdout.toString())126 )127 })128 })129 it('logs when already installed when run from postInstall', function () {130 util.isPostInstall.returns(true)131 return install.start()132 .then(() => {133 snapshot(134 'version already installed - postInstall',135 normalize(this.stdout.toString())136 )137 })138 })139 })140 describe('when getting installed version fails', function () {141 beforeEach(function () {142 state.getBinaryPkgVersionAsync.resolves(null)143 return install.start()144 })145 it('logs message and starts download', function () {146 expect(download.start).to.be.calledWithMatch({147 version: packageVersion,148 })149 expect(unzip.start).to.be.calledWithMatch({150 installDir,151 })152 snapshot(153 'continues installing on failure',154 normalize(this.stdout.toString())155 )156 })157 })158 describe('when there is no install version', function () {159 beforeEach(function () {160 state.getBinaryPkgVersionAsync.resolves(null)161 return install.start()162 })163 it('logs message and starts download', function () {164 expect(download.start).to.be.calledWithMatch({165 version: packageVersion,166 })167 expect(unzip.start).to.be.calledWithMatch({168 installDir,169 })170 // cleans up the zip file171 expect(fs.removeAsync).to.be.calledWith(172 downloadDestination173 )174 snapshot(175 'installs without existing installation',176 normalize(this.stdout.toString())177 )178 })179 })180 describe('when getting installed version does not match needed version', function () {181 beforeEach(function () {182 state.getBinaryPkgVersionAsync.resolves('x.x.x')183 return install.start()184 })185 it('logs message and starts download', function () {186 expect(download.start).to.be.calledWithMatch({187 version: packageVersion,188 })189 expect(unzip.start).to.be.calledWithMatch({190 installDir,191 })192 snapshot(193 'installed version does not match needed version',194 normalize(this.stdout.toString())195 )196 })197 })198 describe('with force: true', function () {199 beforeEach(function () {200 state.getBinaryPkgVersionAsync.resolves(packageVersion)201 return install.start({ force: true })202 })203 it('logs message and starts download', function () {204 expect(download.start).to.be.calledWithMatch({205 version: packageVersion,206 })207 expect(unzip.start).to.be.calledWithMatch({208 installDir,209 })210 snapshot(211 'forcing true always installs',212 normalize(this.stdout.toString())213 )214 })215 })216 describe('as a global install', function () {217 beforeEach(function () {218 sinon.stub(util, 'isInstalledGlobally').returns(true)219 state.getBinaryPkgVersionAsync.resolves('x.x.x')220 return install.start()221 })222 it('logs global warning and download', function () {223 expect(download.start).to.be.calledWithMatch({224 version: packageVersion,225 })226 expect(unzip.start).to.be.calledWithMatch({227 installDir,228 })229 snapshot(230 'warning installing as global',231 normalize(this.stdout.toString())232 )233 })234 })235 describe('when running in CI', function () {236 beforeEach(function () {237 util.isCi.returns(true)238 state.getBinaryPkgVersionAsync.resolves('x.x.x')239 return install.start()240 })241 it('uses verbose renderer', function () {242 snapshot(243 'installing in ci',244 normalize(this.stdout.toString())245 )246 })247 })248 describe('failed write access to cache directory', function () {249 it('logs error on failure', function () {250 os.platform.returns('darwin')251 sinon.stub(state, 'getCacheDir').returns('/invalid/cache/dir')252 const err = new Error('EACCES: permission denied, mkdir \'/invalid\'')253 err.code = 'EACCES'254 fs.ensureDirAsync.rejects(err)255 return install.start()256 .then(() => {257 throw new Error('should have caught error')258 })259 .catch((err) => {260 logger.error(err)261 snapshot(262 'invalid cache directory',263 normalize(this.stdout.toString())264 )265 })266 })267 })268 describe('CYPRESS_INSTALL_BINARY is URL or Zip', function () {269 it('uses cache when correct version installed given URL', function () {270 state.getBinaryPkgVersionAsync.resolves('1.2.3')271 util.pkgVersion.returns('1.2.3')272 process.env.CYPRESS_INSTALL_BINARY = 'www.cypress.io/cannot-download/2.4.5'273 return install.start()274 .then(() => {275 expect(download.start).to.not.be.called276 })277 })278 it('uses cache when mismatch version given URL ', function () {279 state.getBinaryPkgVersionAsync.resolves('1.2.3')280 util.pkgVersion.returns('4.0.0')281 process.env.CYPRESS_INSTALL_BINARY = 'www.cypress.io/cannot-download/2.4.5'282 return install.start()283 .then(() => {284 expect(download.start).to.not.be.called285 })286 })287 it('uses cache when correct version installed given Zip', function () {288 sinon.stub(fs, 'pathExistsAsync').withArgs('/path/to/zip.zip').resolves(true)289 state.getBinaryPkgVersionAsync.resolves('1.2.3')290 util.pkgVersion.returns('1.2.3')291 process.env.CYPRESS_INSTALL_BINARY = '/path/to/zip.zip'292 return install.start()293 .then(() => {294 expect(unzip.start).to.not.be.called295 })296 })297 it('uses cache when mismatch version given Zip ', function () {298 sinon.stub(fs, 'pathExistsAsync').withArgs('/path/to/zip.zip').resolves(true)299 state.getBinaryPkgVersionAsync.resolves('1.2.3')300 util.pkgVersion.returns('4.0.0')301 process.env.CYPRESS_INSTALL_BINARY = '/path/to/zip.zip'302 return install.start()303 .then(() => {304 expect(unzip.start).to.not.be.called305 })306 })307 })308 describe('CYPRESS_BINARY_VERSION', function () {309 it('throws when env var CYPRESS_BINARY_VERSION', function () {310 process.env.CYPRESS_BINARY_VERSION = '/asf/asf'311 return install.start()312 .then(() => {313 throw new Error('should have thrown')314 })315 .catch((err) => {316 logger.error(err)317 snapshot(318 'error for removed CYPRESS_BINARY_VERSION',319 normalize(this.stdout.toString())320 )321 })322 })323 })324 })325 it('is silent when log level is silent', function () {326 process.env.npm_config_loglevel = 'silent'327 return install.start()328 .then(() => {329 return snapshot(330 'silent install',331 normalize(`[no output]${this.stdout.toString()}`)332 )333 })334 })335 })...
install.js
Source:install.js
...254 title: util.titleize('Unzipping Cypress'),255 task: (ctx, task) => {256 // as our unzip progresses indicate the status257 progress.onProgress = progessify(task, 'Unzipping Cypress')258 return unzip.start({ zipFilePath, installDir, progress })259 .then(() => {260 util.setTaskTitle(261 task,262 util.titleize(chalk.green('Unzipped Cypress')),263 rendererOptions.renderer264 )265 })266 },267})268const progessify = (task, title) => {269 // return higher order function270 return (percentComplete, remaining) => {271 percentComplete = chalk.white(` ${percentComplete}%`)272 // pluralize seconds remaining...
FileTools.js
Source:FileTools.js
1import {2 NativeModules, PermissionsAndroid3} from 'react-native';4import {unzip, zip,} from 'react-native-zip-archive'5import RNFS from "react-native-fs";6import Toast from "../JXHelper/JXToast";7import RNFetchBlob from 'react-native-fetch-blob';8import * as RNShot from "react-native-view-shot";9import Base64 from "../JXHelper/Base64";10import CameraRoll from "@react-native-community/cameraroll";11export default class FileTools {12 static downloadFile(formUrl, downloadDest, param, onSucFuc, onProgress) {13 formUrl = formUrl + "?rodom=" + Math.random();14 TW_Log("FileTools---downloadFile==" + formUrl);15 const options = {16 fromUrl: formUrl,17 toFile: downloadDest,18 background: true,19 begin: (res) => {20 // this.log+="==>downloadFile--begin="+res;21 //{statusCode: 404, headers: {â¦}, jobId: 1, contentLength: 15322 TW_Log("FileTools---downloadFile=background--=", res);23 if (res.statusCode != 404) {24 //TW_Store.commonBoxStore.isShow=true;25 } else {26 Toast.showShortCenter("éè¦ä¸è½½ç游ææ件ä¸åå¨");27 // TW_Store.commonBoxStore.isShow=false28 }29 // TW_Log("FileTools---progress==param=="+JSON.stringify(param))30 },31 progress: (res) => {32 // this.log+="==>progress-="+res;33 //let pro = res.bytesWritten / res.contentLength;34 // TW_Store.commonBoxStore.curPecent=res.bytesWritten;35 // TW_Store.commonBoxStore.totalPecent=res.contentLength;36 // TW_Log("FileTools---progress==new==",res);37 if (onProgress) {38 if (res.contentLength > 0) {39 onProgress({percent: (res.bytesWritten / res.contentLength).toFixed(2), param});40 } else {41 let tempContent = param.name && param.name.indexOf("app_") > -1 ? 40000000 : 18000000; //å¦æ读åä¸å°æ»å¤§å° å 为cdnçå ç´ é»è®¤ä½¿ç¨18m å°0.99 çå¾
ï¼42 //let tempContent=40000000;43 let tempPercent = (res.bytesWritten / tempContent).toFixed(2);44 tempPercent = tempPercent >= 0.99 ? 0.99 : tempPercent;45 // TW_Log("FileTools---progress= FileTools.tempPercent---=", tempPercent);46 onProgress({percent: tempPercent, param});47 }48 }49 }50 };51 try {52 const ret = RNFS.downloadFile(options);53 this.log += "==>downloadFile-=" + options;54 ret.promise.then(res => {55 TW_Log('FileTools---downloadFile---sucess file://' + downloadDest, res);56 // this.log+="==>downloadFile--promise="+JSON.stringify(res)+"---state--"+res.statusCode;57 if (`${res.statusCode}` != "404") {58 FileTools.unzipFile(downloadDest, TW_Store.bblStore.storeDir, onSucFuc, param);59 } else {60 this.log += "==>downloadFile--fail--notstart=";61 TW_Log('FileTools --downloadFile --ä¸è½½æ件ä¸åå¨--', downloadDest);62 TW_Store.commonBoxStore.isShow = false;63 if (onSucFuc) {64 onSucFuc({rs: false, param})65 }66 }67 }).catch(err => {68 TW_Log('FileTools --downloadFile --fail err', err);69 });70 } catch (e) {71 TW_Log("FileTools---downloadFile--error", error);72 }73 }74 //解å75 static unzipFile(srcZip, destDir, onSucFuc, param) {76 TW_Log(`FileTools--unzip start------ ${srcZip}`);77 // zipPathï¼zipçè·¯å¾78 // destDirï¼è§£åå°çç®å½79 unzip(srcZip, destDir)80 .then((path) => {81 if (onSucFuc) {82 Toast.showShortCenter(param.gameName + " åå¤å®æ");83 onSucFuc({rs: true, param})84 }85 TW_Log(`FileTools-- unzip completed at------ ${path}`);86 })87 .catch((error) => {88 Toast.showShortCenter(param.gameName + " 解å失败");89 if (onSucFuc) {90 onSucFuc({rs: false, param})91 }92 RNFS.unlink(srcZip).then(() => {93 TW_Log("FileTools--- å é¤æ件----srcZip==" + srcZip)94 }).catch((err) => {95 TW_Log("FileTools--- å é¤æ件失败");96 });97 })98 }99 async exist(target_dir) {100 let target_dir_exist = await RNFS.exists(target_dir);101 if (target_dir_exist) {102 return true;103 } else {104 return false;105 }106 }107 static async onSaveCameraRoll(base64Img, success = null, fail = null,isBase64=true) {108 if (NativeModules.RNFetchBlob) {109 if (G_IS_IOS) {110 FileTools.saveCameraRoll(base64Img, success, fail,isBase64);111 } else {112 try {113 // PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE114 const granted = await PermissionsAndroid.request(115 PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE116 );117 TW_Log("Image saved granted--", granted)118 if (granted === PermissionsAndroid.RESULTS.GRANTED) {119 TW_Log('You can use the WRITE_EXTERNAL_STORAGE');120 FileTools.saveCameraRoll(base64Img, success, fail,isBase64);121 } else {122 Toast.showShortCenter(" 请å
å
许使ç¨ç¸ååè½ æè½ä¿åå¾ç!");123 }124 } catch (err) {125 console.warn(err);126 }127 }128 } else {129 Toast.showShortCenter("请å®è£
ææ°çæ¬app 尽快å°ææ°!");130 }131 }132 static saveCameraRoll = (imageSrc, success = null, fail = null,isBase64=true) => {133 const dirs = G_IS_IOS ? RNFS.LibraryDirectoryPath : RNFS.DocumentDirectoryPath; // å¤é¨æ件ï¼å
±äº«ç®å½çç»å¯¹è·¯å¾ï¼ä»
éandroidï¼134 const downloadDest = `${dirs}/${((Math.random() * 10000000) | 0)}.png`;135 if(isBase64){136 const imageDatas = imageSrc.split('data:image/png;base64,');137 const imageData = imageDatas[1];138 // TW_Log("Image saved imageSrc--downloadDest"+downloadDest, imageSrc)139 RNFetchBlob.fs.writeFile(downloadDest, imageData, 'base64').then((rst) => {140 TW_Log("Image saved imageSrc-writeFile", rst)141 try {142 CameraRoll.saveToCameraRoll(downloadDest,"photo").then((e1) => {143 success && success();144 Toast.showShortCenter(" å¾çä¿åæå!");145 }).catch((e2) => {146 fail && fail()147 Toast.showShortCenter(" å¾çä¿å失败--RNFetchBlob" + e2.toString());148 })149 } catch (e3) {150 fail && fail()151 Toast.showShortCenter(" å¾çä¿å失败--catch " + e3.toString());152 }153 });154 }else{155 try {156 CameraRoll.saveToCameraRoll(imageSrc,'photo').then((e1) => {157 TW_Log("Image saved imageSrc-saveToCameraRoll--"+imageSrc, e1)158 success && success();159 Toast.showShortCenter(" å¾çä¿åæå!");160 }).catch((e2) => {161 fail && fail()162 Toast.showShortCenter(" å¾çä¿å失败--RNFetchBlob" + e2.toString());163 })164 } catch (e3) {165 fail && fail()166 Toast.showShortCenter(" å¾çä¿å失败--catch " + e3.toString());167 }168 }169 }170 static onSaveScreen(isSavePhoto = false,captureRefName=null) {171 if(captureRefName){172 try {173 RNShot.captureRef(captureRefName,{174 format: "jpg",175 quality: 0.8,176 }).then(177 uri => {178 if (isSavePhoto) {179 FileTools.onSaveCameraRoll(uri, null, null,false);180 }181 TW_Log("Image saved to--captureRef", uri)182 },183 error => TW_Log("Image saved Oops, snapshot failed", error)184 );185 } catch (e) {186 }187 }else{188 try {189 RNShot.captureScreen({190 format: "jpg",191 quality: 0.8,192 }).then(193 uri => {194 if (isSavePhoto) {195 FileTools.onSaveCameraRoll(uri, null, null,false);196 }197 TW_Log("Image saved to--captureScreen", uri)198 },199 error => TW_Log("Image saved Oops, snapshot failed", error)200 );201 } catch (e) {202 }203 }204 }...
download.js
Source:download.js
1import React, { Component } from 'react';2import utils from './index';3import { saveDownUrl } from '../store/actions';4import { connect } from "react-redux";5import RNFS from 'react-native-fs';6var Zip = require('@remobile/react-native-zip');7const downloadDest = utils.DOWNLOADDOCUMENTPATH; //ä¸è½½ä¹åä¿åçç®å½8// export default class Downloader {9// constructor(path, docName, callback) {10// this.path = path;11// this.docName = docName;12// this.callback = callback;13// }14// download() {15// let that = this;16// const progress = data => {17// const percentage = ((100 * data.bytesWritten) / data.contentLength) || 0;18// const text = `Progress ${percentage}%`;19// callback({ "path": that.path, "docName": that.docName, "status": "downloading", "progress": percentage.toFixed(0) + " %" });20// console.log(text);21// };22// const begin = res => {23// callback({ "path": that.path, "docName": that.docName, "status": "start", "progress": "0%" });24// console.log('Download has begun');25// };26// const progressDivider = 1;27// const ret = RNFS.downloadFile({28// fromUrl: that.path,29// toFile: downloadDest + "/" + that.docName + ".zip",30// begin,31// progress,32// progressDivider33// });34// ret.promise.then(res => {35// console.log("file download ");36// console.log(downloadDest);37// console.log(res);38// callback({ "path": that.path, "docName": that.docName, "status": "success", "progress": "å¤çä¸", unzip: "start" });39// // è°ç¨è§£åå½æ°40// this.unzipNewCourse(that.docName);41// }).catch(err => {42// callback({ "path": that.path, "docName": that.docName, "status": "faild", "progress": "0%" });43// console.log(err)44// });45// }46// unzipNewCourse(docName) {47// const oriPath = downloadDest + "/" + docName + ".zip";48// const newPath = downloadDest + "/" + docName;49// Zip.unzip(oriPath, newPath, (err) => {50// if (err) {51// debugger52// callback({ "path": path, "docName": docName, "status": "success", "progress": "0%", unzip: "faild" });53// // 解å失败54// console.log('error')55// }56// else {57// // //解åæåï¼å°zipå é¤58// RNFS.unlink(oriPath).then(() => {59// callback({ "path": path, "docName": docName, "status": "success", "progress": "100%", unzip: "success" });60// });61// console.log('success__newPath==' + newPath);62// }63// });64// }65// }66// let downloader = new Downloader(adsf,adf);67// downloader.callback = function(){};68module.exports = (path, docName, callback) => {// åæ°åä¸ä¸69 return {70 download() {71 // const progress = data => {72 // const percentage = ((100 * data.bytesWritten) / data.contentLength) || 0;73 // const text = `Progress ${percentage}%`;74 // callback({ "path": path, "docName": docName, "status": "downloading", "progress": percentage.toFixed(0) + " %" });75 // console.log(text);76 // };77 // const begin = res => {78 // callback({ "path": path, "docName": docName, "status": "start", "progress": "0%" });79 // console.log('Download has begun');80 // };81 const progressDivider = 1;82 const options = {83 fromUrl: path,84 toFile: downloadDest + "/" + docName + ".zip",85 begin:(res)=>{86 callback({ "path": path, "docName": docName, "status": "start", "progress": "0%" });87 console.log('Download has begun');88 },89 progress:(data)=>{90 const percentage = ((100 * data.bytesWritten) / data.contentLength) || 0;91 const text = `Progress ${percentage}%`;92 callback({ "path": path, "docName": docName, "status": "downloading", "progress": percentage.toFixed(0) + " %" });93 console.log(text);94 },95 progressDivider,96 }97 // const ret = RNFS.downloadFile({98 // fromUrl: path,99 // toFile: downloadDest + "/" + docName + ".zip",100 // begin,101 // progress,102 // progressDivider,103 // });104 let ret;105 try{106 ret = RNFS.downloadFile(options);107 ret.promise.then(res => {108 console.log("file download ");109 console.log(downloadDest);110 console.log(res);111 callback({ "path": path, "docName": docName, "status": "success", "progress": "å¤çä¸", unzip: "start" });112 // è°ç¨è§£åå½æ°113 this.unzipNewCourse(docName);114 115 }).catch(err => {116 callback({ "path": path, "docName": docName, "status": "faild", "progress": "0%" });117 console.log(err)118 });119 }120 catch(error){121 callback({ "path": path, "docName": docName, "status": "faild", "progress": "0%" });122 console.log(error);123 }124 return ret;125 },126 unzipNewCourse(docName) {127 const oriPath = downloadDest + "/" + docName + ".zip";128 const newPath = downloadDest + "/" + docName;129 //å¦æåæ¥åå¨ç®å½ å æåæ¥ç®å½ 130 RNFS.unlink(newPath)131 .then(()=>{132 console.log('å é¤æå');133 })134 .catch((err)=>{135 console.log(err.message);136 })137 setTimeout(()=>{138 Zip.unzip(oriPath, newPath, (err) => {139 if (err) {140 callback({ "path": path, "docName": docName, "status": "success", "progress": "0%", unzip: "faild" });141 // 解å失败142 console.log('error')143 }else {144 // //解åæåï¼å°zipå é¤145 RNFS.unlink(oriPath).then(() => {146 callback({ "path": path, "docName": docName, "status": "success", "progress": "100%", unzip: "success" });147 });148 149 console.log('success__newPath==' + newPath);150 }151 },(progress)=>{152 // callback({ "path": path, "docName": docName, "status": "success", "progress": "0%", unzip: "faild" });153 console.log(progress);154 });155 },500)156 157 }158 }...
Gruntfile.js
Source:Gruntfile.js
1/**2 * Copyright © 2014, 2015 dr. ir. Jeroen M. Valk3 * 4 * This file is part of ComPosiX. ComPosiX is free software: you can5 * redistribute it and/or modify it under the terms of the GNU Lesser General6 * Public License as published by the Free Software Foundation, either version 37 * of the License, or (at your option) any later version.8 * 9 * ComPosiX is distributed in the hope that it will be useful, but WITHOUT ANY10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR11 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more12 * details.13 * 14 * You should have received a copy of the GNU Lesser General Public License15 * along with ComPosiX. If not, see <http://www.gnu.org/licenses/>.16 */17/* global require, module, __dirname, process */18var cpxpkg = JSON.parse(require('fs').readFileSync(require('path').resolve(__dirname, 'package.json')));19var gruntConfig = require("./src/main/scripts/gruntConfig");20module.exports = gruntConfig({21 properties : {22 cpx : cpxpkg.name,23 cpxdir : "node_modules/" + cpxpkg.name,24 cpxver : cpxpkg.version25 },26 lifecycle : {27 "pre-clean" : {},28 "clean" : {29 depends : "pre-clean"30 },31 "validate" : {},32 "initialize" : {33 depends : "validate"34 },35 "generate-sources" : {36 depends : "initialize"37 },38 "process-sources" : {39 depends : "generate-sources"40 },41 "generate-resources" : {42 depends : "process-sources"43 },44 "process-resources" : {45 depends : "generate-resources"46 },47 "compile" : {48 depends : "process-resources"49 },50 "process-classes" : {51 depends : "compile"52 },53 "generate-test-sources" : {54 depends : "process-classes"55 },56 "process-test-sources" : {57 depends : "generate-test-sources"58 },59 "generate-test-resources" : {60 depends : "process-test-sources"61 },62 "process-test-resources" : {63 depends : "generate-test-resources"64 },65 "test-compile" : {66 depends : "process-test-resources"67 },68 "process-test-classes" : {69 depends : "test-compile"70 },71 "test" : {72 depends : "process-test-classes"73 },74 "prepare-package" : {75 depends : "test"76 },77 "package" : {78 depends : "prepare-package"79 },80 "pre-integration-test" : {81 depends : "package"82 },83 "integration-test" : {84 depends : "pre-integration-test"85 },86 "post-integration-test" : {87 depends : "integration-test"88 },89 "verify" : {90 depends : "post-integration-test"91 },92 "install" : {93 depends : "verify"94 },95 "deploy" : {96 depends : "install"97 },98 "start" : {99 depends : "process-test-classes"100 },101 "stop" : {},102 "restart" : {103 depends : "stop",104 invoke : "start"105 }106 },107 executions : {108 "clean" : [ "clean" ],109 "validate" : [ "validate" ],110 "initialize" : [ "if-missing:curl-dir" ],111 "generate-sources" : [ "jison" ],112 "generate-resources" : [ "classpath" ],113 "compile" : [ "uglify" ],114 "test" : [ "jshint:all", "jasmine:node" ],115 "package" : [ "compress" ],116 "pre-integration-test" : [ "unzip" ],117 "start" : [ "lock", "server:karma", "connect" ],118 "stop" : [ "stop" ]119 },120 clean : [ "dist" ],121 'curl-dir' : {122 'dist/lib' : [ "http://requirejs.org/docs/release/2.1.11/comments/require.js", "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.js",123 "http://code.angularjs.org/1.2.13/angular.js", "https://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.3/js/foundation/foundation.js",124 "https://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.3/css/foundation.css", "http://requirejs.org/docs/release/1.0.5/minified/order.js" ]125 },126 connect : {127 test : {128 options : {129 keepalive : true,130 hostname : "*",131 port : 8080,132 base : Object.keys({133 "src/test/webapp" : 0,134 "src/main/webapp" : 0,135 "src/test" : 0,136 "src/main" : 0,137 "dist" : 0,138 "src" : 0,139 "<%= properties.cpxdir %>/src/main" : 0,140 "<%= properties.cpxdir %>" : 0141 })142 }143 }144 },145 jshint : {146 all : [ "*.js", "src/main/scripts/*.js", "src/main/javascript/**/*.js", "src/test/javascript/**/*.js" ]147 },148 uglify : {149 definition : {150 options : {151 maxLineLen : 160,152 banner : Object.keys({153 "/*_____________________________________________<%= grunt.template.today('yyyy-mm-dd') %>\n" : 0,154 "* Copyright © 2010-2014 dr. ir. Jeroen Valk\n" : 0,155 "*\n" : 0,156 "* <%= properties.cpx %> - v<%= properties.cpxver %> - definition.min.js:\n" : 0,157 "* - http://github.com/jeroenvalk/badgerfish/\n" : 0,158 "* - http://www.npmjs.org/package/badgerfish.composix/\n" : 0,159 "* - http://code.google.com/p/composix/\n" : 0,160 "* - http://www.agentsatwork.nl/\n" : 0,161 "* ---------------------GNU Lesser General Public License\n" : 0,162 "* LGPLv3: http://www.gnu.org/licenses\n" : 0,163 "*/\n" : 0164 }).join("")165 },166 files : [ {167 src : [ "<%= properties.cpxdir %>/src/main/javascript/nl/agentsatwork/globals/Definition.js" ],168 dest : "dist/script/definition.min.js",169 nonull : true170 } ]171 }172 },173 compress : {174 main : {175 archive : "dist/<%= pkg.name %>-<%= pkg.version %>.zip"176 }177 },178 unzip : {179 main : {180 src : "dist/<%= pkg.name %>-<%= pkg.version %>.zip",181 dest : "target/<%= pkg.name %>-<%= pkg.version %>"182 }183 },184 karma : {185 // base path that will be used to resolve all patterns (eg. files,186 // exclude)187 basePath : '',188 // frameworks to use189 // available frameworks: https://npmjs.org/browse/keyword/karma-adapter190 frameworks : [ 'jasmine', 'requirejs', 'chai' ],191 // list of files / patterns to load in the browser192 files : [ '<%= properties.cpxdir %>/src/main/scripts/shims.js', '<%= properties.cpxdir %>/src/main/scripts/karma.js', {193 pattern : './src/main/scripts/*Only.js',194 included : false195 }, {196 pattern : './src/test/javascript/nl/**/*.js',197 included : false198 }, {199 pattern : './src/main/javascript/**/*.js',200 included : false201 }, {202 pattern : '<%= properties.cpxdir %>/src/main/javascript/**/*.js',203 watched : false,204 included : false205 }, {206 pattern : './src/test/templates/*',207 included : false208 }],209 // proxy to the grunt connect server210 proxies : {211 '/base/src/test/javascript/' : 'http://localhost:8080/javascript/',212 '/base/src/test/resources/' : 'http://localhost:8080/resources/'213 },214 // list of files to exclude215 exclude : [],216 // preprocess matching files before serving them to the browser217 // available preprocessors:218 // https://npmjs.org/browse/keyword/karma-preprocessor219 preprocessors : {},220 // test results reporter to use221 // possible values: 'dots', 'progress'222 // available reporters: https://npmjs.org/browse/keyword/karma-reporter223 reporters : [ 'progress' ],224 // web server port225 port : 9876,226 // enable / disable colors in the output (reporters and logs)227 colors : true,228 // enable / disable watching file and executing tests whenever any file229 // changes230 autoWatch : true,231 // start these browsers232 // available browser launchers:233 // https://npmjs.org/browse/keyword/karma-launcher234 browsers : [ 'Chrome' ],235 // Continuous Integration mode236 // if true, Karma captures browsers, runs the tests and exits237 singleRun : false238 }...
cb2pdf.node.js
Source:cb2pdf.node.js
1#!/usr/bin/env node2const exec = require('child_process').exec;3const os = require('os');4const fs = require('fs'); // http://nodejs.org/api/fs.html5const argv = require('optimist').argv; // https://github.com/substack/node-optimist6const admzip = require('adm-zip'); // https://github.com/cthackers/adm-zip7const rimraf = require('rimraf'); // https://github.com/isaacs/rimraf8const find = require('find'); // https://npmjs.org/package/find9const Magic = require('mmmagic').Magic; // https://github.com/mscdex/mmmagic10const imagick = require('node-imagemagick'); // https://github.com/rsms/node-imagemagick11const tmp = `${os.tmpdir()}/${new Date().getTime()}/`12const usage = `Usage:13 To convert from cbr/cbz to PDF: cb2pdf.node.js --comic="path/to/comic.cbr|cbz"14 To create a PDF from a path of images: cb2pdf.node.js --path="path/to/images/" --bookname="Name of PDF"`;15const cbc = {16 format: '',17 intervalChrs: ["\u2580","\u2584","\u2585","\u2586","\u2587","\u2588"],18 comic: argv.comic || null,19 convPath: argv.path || null,20 bookName: argv.bookname || null,21 isConversion: false,22 isCreation: false,23 imageFiles: [],24 init: function() {25 cbc.errorCheck();26 if (cbc.isConversion) {27 cbc.formatDetection();28 } else if (cbc.isCreation) {29 tmp = cbc.convPath;30 console.log(cbc.bookName);31 cbc.comic = cbc.bookName.replace(/\.pdf$/,'')+'.pdf';32 cbc.startCreation();33 }34 },35 formatDetection: function() {36 // I have found that there are many erronously extensioned files in the world, I detect first.37 const magic = new Magic();38 magic.detectFile(cbc.comic, function(err, result) {39 if (err) throw err;40 cbc.format = result.match(/^\w\w\w/)[0].toLowerCase();41 if (['zip','rar'].indexOf(cbc.format) === -1) {42 console.log(`Invalid file type: ${cbc.format}`);43 process.exit(1);44 }45 cbc.startConversion();46 });47 },48 errorCheck: function() {49 const tooManyParams = (cbc.comic !== null && cbc.convPath !== null && cbc.bookName !== null);50 cbc.isConversion = (tooManyParams === false && cbc.comic !== null);51 cbc.isCreation = (tooManyParams === false && cbc.isConversion === false && cbc.convPath !== null && cbc.bookName !== null);52 // Invalid parameter combination.53 if (tooManyParams == true) {54 console.log('Invalid parameter combination.');55 console.log(usage);56 process.exit(1);57 }58 // Invalid file type59 if (cbc.isConversion === true && !/\.cb[rz]$/.test(cbc.comic.toLowerCase())) {60 console.log('Invalid comic file. I only support cbr and cbz files.');61 console.log(usage);62 process.exit(1);63 }64 // Not a conversion or creation.65 if (cbc.isConversion === false && cbc.isCreation === false) {66 console.log("Not sure what you're trying to do.");67 console.log(usage);68 process.exit(1);69 }70 return;71 },72 startConversion: function() {73 console.log('Making temp path: '+ tmp);74 fs.mkdir(tmp,'0777',function(err) {75 if (err) throw err;76 (cbc.format === 'rar') ? cbc.extract.unrar() : cbc.extract.unzip();77 });78 },79 startCreation: function() {80 cbc.findFiles();81 },82 extract: {83 unrar: function() {84 console.log('Extracting cbr: '+ cbc.comic);85 const cmd = `unrar e -y -inul "${cbc.comic}" ${tmp}`;86 exec(cmd, function(err, stdout, stderr) {87 // unrar may throw errors but not actually die88 if (err != null && err.killed === true) throw err;89 cbc.findFiles();90 return;91 });92 },93 unzip: function() {94 console.log(`Extracting cbz: ${cbc.comic}`);95 const rs = fs.createReadStream(cbc.comic);96 const zip = new admzip(cbc.comic).extractAllTo(tmp);97 cbc.findFiles();98 return;99 }100 },101 findFiles: function() {102 find.file(/\.(jpeg|jpg|png|gif)$/i, tmp, function(files) {103 cbc.imageFiles = files;104 cbc.buildPDF();105 });106 },107 buildPDF: function() {108 const convArgs = [];109 cbc.imageFiles.sort().forEach(function(f) {110 convArgs.push(f);111 });112 convArgs.push('-quality');113 convArgs.push('0');114 convArgs.push('-adjoin');115 convArgs.push(cbc.comic.replace(/\.cb[rz]/i,'.pdf'));116 console.log(`Making PDF: ${cbc.comic.replace(/\.cb[rz]/i,'.pdf')}`);117 cbc.toggleInterval();118 imagick.convert(convArgs,function(err, stdout){119 cbc.toggleInterval();120 if (err) {121 throw err;122 }123 cbc.removeTemp();124 });125 },126 removeTemp: function() {127 console.log(`Cleaning up temp: ${tmp}`);128 rimraf(tmp, function(err) {129 if (err) throw err;130 });131 console.log("---Finished---\n");132 },133 toggleInterval: function() {134 // Displays a chr to show that it is still doing something, useful for very large CB files.135 cbc.interval = cbc.interval || false;136 if (!cbc.interval) {137 cbc.interval = setInterval(function() {138 // Display a random character for this interval.139 process.stdout.write(cbc.intervalChrs[Math.ceil(Math.random()*cbc.intervalChrs.length)-1]);140 },500);141 } else {142 clearInterval(cbc.interval);143 process.stdout.write("\n");144 cbc.interval = false;145 }146 }147};...
unzip_spec.js
Source:unzip_spec.js
1require('../../spec_helper')2const os = require('os')3const path = require('path')4const snapshot = require('snap-shot-it')5const fs = require(`${lib}/fs`)6const util = require(`${lib}/util`)7const logger = require(`${lib}/logger`)8const unzip = require(`${lib}/tasks/unzip`)9const stdout = require('../../support/stdout')10const normalize = require('../../support/normalize')11const version = '1.2.3'12const installDir = path.join(os.tmpdir(), 'Cypress', version)13describe('lib/tasks/unzip', function () {14 require('mocha-banner').register()15 beforeEach(function () {16 this.stdout = stdout.capture()17 os.platform.returns('darwin')18 sinon.stub(util, 'pkgVersion').returns(version)19 })20 afterEach(function () {21 stdout.restore()22 // return fs.removeAsync(installationDir)23 })24 it('throws when cannot unzip', function () {25 const ctx = this26 return unzip27 .start({28 zipFilePath: path.join('test', 'fixture', 'bad_example.zip'),29 installDir,30 })31 .then(() => {32 throw new Error('should have failed')33 })34 .catch((err) => {35 logger.error(err)36 snapshot('unzip error', normalize(ctx.stdout.toString()))37 })38 })39 it('can really unzip', function () {40 const onProgress = sinon.stub().returns(undefined)41 return unzip42 .start({43 zipFilePath: path.join('test', 'fixture', 'example.zip'),44 installDir,45 progress: { onProgress },46 })47 .then(() => {48 expect(onProgress).to.be.called49 return fs.statAsync(installDir)50 })51 })...
index.js
Source:index.js
1require('./env');2const Koa = require('koa');3const app = new Koa();4const Router = require('koa-router');5const koaBody = require('koa-body');6const unzip = require('./lib/unzip');7const router = new Router();8const URLSafeBase64 = function(str) {9 return new Buffer(str, 'base64').toString('utf-8');10};11// response12app.use(koaBody());13router.post('/unzip', async (ctx, next) => {14 const body = ctx.request.body;15 const zip = body.url;16 const bucket = body.bucket;17 const prefix = body.prefix || '';18 if(process.env.IP_WHITELIST.indexOf(ctx.ip) || (body.token && body.token === process.env.ACCESS_TION)) {19 if(!zip || ! bucket) {20 ctx.throw(400, 'zip url and bucket reqired');21 }22 try {23 const result = await unzip(URLSafeBase64(bucket), URLSafeBase64(prefix), URLSafeBase64(zip))24 ctx.body = result;25 }26 catch(err) {27 console.log(err);28 ctx.throw(400, '解å失败' + JSON.stringify(err));29 }30 }31 else {32 ctx.throw(400, 'unauthorized')33 }34});35router.get('/health', async (ctx) => {36 ctx.body = 'health';37});38app39.use(router.routes())40.use(router.allowedMethods());41app.listen(9100, function() {42 console.log('unzip start on 9100');43});44app.on('error', function(err) {45 console.log(err)...
Using AI Code Generation
1it('should unzip file', () => {2 .fixture('test.zip', 'base64')3 .then(Cypress.Blob.base64StringToBlob)4 .then((fileContent) => {5 const file = new File([fileContent], 'test.zip', { type: 'application/zip' });6 const dataTransfer = new DataTransfer();7 dataTransfer.items.add(file);8 const fileList = dataTransfer.files;9 return cy.get('#file').upload({ fileList, subjectType: 'drag-n-drop' });10 });11});
Using AI Code Generation
1describe('Unzip Test', function () {2 it('Unzip Test', function () {3 cy.get('body').then(($body) => {4 if ($body.find('a').length > 0) {5 cy.get('a').then(($a) => {6 if ($a.text().includes('Download')) {7 cy.get('a').click()8 }9 })10 }11 })12 cy.wait(5000)13 cy.readFile('downloads/dummy.pdf').then((content) => {14 cy.writeFile('downloads/dummy.zip', content)15 cy.unzip('downloads/dummy.zip', 'unzipped')16 })17 cy.readFile('unzipped/dummy.pdf').should('exist')18 })19})
Using AI Code Generation
1describe('Unzip file', () => {2 it('Unzip file', () => {3 cy.unzip('cypress/fixtures/sample.zip', 'cypress/fixtures/unzip');4 cy.readFile('cypress/fixtures/unzip/sample.txt').then((content) => {5 expect(content).to.equal('Hello World');6 });7 });8});9{10 "env": {11 },12}13const unzip = require('cypress-unzip');14module.exports = (on, config) => {15 unzip(on, config);16 return config;17};18module.exports = (on, config) => {19 on('task', {20 unzip(options) {21 return require('unzipper').Open.file(options.zipFilePath).then((d) => {22 return d.extract({23 });24 });25 },26 });27};28{29 "dependencies": {30 }31}32{33 "dependencies": {34 "buffer-crc32": {
Using AI Code Generation
1describe('Unzip Test', function () {2 it('Unzip Test', function () {3 cy.get('body').then(($body) => {4 if ($body.find('a').length > 0) {5 cy.get('a').then(($a) => {6 if ($a.text().includes('Download')) {7 cy.get('a').click()8 }9 })10 }11 })12 cy.wait(5000)13 cy.readFile('downloads/dummy.pdf').then((content) => {14 cy.writeFile('downloads/dummy.zip', content)15 cy.unzip('downloads/dummy.zip', 'unzipped')16 })17 cy.readFile('unzipped/dummy.pdf').should('exist')18 })19})
Using AI Code Generation
1describe('Unzip file', () => {2 it('Unzip file', () => {3 cy.unzip('cypress/fixtures/sample.zip', 'cypress/fixtures/unzip');4 cy.readFile('cypress/fixtures/unzip/sample.txt').then((content) => {5 expect(content).to.equal('Hello World');6 });7 });8});9{10 "env": {11 },12}13const unzip = require('cypress-unzip');14module.exports = (on, config) => {15 unzip(on, config);16 return config;17};18module.exports = (on, config) => {19 on('task', {20 unzip(options) {21 return require('unzipper').Open.file(options.zipFilePath).then((d) => {22 return d.extract({23 });24 });25 },26 });27};28{29 "dependencies": {30 }31}32{33 "dependencies": {34 "buffer-crc32": {
Using AI Code Generation
1describe('Unzip', () => {2 it('Unzip file', () => {3 cy.unzip.start('example.zip', 'example.csv')4 })5})6import 'cypress-unzip'
Using AI Code Generation
1You can use fs-extra to copy the file from the unzipped folder to the folder that you want to use in your tests.ip.start() method will unzip the file2describe('Unzip file', () => {3 it('Unzip file', () => {4 cy.unzip.start({5 })6 })7})8describe('Verify the unzipped file', () => {9 it('Verify the unzipped file', () => {10 cy.unzip.verify({11 })12 })13})14describe('Delete the unzipped file', () => {15 it('Delete the unzipped file', () => {16 cy.unzip.end({17 })18 })19})20describe('Delete the unzipped file', () => {21 it('Delete the unzipped file', () => {22 cy.unzip.end({23 })24 })25})26describe('Delete the unzipped file', () => {27 it('Delete the unzipped file', () => {28 cy.unzip.end({29 })30 })31})32describe('Delete the unzipped file', () => {33 it('Delete the unzipped file', () => {34 cy.unzip.end({35 })36 })37})
Using AI Code Generation
1import unzip from 'cypress-file-upload';2describe('Test', () => {3 it('Test', () => {4 unzip.start('Cypress/fixtures/test.zip');5 });6});
Using AI Code Generation
1Cypress.Commands.add('unzip', (zipFile, unzipDir) => {2 cy.task('unzip', {zipFile, unzipDir})3 })4module.exports = (on, config) => {5 on('task', {6 unzip({ zipFile, unzipDir }) {7 return require('unzipper').Open8 .file(zipFile)9 .then(d => d.extract({ path: unzipDir }))10 },11 })12 }
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!!