testFoxxDirectories : function () { var appPath = fs.join(FoxxService._appPath, ".."); assertTrue(fs.isDirectory(fs.join(appPath, "UnitTestsRecovery1"))); assertTrue(fs.isFile(fs.join(appPath, "UnitTestsRecovery1", "foo.json"))); assertTrue(fs.isDirectory(fs.join(appPath, "UnitTestsRecovery2"))); assertFalse(fs.isFile(fs.join(appPath, "UnitTestsRecovery2", "bar.json"))); }
function getResemblePath(root){ var path = [root,'libs','resemblejs','resemble.js'].join(fs.separator); if(!fs.isFile(path)){ path = [root,'node_modules','resemblejs','resemble.js'].join(fs.separator); if(!fs.isFile(path)){ throw "[PhantomCSS] Resemble.js not found: " + path; } } return path; }
/** *Returns all the files paths in a directory *@param {string} directory The directory path *@param {Object=} options Options (optional): exclude (an array of dir paths) , extension (a String) */ function getFiles(directory, options){ var i; if(options && options.excludeDirs){ for(i = 0; i < options.excludeDirs.length; i++){ if(directory === options.excludeDirs[i]){ return []; } } } var stuff = fs.list(directory); var files = []; var directories = []; for(i = 2; i< stuff.length; i++){//starts at 2 to skip "." and ".." var path = directory + fs.separator + stuff[i]; if(fs.isFile(path) && (!options || !options.extension || fileHasExtension(stuff[i], options.extension)) && (!options || !options.excludeFiles || notInArray(stuff[i], options.excludeFiles))) { files.push(path); } if(fs.isDirectory(path)){ directories.push(path); } } for(i = 0; i < directories.length; i++){ var files = files.concat(getFiles(directories[i], options)); } return files; }
fileNameGetter: function(root, fileName) { var file = root + '/' + fileName; if (isFile(file + '.png')) { return file + '.diff.png'; } return file + '.png'; }
page.open('render_base.html', function () { // Fixed view size page.viewportSize = { width: 1200, height: 1000 }; // Switch to specific stylesheet subdirectory fs.changeWorkingDirectory(rootPath + '/' + staticPath + 'styles/' + system.args[3] + '/'); if (!fs.isWritable(fs.workingDirectory)) { // Don't have write access. returnStatus.status = -3; console.log(JSON.stringify(returnStatus)); phantom.exit(); } fs.write('preview.html', page.content, 'w'); if (!fs.isFile('preview.html')) { // Failed to store specific preview file. returnStatus.status = -4; console.log(JSON.stringify(returnStatus)); phantom.exit(); } page.close(); returnStatus.status = 0; console.log(JSON.stringify(returnStatus)); phantom.exit(); });
casper.then(function() { // onReadyScript files should export a module like so: // // module.exports = function(casper, scenario) { // // run custom casperjs code // }; // if ( scenario.onReadyScript ) { casper.echo('Running custom scripts.'); // Ensure a `.js` file suffix var script_path = scenario.onReadyScript.replace(/\.js$/, '') + '.js'; // if a casper_scripts path exists, append the onReadyScript soft-enforcing a single slash between them. if ( casper_scripts ) { script_path = casper_scripts.replace(/\/$/, '') + '/' + script_path.replace(/^\//, ''); } // make sure it's there... if ( !fs.isFile( script_path ) ) { casper.echo("FYI: onReadyScript was not found."); return; } // the require() call below is relative to this file `genBitmaps.js` (not CWD) -- therefore relative paths need shimmimg var require_script_path = script_path.replace(/^\.\.\//, '../../../').replace(/^\.\//, '../../'); require(require_script_path)(casper, scenario, vp); } });
var toFile = function(path, text) { if( fs.isFile(path)) { fs.write(path, text, "a"); } else { fs.write(path, text, "w"); } };
exports.gitinfo = function (key) { 'use strict'; var _ = require("underscore"), gitinfo, aal = getStorage(), result = aal.toArray().concat(exports.developmentMounts()), path = module.appPath(), foxxPath, completePath, gitfile, gitcontent; _.each(result, function(k) { if (k.name === key) { foxxPath = k.path; } }); completePath = path+"/"+foxxPath; gitfile = completePath + "/gitinfo.json"; if (fs.isFile(gitfile)) { gitcontent = fs.read(gitfile); gitinfo = {git: true, url: JSON.parse(gitcontent), name: key}; } else { gitinfo = {}; } return gitinfo; };
var zipDirectory = function(directory) { "use strict"; if (!fs.isDirectory(directory)) { throw directory + " is not a directory."; } var tempFile = fs.getTempFile("zip", false); var tree = fs.listTree(directory); var files = []; var i; var filename; for (i = 0; i < tree.length; ++i) { filename = fs.join(directory, tree[i]); if (fs.isFile(filename)) { files.push(tree[i]); } } if (files.length === 0) { throwFileNotFound("Directory '" + String(directory) + "' is empty"); } fs.zipFile(tempFile, directory, files); return tempFile; };
function fileNameGetter( root, fileName ) { var diffDir, origFile, diffFile; var increment = count ? '.' + count : ''; diffDir = root + '/' + currentFilename + '/' + currentDescribe; origFile = diffDir + '/' + currentWhen + increment + '.png'; diffFile = diffDir + '/' + currentWhen + increment + '.diff.png'; if ( !fs.isDirectory( diffDir ) ) { fs.makeDirectory( diffDir ); } casper.emit( 'phantomcss.screenshot', { path: origFile.replace( visualTestsRoot, '' ) } ); if ( !fs.isFile( origFile ) ) { casper.test.info( "return origfile" ); casper.test.info( "New screenshot created for " + currentWhen ); return origFile; } else { casper.test.info( "return diffile" ); return diffFile.replace( /\/\//g, '/' ); } }
phantom.initCasperCli = function initCasperCli() { var fs = require("fs"); if (!!phantom.casperArgs.options.version) { console.log(phantom.casperVersion.toString()); phantom.exit(0); } else if (phantom.casperArgs.get(0) === "test") { phantom.casperScript = fs.absolute(fs.pathJoin(phantom.casperPath, 'tests', 'run.js')); phantom.casperArgs.drop("test"); } else if (phantom.casperArgs.args.length === 0 || !!phantom.casperArgs.options.help) { var phantomVersion = [phantom.version.major, phantom.version.minor, phantom.version.patch].join('.'); var f = require("utils").format; console.log(f('CasperJS version %s at %s, using PhantomJS version %s', phantom.casperVersion.toString(), phantom.casperPath, phantomVersion)); console.log(fs.read(fs.pathJoin(phantom.casperPath, 'bin', 'usage.txt'))); phantom.exit(0); } if (!phantom.casperScript) { phantom.casperScript = phantom.casperArgs.get(0); } if (!fs.isFile(phantom.casperScript)) { console.error('Unable to open file: ' + phantom.casperScript); phantom.exit(1); } // filter out the called script name from casper args phantom.casperArgs.drop(phantom.casperScript); // passed casperjs script execution phantom.injectJs(phantom.casperScript); };
this.repackZipFile = function (path) { if (! fs.exists(path) || ! fs.isDirectory(path)) { throw "'" + String(path) + "' is not a directory"; } var tree = fs.listTree(path); var files = []; var i; for (i = 0; i < tree.length; ++i) { var filename = fs.join(path, tree[i]); if (fs.isFile(filename)) { files.push(tree[i]); } } if (files.length === 0) { throw "Directory '" + String(path) + "' is empty"; } var tempFile = fs.getTempFile("downloads", false); fs.zipFile(tempFile, path, files); return tempFile; };
service = server.listen(testServerPort, function(request, response) { /*jshint maxstatements:20*/ "use strict"; var requestPath = request.url; if (requestPath.indexOf('?') !== -1) { requestPath = request.url.split('?')[0]; } var pageFile = fs.pathJoin(phantom.casperPath, requestPath); if (!fs.exists(pageFile) || !fs.isFile(pageFile)) { response.statusCode = 404; console.log(utils.format('Test server url not found: %s (file: %s)', request.url, pageFile), "warning"); response.write("404 - NOT FOUND"); } else { var headers = {}; var binMode = false; if (/js$/.test(pageFile)) { headers['Content-Type'] = "application/javascript"; } else if (/png$/.test(pageFile)) { binMode = true; } response.writeHead(200, headers); if (binMode) { response.write(fs.read(pageFile, 'b')); } else { response.write(fs.read(pageFile)); } } response.close(); });
fs.list(fullFolderPath).forEach(function(itemName) { if(itemName == "." || itemName == "..") { return; } if(fs.isFile(fullFolderPath + itemName)) { var fileContent = fs.read(fullFolderPath + itemName); var fileLines = fileContent.split(/\n/g); var dataItems = []; fileLines.forEach(function(fileLine) { if(fileLine.trim() == "") { return; } var parts = fileLine.split(/@/gi); if(parts.length < 3) { return; } dataItems.push({ expressionCoverage: parseFloat(parts[0].slice(0,5)), branchCoverage: parseFloat(parts[1].slice(0,5)), statementCoverage: parseFloat(parts[2].slice(0,5)) }); }); coverageData[coverageType][itemName] = dataItems; } });
function () { var failFile, safeFileName, increment; if(_diffRoot){ // flattened structure for failed diffs so that it is easier to preview failFile = _diffRoot + fs.separator + file.split(fs.separator).pop().replace('.diff.png', ''); safeFileName = failFile; increment = 0; while ( fs.isFile(safeFileName+'.fail.png') ){ increment++; safeFileName = failFile+'.'+increment; } failFile = safeFileName + '.fail.png'; casper.captureSelector(failFile, 'img'); } casper.captureSelector(file.replace('.diff.png', '.fail.png'), 'img'); casper.evaluate(function(){ window._imagediff_.hasImage = false; }); }, function(){},
getIndexPagePaths = function() { var fs = require('fs'), dir = fs.absolute('test/functional-tests'), apps, appPath, indexPage, indexPagePaths = []; apps = fs.list(dir); for (var i = 0, len = apps.length; i < len; i++) { // Exclude hidden directories if (apps[i] === '.' || apps[i] === '..') { continue; } // Get the path to the apps index file appPath = dir + fs.separator + apps[i]; indexPage = appPath + fs.separator + 'index.html'; // If the index.html file exists, // add it to the indexPagePaths array if (fs.isFile(indexPage)) { indexPagePaths.push(indexPage); appCount = appCount + 1; } } return indexPagePaths; };
exports.setCookie = function() { var cookie_file = fs.pathJoin((fs.pathJoin(phantom.casperPath, 'data')), 'tencentCookies'); var cookies = fs.isFile(cookie_file) ? JSON.parse(fs.read(cookie_file)) : []; for(var i = 0; i < cookies.length; i++) { phantom.addCookie(cookies[i]); } };
files.forEach(function(file){ var rootedFile = testRoot+'/'+file; if (fs.isFile(rootedFile)) { associateFileNameWithTest(file); phantom.injectJs(rootedFile); } });
var buildAssetContent = function(app, assets, basePath) { var i, j, m; var reSub = /(.*)\/\*\*$/; var reAll = /(.*)\/\*$/; var files = []; for (j = 0; j < assets.length; ++j) { var asset = assets[j]; var match = reSub.exec(asset); if (match !== null) { m = fs.listTree(fs.join(basePath, match[1])); // files are sorted in file-system order. // this makes the order non-portable // we'll be sorting the files now using JS sort // so the order is more consistent across multiple platforms m.sort(); for (i = 0; i < m.length; ++i) { var filename = fs.join(basePath, match[1], m[i]); if (! excludeFile(m[i])) { if (fs.isFile(filename)) { files.push(filename); } } } } else { match = reAll.exec(asset); if (match !== null) { throw new Error("Not implemented"); } else { if (! excludeFile(asset)) { files.push(fs.join(basePath, asset)); } } } } var content = ""; for (i = 0; i < files.length; ++i) { try { var c = fs.read(files[i]); content += c + "\n"; } catch (err) { console.error("Cannot read asset '%s'", files[i]); } } return content; };
function () { var failFile, safeFileName, increment; if(_diffRoot){ // flattened structure for failed diffs so that it is easier to preview failFile = _diffRoot + fs.separator + file.split(fs.separator).pop().replace('.diff.png', ''); safeFileName = failFile; increment = 0; while ( fs.isFile(safeFileName+'.fail.png') ){ increment++; safeFileName = failFile+'.'+increment; } failFile = safeFileName + '.fail.png'; casper.captureSelector(failFile, 'img'); } casper.captureSelector(file.replace('.diff.png', '.fail.png'), 'img'); casper.evaluate(function(){ window._imagediff_.hasImage = false; }); if(mismatch){ test.mismatch = mismatch; _onFail(test); // casper.test.fail throws and error, this function call is aborted return; // Just to make it clear what is happening } else { _onTimeout(test); } }, function(){},
this.getTemplateSources(templateName).some(function(templatePath) { // FIXME debug mode which outputs the directories the loader tried if (fs.exists(templatePath) && fs.isFile(templatePath)) { source = fs.read(templatePath); return true; } });
var moveAppToServer = function(serviceInfo) { if (! fs.exists(serviceInfo)) { throwFileNotFound("Cannot find file: " + serviceInfo + "."); } var filePath; var shouldDelete = false; if (fs.isDirectory(serviceInfo)) { filePath = utils.zipDirectory(serviceInfo); shouldDelete = true; } if (fs.isFile(serviceInfo)) { filePath = serviceInfo; } if (!filePath) { throwBadParameter("Invalid file: " + serviceInfo + ". Has to be a direcotry or zip archive"); } var response = arango.SEND_FILE("/_api/upload", filePath); if (shouldDelete) { try { fs.remove(filePath); } catch (err2) { arangodb.printf("Cannot remove temporary file '%s'\n", filePath); } } if (! response.filename) { throw new ArangoError({ errorNum: errors.ERROR_SERVICE_UPLOAD_FAILED.code, errorMessage: errors.ERROR_SERVICE_UPLOAD_FAILED.message + ": " + String(response.errorMessage) }); } return response.filename; };
init: function() { self = this; this.developmentMode = (args[1] == 'true'), this.serverPort = String(args[2]); this.dir = String(args[3]); if(fs.isFile(this.dir + this.config.tmpFile)) { var data = JSON.parse(fs.read(this.dir + this.config.tmpFile)), selenium = JSON.parse(fs.read(this.dir + this.config.commandFile)), props = null; if(data && data.config) { self.setup.apply(self.config, [data.config, selenium]); } } else { this.kill(this.FAILED_PROPERTIES); } },
var intr = setInterval( function() { if(! fs.isFile('captcha.png') ) { web_browser.render('captcha.png') console.log('warn: enter chars from captcha.png') } if( captcha = system.stdin.readLine().trim() ) { fs.remove('captcha.png') var error = web_browser.evaluateJavaScript( "function() {\n\ var captcha = document.getElementById('captcha')\n\ if(! captcha)\n\ return 'captcha field not found'\n\ captcha.value = '" + captcha.replace(/[\r\n]/g, '') + "'\n\ node = captcha\n\ while( node = node.parentNode )\n\ if( node.tagName.toLowerCase() == 'form' || node.tagName.toLowerCase() == 'body' )\n\ break\n\ if( node.tagName.toLowerCase() != 'form')\n\ return 'captcha form not found'\n\ }" ) web_browser.sendEvent('keypress', web_browser.event.key.Enter) captcha = false clearInterval(intr) if(error) console.log(error) } else console.log('warn: enter chars from captcha.png') }, 500 )
return function(path) { var i, dir, paths = [], fileGuesses = [], file, module = { exports: {} }; if (phantomBuiltins.indexOf(path) !== -1) { return phantomRequire(path); } if (path[0] === '.') { paths.push.apply(paths, [ fs.absolute(path), fs.absolute(fs.pathJoin(requireDir, path)) ]); } else if (path[0] === '/') { paths.push(path); } else { dir = fs.absolute(requireDir); while (dir !== '' && dir.lastIndexOf(':') !== dir.length - 1) { // nodejs compatibility paths.push(fs.pathJoin(dir, 'node_modules', path)); dir = fs.dirname(dir); } paths.push(fs.pathJoin(requireDir, 'lib', path)); paths.push(fs.pathJoin(requireDir, 'modules', path)); } paths.forEach(function(testPath) { fileGuesses.push.apply(fileGuesses, [ testPath, testPath + '.js', testPath + '.coffee', fs.pathJoin(testPath, 'index.js'), fs.pathJoin(testPath, 'index.coffee'), fs.pathJoin(testPath, 'lib', fs.basename(testPath) + '.js'), fs.pathJoin(testPath, 'lib', fs.basename(testPath) + '.coffee') ]); }); file = null; for (i = 0; i < fileGuesses.length && !file; ++i) { if (fs.isFile(fileGuesses[i])) { file = fileGuesses[i]; } } if (!file) { throw new Error("CasperJS couldn't find module " + path); } if (file in requireCache) { return requireCache[file].exports; } try { var scriptCode = phantom.getScriptCode(file); new Function('module', 'exports', scriptCode)(module, module.exports); } catch (e) { phantom.processScriptError(e, file); } requireCache[file] = module; return module.exports; };
util.updateProcessTime = function (name, dateString) { var accessJSON = {}; if (fs.isFile(accessFilename)) { accessJSON = JSON.parse(fs.read(accessFilename)); } accessJSON[name] = dateString; fs.write(accessFilename, JSON.stringify(accessJSON)); };
setUp: function(test) { if (fs.exists(this.testFile) && fs.isFile(this.testFile)) { try { fs.remove(this.testFile); } catch (e) { } } },
fileNameGetter: function(root, filename) { var name = phantomcss.pathToTest + args.screenshots + '/' + filename; if (fs.isFile(name + '.png')) { return name + '.diff.png'; } else { return name + '.png'; } },
var load_state = function( session_file ) { if( fs.isFile(session_file) ) { console.log("resume " + session_file) return JSON.parse( fs.read(session_file) ) } }
pageRenderer.capture(processedFilePath, function (err) { if (err) { var indent = " "; err.stack = err.message + "\n" + indent + getPageLogsString(pageRenderer.pageLogs, indent); done(err); return; } var fail = function (message) { failCapture("file", pageRenderer, testInfo, expectedFilePath, processedFilePath, message, done); }; var pass = function () { if (options['print-logs']) { console.log(getPageLogsString(pageRenderer.pageLogs, " ")); } done(); }; var processed = pageRenderer.getPageContents(); fs.write(processedFilePath, processed); var filename = processedFilePath.split(/[\\/]/).pop(); var testInfo = { name: filename, processed: fs.isFile(processedFilePath) ? processedFilePath : null, expected: fs.isFile(expectedFilePath) ? expectedFilePath : null, baseDirectory: app.runner.suite.baseDirectory }; if (!fs.isFile(testInfo.expected)) { fail("No expected output file found at " + testInfo.expected + "."); return; } var expected = fs.read(testInfo.expected); if (processed == expected) { pass(); } else { fail("Processed page contents does not equal expected file contents."); } });