module.exports = function testCanSymlink(options) { options = options || {}; var fs = options.fs || require('fs'); var canLinkSrc = tmp.tmpNameSync(); var canLinkDest = tmp.tmpNameSync(); try { fs.writeFileSync(canLinkSrc, ''); } catch (e) { return false } try { fs.symlinkSync(canLinkSrc, canLinkDest) } catch (e) { fs.unlinkSync(canLinkSrc) return false } fs.unlinkSync(canLinkSrc) fs.unlinkSync(canLinkDest) return true }
beforeEach(function() { this.output1Path = tmp.tmpNameSync(); this.output2Path = tmp.tmpNameSync(); this.output1 = fs.createWriteStream(this.output1Path); this.output2 = fs.createWriteStream(this.output2Path); });
function verify (t, req) { var expected = path.join(__dirname, 'expected.png'); var actual = tmp.tmpNameSync({ postfix: '.png' }); var diff = tmp.tmpNameSync({ postfix: '.png' }); var tunnel; contra.concurrent({ psi: insights, screenshot: screenshot }, assessment); function insights (next) { console.log('\n' + exercise.__('tunnel', { port: req.port })); localtunnel(req.port, tunneled); function tunneled (err, tune) { if (err) { next(err); return; } tunnel = tune; console.log(exercise.__('get_feedback', { url: tune.url })); psi(tune.url, next); } } function screenshot (done) { contra.series({ take: function take (next) { webshot(req.url, actual, next); }, compare: function compare (next) { imageDiff({ actualImage: actual, expectedImage: expected, diffImage: diff, threshold: 0.1 }, next); } }, done); } function assessment (err, result) { if (err) { t.error(err); return; } var amount = result.psi.pageStats.numberResources; tunnel.close(); t.fgroup('overall'); t.fpass('psi_score', { amount: amount }, amount < 5); t.fpass('visualcomp', result.screenshot.compare); t.end(); } }
it('Policy should create a role that can spawn command', function (done) { this.timeout(240000); var testFile = utils.escapeBackSlash(tmp.tmpNameSync() + '.TEST'), incFile = path.join(__dirname, 'include_test.p2'); p2Test.runP2Str( 'p2\n' + '.include(\'{{{ incFile }}}\')\n' + '.file(\'{{{ testFile }}}\', {ensure: \'absent\'})\n' + '._testRole_(\'MyTest\', {arg1: \'MyArgument1\', testFile: \'{{{ testFile }}}\'});', { testFile: testFile, incFile: incFile } ) .then(function () { return pfs.pExists(testFile); }) .then(function (exists) { exists.should.be.true; return pfs.pUnlink(testFile); }) .then(function (err) { should(err).be.undefined; done(); }) .done(null, function (err) { done(err); }); });
busboy.on('file', function (fieldName, stream, filename, encoding, mimeType) { // If fieldName ends in [], it was intended to be an array of files if ( // fieldname has not already been added to formData obj typeof formData[fieldName] === 'undefined' // and it is a string && typeof fieldName === 'string' // and last 2 chars are [] (per FormData.append client api) && fieldName.slice(-2) == '[]') { formData[fieldName] = [] } //save tmp files const tmpDir = (options.uploadDir ? options.uploadDir : os.tmpDir()); const tmpPath = tmp.tmpNameSync({ template: tmpDir + '/upload-XXXXXXXXXXXXXXXXXXX' }); stream.pipe(fs.createWriteStream(tmpPath)); stream.on('end', function () { //push file data var data = { fileName: filename, mimeType: mimeType, tmpPath: tmpPath }; if (Array.isArray(formData[fieldName])) { formData[fieldName].push(data) } else { formData[fieldName] = data } }); stream.on('limit', function () { hasError = 'filesSizeLimit'; }); });
(async function () { try { const tempPath = tmp.tmpNameSync(); const db = await DB.open(tempPath); expect(db instanceof DB); expect((await db.get('PRAGMA user_version')).user_version === 0); // Make a v1 DB. const storage = new ProfileStorage(db); await new ProfileStorageSchemaV1().createOrUpdate(storage); expect((await db.get('PRAGMA user_version')).user_version === 1); // Upgrade it. await storage.init(); expect((await db.get('PRAGMA user_version')).user_version === 2); await storage.close(); console.log('Cleaning up.'); fs.unlinkSync(tempPath); // Clean up. done(); } catch (e) { done(e); } }());
beforeEach(function() { var workingDirectory = tmpName(); mkdirp.sync(workingDirectory); job = new JobClass(); job.setWorkingDirectory(workingDirectory); });
it('can write out a few points correctly', function(done) { var tmpFilename = tmp.tmpNameSync(); var stream = fs.createWriteStream(tmpFilename); stream.on('open', function() { var serializer = serializers.getSerializer('csv', stream); var data = [ { time: '2014-01-01T00:00:00.000Z', foo: 'bar' }, { time: '2014-02-01T00:00:00.000Z', foo: 'buzz' }, { time: '2014-03-01T00:00:00.000Z', foo: 'bizz' } ]; serializer.write(data); serializer.done() .then(() => { var parser = parsers.getParser('csv'); var results = []; parser.parseStream(fs.createReadStream(tmpFilename), function(result) { results.push(result); }) .then(function() { expect(results).to.deep.equal([data]); done(); }) .catch(function(err) { done(err); }) .finally(function() { fs.unlinkSync(tmpFilename); }); }); }); });
create: (dir, outfile) => { // Move nxtpm.json to tmp dir let tempFile; const manifest = path.resolve( path.join(dir, config.get('filename')) ); if (jetpack.exists(manifest)) { tempFile = tmp.tmpNameSync(); jetpack.move(manifest, tempFile); } const compress = new Targz(); return new Promise((resolve, reject) => { compress.compress(dir, outfile, err => { if (err) { return reject(err); } log.info('Created', path.resolve(outfile)); const hash = crypto.createHash('sha256'); const stream = fs.createReadStream(outfile); stream.on('data', data => hash.update(data, 'utf8')); stream.on('end', () => { const checksum = hash.digest('hex'); log.info('Checksum %s (sha256)', checksum); if (tempFile) { jetpack.move(tempFile, manifest); } resolve(checksum); }); }); }); },
/** * Return a new instance of PDFMerge * @param pdfFiles * @param pdftkPath * @returns {PDFMerge} * @constructor */ function PDFMerge(pdfFiles, pdftkPath) { if(!_(pdfFiles).isArray() || pdfFiles.length === 0) { throw new Error('pdfFiles must be an array of absolute file paths.'); } //Windows: Demand path to lib if(isWindowsPlatform()) { this.exec = child.execFile; if(!pdftkPath || !fs.existsSync(pdftkPath)) { throw new Error('Path to PDFtk is incorrect.'); } this.pdftkPath = pdftkPath; this.isWin = true; } else { this.exec = child.exec; } //Array of files this.pdfFiles = pdfFiles; //Get an available temporary filePath to be used in PDFtk this.tmpFilePath = tmp.tmpNameSync(); //Setup Arguments to be used when calling PDFtk this.execArgs = assembleExecArgs.call(this); //Default Mode 'BUFFER'; this.mode = 'BUFFER'; //Default dont keep the temporary file this.keepTmpFile = false; return this; }
(async function () { try { const tempPath = tmp.tmpNameSync(); const db = await DB.open(tempPath); expect(db).toBeA(DB); expect((await db.get('PRAGMA user_version')).user_version).toBe(0); // Make a v4 DB. const storage = new ProfileStorage(db); await new ProfileStorageSchemaV4().createOrUpdate(storage); expect((await db.get('PRAGMA user_version')).user_version).toBe(4); // Upgrade it. await storage.init(); expect((await db.get('PRAGMA user_version')).user_version).toBe(5); await storage.close(); fs.unlinkSync(tempPath); // Clean up. done(); } catch (e) { done(e); } }());
it('should be able to extract the image', function () { const output = tmp.tmpNameSync() return imageStream.getFromFilePath(file).then(function (results) { m.chai.expect(results.path).to.equal(file) m.chai.expect(_.isString(results.extension)).to.be.true m.chai.expect(_.isEmpty(_.trim(results.extension))).to.be.false if (!_.some([ results.size.original === fs.statSync(file).size, results.size.original === fs.statSync(image).size ])) { throw new Error(`Invalid size: ${results.size.original}`) } const stream = results.stream .pipe(results.transform) .pipe(fs.createWriteStream(output)) return new Bluebird((resolve, reject) => { stream.on('error', reject) stream.on('close', resolve) }) }).then(function () { return doFilesContainTheSameData(image, output) }).then(function (areEqual) { m.chai.expect(areEqual).to.be.true }).finally(function () { return deleteIfExists(output) }) })
before(function() { withoutSubdir = tmp.dirSync().name; withSubdir = tmp.dirSync().name; fs.mkdirsSync(path.join(withSubdir, 'google')); doesNotExist = tmp.tmpNameSync(); notADir = tmp.fileSync().name; });
test('screenshot to a file', t => { t.plan(1) const tmpName = tmpNameSync({ postfix: '.jpg' }) return screenshot({ filename: tmpName }).then(() => { t.truthy(existsSync(tmpName)) unlinkSync(tmpName) }) })
beforeEach(function() { workingDirectory = tmpName(); mkdirp.sync(workingDirectory); var job = new JobClass(); job.setWorkingDirectory(workingDirectory); jobPromise = job._runJobScript('pwd'); });
async _createNewTmpDir () { this.path = tmp.tmpNameSync({ dir: TempDirectory.TEMP_DIRECTORIES_ROOT, prefix: this.namePrefix + '-' }); await ensureDir(this.path); this.lockFile = new LockFile(this.path); this.lockFile.init(); }
test('screenshot to a file with a space', t => { // https://github.com/bencevans/screenshot-desktop/issues/12 t.plan(1) const tmpName = tmpNameSync({ prefix: 'sd ', postfix: '.jpg' }) return screenshot({ filename: tmpName }).then(() => { t.truthy(existsSync(tmpName)) unlinkSync(tmpName) }) })
it('fails when new fields appear in the stream', function(done) { var tmpFilename = tmp.tmpNameSync(); var stream = fs.createWriteStream(tmpFilename); var serializer = serializers.getSerializer('csv', stream); serializer .on('error', function(err) { expect(err.toString()).to.contain('Found new or missing fields: fizz'); done(); }); serializer.write([{ foo: 'bar' }]); serializer.write([{ fizz: 'buzz' }]); serializer.done(); });
function createInstaller(resourcesDir, installer_options, src, dest, resolve, reject){ const installer_name = src.inspect('.').name+'-v'+installer_options['VERSION']+'-setup'; installer_options['INSTALLER_NAME'] = dest.path(installer_name+'.exe'); installer_options['INSTALL_FILES'] = src.path(); installer_options['ARCH'] = installer_name.indexOf('64')>-1?'64':'32'; let installScript = resourcesDir.read('./installer.nsis'); for(let pattern in installer_options) installScript = installScript.replace(new RegExp('{{'+pattern+'}}','g'), installer_options[pattern]); let nsi = tmp.tmpNameSync(); jetpack.write(nsi, installScript); const nsis = childProcess.spawn('makensis', [nsi], {stdio: 'inherit'}); nsis.on('error', e=>reject('Failed building installer: '+installer_name+', reason: '+e)); nsis.on('close', ()=>fs.unlink(dest.path(nsi), (e)=>{if(e) reject(e); else resolve();})); }
return new Promise((resolve, reject) => { var ext = Path.extname(localFilePath); var tmp = require("tmp"); var tmpFilePath = tmp.tmpNameSync({ postfix: ext }); var cmdline = buildCmdline("print", '-q -o "' + tmpFilePath + '" "' + localFilePath + '"'); CP.exec(cmdline, {cwd: workspace.rootPath}, function (err, stdout, stderr) { if(err){ reject(err); } else if (stderr) { reject(stderr); } else { resolve(tmpFilePath); } }); });
tmpWindow.webContents.session.once('will-download', (event, downloadItem) => { this.imageCache[url] = file = { path: tmp.tmpNameSync() + '.' + mime.extension(downloadItem.getMimeType()), complete: false }; downloadItem.setSavePath(file.path); downloadItem.once('done', () => { tmpWindow.destroy(); tmpWindow = null; spawn('xdg-open', [file.path]); file.complete = true; }); });
.then(manifest => { if (appPath) { // generate ruff_box.json for (var i = 0; i < manifest.length; i++) { var element = manifest[i]; if (element.name === 'ruff_box.json') { fs.writeFileSync(element.name, element.content.toString()); console.log('Save ' + element.name + ' succesfully'); } } // create package only return new Promise((resolve, reject) => { try { let appBuffer = generateApp(manifest, toCompile, origin, alignment); fs.writeFileSync(appPath, appBuffer); resolve(); } catch (error) { reject(error); } }).then(() => { console.log(`Package created at "${appPath}"`); }); } else { // get program.port var parameters = parametersJS.getParameters(rap, program); if (parameters === undefined) { return; } program.port = parameters.port; // create package and deploy it let appPath = tmp.tmpNameSync(); let appBuffer = generateApp(manifest, toCompile, origin, alignment); fs.writeFileSync(appPath, appBuffer); let cp = flash({ type: 'flash-application', port: program.port, binary: appPath, address: origin }); return Promise.for(cp); } });
it('can write no points to a provided stream', function(done) { var tmpFilename = tmp.tmpNameSync(); var stream = fs.createWriteStream(tmpFilename); stream.on('open', function() { var serializer = serializers.getSerializer('csv', stream); serializer.done() .then(() => { stream.end(function(err) { if (err) { done(err); } expect(fs.readFileSync(tmpFilename).toString()).to.equal(''); done(); }); }); }); });
.then(data => { let tmpname = tmp.tmpNameSync(); function callback(err) { if (err) { return service.deferred.reject(err); } service.deferred.resolve(tmpname); } if ('sage' === type) { return fs.writeFile(tmpname, data, callback); } xlsx.write(tmpname, data, callback); }).catch(service.error);
app.get('/tts', function(req, res) { var remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress; var lang = req.query.lang; var text = req.query.text; logger('TTS: requested for lang ' + req.query.lang + ' text: ' + req.query.text, {remoteAddress: remoteAddress}); if (text == undefined || lang == undefined || text == '' || lang == '') { res.send('Error on query string'); logger('TTS: reported error on input', {remoteAddress: remoteAddress}); return; } //Generating a new tmp filename (won't be used directly, see below) var tmpPath = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' }); var wavePath = tmpPath + '.wav'; var mp3Path = tmpPath + '.mp3'; var ttsCMD = ['pico2wave', '-w', wavePath, '-l', lang, text]; logger('TTS Executing command: ' + shellescape(ttsCMD), {remoteAddress: remoteAddress}); if (exec(shellescape(ttsCMD)).code == 0) { logger('TTS OK', {remoteAddress: remoteAddress}); var wav2mp3CMD = ['avconv', '-i', wavePath, mp3Path] logger('TTS: Executing command: ' + shellescape(wav2mp3CMD), {remoteAddress: remoteAddress}); if (exec(shellescape(wav2mp3CMD)).code == 0) { logger('TTS: Wave to MP3 OK', {remoteAddress: remoteAddress}); res.sendFile(mp3Path); } else { logger('TTS: Wave to MP3 KO', {remoteAddress: remoteAddress}); res.send('Well mate, this is really weird. Something that was never supposed to fail, just failed. I guess sh!t happens. Lame error. No, really.'); } } else { logger('TTS failed', {remoteAddress: remoteAddress}); res.send('TTS failed: are you passing a proper ISO lang code? Are you trying to do funky stuff with text? I\'m watching you.'); } });
(async function () { try { const tempPath = tmp.tmpNameSync(); const db = await DB.open(tempPath); expect(db instanceof DB); fs.accessSync(tempPath); // Throws on failure. const row = await db.get('PRAGMA user_version'); expect(row.user_version).toBe(0); await db.close(); fs.unlinkSync(tempPath); // Clean up. done(); } catch (e) { done(e); } }());
it('Policy should create a role taking a title and options that can spawn command', function (done) { this.timeout(240000); var testFile = utils.escapeBackSlash(tmp.tmpNameSync() + '.TEST'); p2Test.runP2Str(heredoc(function () {/* p2 .role('_testRole_', { p2: function (title, opts) { p2 .command('echo ' + title + ': ' + opts.arg1 + ' > {{{ testFile }}}'); } }) .file('{{{ testFile }}}', {ensure: 'absent'}) ._testRole_('MyTitle', {arg1: 'MyArgument1'}); */}), { testFile: testFile } ) .then(function () { return pfs.pExists(testFile); }) .then(function (exists) { exists.should.be.true; return pfs.pReadFile(testFile); }) .then(function (data) { should(data).not.be.undefined; data = data.toString().trim(); data.should.equal('MyTitle: MyArgument1'); return pfs.pUnlink(testFile); }) .then(function (err) { should(err).be.undefined; done(); }) .done(null, function (err) { done(err); }); });
function objcopy(file, args, callback) { if (!callback) { callback = args; args = []; } var out = tmp.tmpNameSync(); var defaultArgs = ['-O', 'binary', file, out]; var proc = spawn('arm-none-eabi-objcopy', args.concat(defaultArgs)); proc.on('exit', function (code) { if (code) { log(chalk.red('Objcopy failed')); } else { var binary = fs.readFileSync(out); fs.unlinkSync(out); callback(binary); } }) }
it('builds a file that requires ' + file + ' that has at least ' + MINIMUM_SIZE + ' characters', function (done) { var inputFile = tmp.fileSync({postfix: '.js'}); var outputFileName = tmp.tmpNameSync({postfix: '.js'}); var config = { baseUrl: path.resolve(__dirname, '..', '..', 'dist', 'hosted', 'web', version, 'js'), name: inputFile.name, out: outputFileName }; this.slow(3000); fs.writeSync(inputFile.fd, 'requirejs(["' + file + '"], function () {})'); requirejs.optimize(config, function () { var contents = fs.readFileSync(config.out, 'utf8'); expect(contents.length).to.be.above(MINIMUM_SIZE); done(); }, done); });
buildApp : function() { if (!fs.existsSync('./package.bon')) { console.log('ERROR: package.bon not found!'); return; } var jamfile = path.basename(path.resolve('.')) + '.jam'; if (fs.existsSync(jamfile)) { fs.unlinkSync(jamfile); } tempfile = tmp.tmpNameSync(); zipdir('.', { saveTo:tempfile }, function(err, buffer) { if (err) { throw err; } fs.renameSync(tempfile, jamfile); }); },