<commit_before>const express = require('express');
const appexpress = module.exports = exports = express();
const mongoose = require('mongoose');

const authRoutes = require(__dirname + '/../routes/auth_routes');
const trailRoutes = require(__dirname + '/../routes/trail_routes');

appexpress.use('/api', authRoutes);
appexpress.use('/api', trailRoutes);

module.exports = exports = {
  server: appexpress,
  db: mongoose,
  dbconnect: process.env.MONGOLAB_URI || 'mongodb://localhost/localdbtest'
};
<commit_msg>remove LAB from MONGO<commit_after>const express = require('express');
const appexpress = module.exports = exports = express();
const mongoose = require('mongoose');

const authRoutes = require(__dirname + '/../routes/auth_routes');
const trailRoutes = require(__dirname + '/../routes/trail_routes');

appexpress.use('/api', authRoutes);
appexpress.use('/api', trailRoutes);

module.exports = exports = {
  server: appexpress,
  db: mongoose,
  dbconnect: process.env.MONGO_URI || 'mongodb://localhost/localdbtest'
};
<|endoftext|>


<commit_before>'use strict';

var exec = require('child-process-promise').exec;
var spawn = require('child_process').spawn;
var path = require('path');
var https = require('https');
var unzip = require('unzip');
var Promise = require('lie');
var fs = require('fs-extra-promise');
var url = require('url');
var FILE_NOT_FOUND = 'ENOENT';

// If this file exists in the thaliDontCheckIn directory then
// we will copy the Cordova plugin from a sibling Thali_CordovaPlugin
// project to this Cordova project.
var MAGIC_DIRECTORY_NAME_FOR_LOCAL_DEPLOYMENT = 'localdev';

// Unfortunately the obvious library, request-promise, doesn't handle streams
// well so it would take the multi-megabyte ZIP response file and turn it into
// an in-memory string. So we use this instead.
function httpRequestPromise(method, urlObject) {
  if (method !== 'GET' && method !== 'HEAD') {
    return Promise.reject(new Error('We only support GET or HEAD requests'));
  }

  return new Promise(function (resolve, reject) {
    var httpsRequestOptions = {
      host: urlObject.host,
      method: method,
      path: urlObject.path,
      keepAlive: true
    };

    var req = https.request(httpsRequestOptions, function (res) {
      if (res.statusCode !== 200) {
        reject(new Error('Did not get 200 for ' + urlObject.href +
          ', instead got ' + res.statusCode));
        return;
      }

      resolve(res);
    }).on('error', function (e) {
      reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
    });

    req.end();
  });
}

function getEtagFileLocation(depotName, branchName, directoryToInstallIn) {
  return path.join(directoryToInstallIn,
                   'etag-' + depotName + '-' + branchName);
}

function getEtagFromEtagFile(depotName, branchName, directoryToInstallIn) {
  var etagFileLocation =
    getEtagFileLocation(depotName, branchName, directoryToInstallIn);
  return fs.readFileAsync(etagFileLocation)
    .catch(function (err) {
      if (err.code !== FILE_NOT_FOUND) {
        return Promise.reject(err);
      } else {
        return Promise.resolve();
      }
    });
}

/**
 * This method is used to retrieve the release configuration data
 * stored in the releaseConfig.json
 *
 * @returns {Promise}
 */
function getReleaseConfig() {
  var configFileName = path.join(__dirname, '../', 'package.json');

  return fs.readFileAsync(configFileName, "utf-8")
    .then(function (data) {
      var conf;
      try {
        conf = JSON.parse(data);
        if (conf && conf.thaliInstall) {
          return conf.thaliInstall;
        }
        return Promise.reject("Configuration error!");
      }
      catch (err) {
        return Promise.reject(new Error(err));
      }
    });
}

function returnEtagFromResponse(httpResponse) {
  // The etag value is returned with quotes but when we set the header it adds
  // its own quotes so we need to strip those quotes here
  return httpResponse && httpResponse.headers && httpResponse.headers.etag &&
    httpResponse.headers.etag.substring(1,
                                        httpResponse.headers.etag.length - 1);
}

function writeToEtagFile(depotName, branchName, directoryToInstallIn,
                         httpResponse) {
  var etag = returnEtagFromResponse(httpResponse);

  if (etag == null) {
    return Promise.reject(
      new Error('Did not get ETag header, something is wrong because Github' +
        'always sends one!'));
  }

  var etagFileLocation =
    getEtagFileLocation(depotName, branchName, directoryToInstallIn);
  return fs.writeFileAsync(etagFileLocation, etag);
}

function getGitHubZipUrlObject(projectName, depotName, branchName) {
  return url.parse('https://codeload.github.com/' + projectName + '/' +
    depotName + '/zip/' + branchName);
}

/**
 * This method is a hack because I'm having trouble getting GitHub to respect
 * if-none-match headers. So instead I'm doing a HEAD request and manually
 * checking if the etags match.
 *
 * @param {string} projectName
 * @param {string} depotName
 * @param {string} branchName
 * @param {string} directoryToInstallIn
 * @returns {boolean}
 */
function doGitHubEtagsMatch(projectName, depotName, branchName,
                            directoryToInstallIn) {
  return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn)
    .then(function (etagFromFile) {
      if (!etagFromFile) {
        return false;
      }

      return httpRequestPromise('HEAD',
        getGitHubZipUrlObject(projectName, depotName, branchName))
        .then(function (res) {
          var etagFromHeadRequest = returnEtagFromResponse(res);
          return etagFromFile === etagFromHeadRequest;
        });
    });
}

function createUnzippedDirectoryPath(depotName, branchName,
                                     directoryToInstallIn) {
  return path.join(directoryToInstallIn, depotName + '-' + branchName);
}

function createGitHubZipResponse(depotName, branchName, directoryToInstallIn,
                                 directoryUpdated) {
  return {
    unzipedDirectory: createUnzippedDirectoryPath(depotName, branchName,
                                                  directoryToInstallIn),
    directoryUpdated: directoryUpdated
  };
}

function installGitHubZip(projectName, depotName, branchName,
                          directoryToInstallIn) {
  var gitHubZipUrlObject = getGitHubZipUrlObject(projectName, depotName,
                                                 branchName);

  return doGitHubEtagsMatch(projectName, depotName, branchName,
                            directoryToInstallIn)
    .then(function (doTheEtagsMatch) {
      if (doTheEtagsMatch) {
        return createGitHubZipResponse(depotName, branchName,
                                       directoryToInstallIn, false);
      }
      console.log('Starting to download Thali Cordova plugin from: ' +
                  gitHubZipUrlObject.href);
      return httpRequestPromise('GET', gitHubZipUrlObject)
        .then(function (res) {
          return new Promise(function (resolve, reject) {
            res.pipe(unzip.Extract({ path: directoryToInstallIn}))
              .on('close', function () {
                resolve();
              }).on('error', function (e) {
                reject(new Error('Could not extract zip file from ' +
                                 gitHubZipUrlObject.href + ', error was ' + e));
              });
          }).then(function () {
              return writeToEtagFile(depotName, branchName,
                                     directoryToInstallIn, res);
            }).then(function () {
              return createGitHubZipResponse(depotName, branchName,
                                             directoryToInstallIn, true);
            });
        });
    });
}

function uninstallPluginsIfNecessary(weAddedPluginsFile, appRootDirectory) {
  return fs.readFileAsync(weAddedPluginsFile).catch(function (err) {
    if (err) {
      if (err.code === FILE_NOT_FOUND) {
        return Promise.resolve(false);
      }
      return Promise.reject(err);
    }
    return Promise.resolve(true);
  }).then(function (doWeNeedToUninstall) {
    if (!doWeNeedToUninstall) {
      return Promise.resolve();
    }
    console.log('Trying to remove previously installed Thali Cordova plugin');
    var pluginRemoveCommand = 'cordova plugin remove org.thaliproject.p2p';
    return exec(pluginRemoveCommand, { cwd: appRootDirectory })
    .catch(function (err) {
      console.log('Ignoring a non-critical error: ' + err);
      // Resolve the promise even if plugin removal fails, because it is
      // possible that the user has removed the plugin outside of this install
      // script, but there is still the left-over file that says this script has
      // added the plugins.
      return Promise.resolve();
    });
  });
}

/**
 * This will copy the contents of a Thali_CordovaPlugin local depot to the right
 * directory in the current Cordova project so it will be installed. This is
 * used for local development only.
 *
 * @param {string} appRootDirectory
 * @param {string} thaliDontCheckIn
 * @param {string} depotName
 * @param {string} branchName
 * @returns {Promise<Object|Error>}
 */
function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
                                                    thaliDontCheckIn,
                                                    depotName,
                                                    branchName) {
  var targetDirectory = createUnzippedDirectoryPath(depotName, branchName,
                                                    thaliDontCheckIn);
  var sourceDirectory = path.join(appRootDirectory, '../Thali_CordovaPlugin');
  return new Promise(function (resolve, reject) {
    fs.remove(targetDirectory, function (err) {
      if (err) {
        reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' +
                         'failed with ' + err));
        return;
      }
      console.log('Copying files from ' + sourceDirectory + ' to ' +
                  targetDirectory);
      fs.copy(sourceDirectory, targetDirectory, function (err) {
        if (err) {
          reject(
            new Error('copyDevelopmentThaliCordovaPluginToProject failed with' +
                      err));
          return;
        }
        resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn,
                                        true));
      });
    });
  });
}

function doesMagicDirectoryNamedExist(thaliDontCheckIn) {
  var magicFileLocation = path.join(thaliDontCheckIn,
    MAGIC_DIRECTORY_NAME_FOR_LOCAL_DEPLOYMENT);
  return fs.existsSync(magicFileLocation);
}

function fetchAndInstallJxCoreCordovaPlugin(baseDir, jxCoreVersionNumber, jxCoreUrl) {
  return new Promise(function (resolve, reject) {
    console.log('Trying to install jxcore-cordova version: ' +
                jxCoreVersionNumber);
    var jxcBin =
      path.join(__dirname, 'node_modules', 'jxc', 'bin', 'jxc.bin.js');
    var jxcInstall =
      spawn('jx',
        [
          jxcBin, 'install', jxCoreVersionNumber,
          '--use-url', jxCoreUrl
        ],
        { cwd: baseDir }
      );
    jxcInstall.stdout.on('data', function (data) {
      console.log(data + '');
    });
    jxcInstall.stderr.on('data', function (data) {
      console.log(data + '');
    });
    jxcInstall.on('close', function (code) {
      if (code === 0) {
        resolve();
      } else {
        reject('jxc install exited with code: ' + code);
      }
    });
  });
}

module.exports = function (callback, appRootDirectory) {
  // Get the app root as an argument or from app/www/jxcore/node_modules/thali.
  // Passing as argument can be leveraged in local development and testing
  // scenarios.
  appRootDirectory = appRootDirectory ||
                     path.join(__dirname, '../../../../../');
  var thaliDontCheckIn = path.join(appRootDirectory, 'thaliDontCheckIn' );
  var appScriptsFolder =
    path.join(appRootDirectory, 'plugins/org.thaliproject.p2p/scripts');

  var thaliProjectName, thaliDepotName, thaliBranchName, btconnectorlib2;

  getReleaseConfig(thaliDontCheckIn)
    .then(function (conf) {

      thaliProjectName = conf.thali.projectName;
      thaliDepotName = conf.thali.depotName;
      thaliBranchName = conf.thali.branchName;
      btconnectorlib2 = conf.btconnectorlib2;

      return fetchAndInstallJxCoreCordovaPlugin(appRootDirectory, conf["jxcore-cordova"], conf["jxcore-cordova-url"]);
    })
    .then(function () {
      if (doesMagicDirectoryNamedExist(thaliDontCheckIn)) {
        return copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
                                                          thaliDontCheckIn,
                                                          thaliDepotName,
                                                          thaliBranchName);
      } else {
        return installGitHubZip(thaliProjectName, thaliDepotName,
                                thaliBranchName, thaliDontCheckIn);
      }
    })
    .then(function(thaliCordovaPluginUnZipResult) {
      // This step is used to prepare the gradle.properties file
      // containing the btconnectorlib2 version
      var projectDir = createUnzippedDirectoryPath(thaliDepotName, thaliBranchName, thaliDontCheckIn);
      var gradleFileName = path.join(projectDir, 'src', 'android', 'gradle.properties');

      return fs.writeFileAsync(gradleFileName,
        "btconnectorlib2Version=" + btconnectorlib2)
        .then(function() {
          return thaliCordovaPluginUnZipResult;
        });
    })
    .then(function (thaliCordovaPluginUnZipResult) {
      if (thaliCordovaPluginUnZipResult.directoryUpdated) {
        var weAddedPluginsFile = path.join(thaliDontCheckIn, 'weAddedPlugins');

        return uninstallPluginsIfNecessary(weAddedPluginsFile, appRootDirectory)
          .then(function () {
            console.log('Adding Thali Cordova plugin from: ' +
              thaliCordovaPluginUnZipResult.unzipedDirectory);

            return exec('cordova plugins add ' +
              thaliCordovaPluginUnZipResult.unzipedDirectory + ' -d',
                { cwd : appRootDirectory })
              .then(function (result) {
                if (result.stdout) {
                  console.log('Added Thali Cordova plugin successfully\n');
                  console.log(result.stdout);
                }

                if (result.stderr) {
                  console.log('Added Thali Cordova plugin with errors\n');
                  console.log(result.stderr);
                }

                return;
              })
              .catch(function (error) {
                  console.log('Failed adding Thali Cordova plugin\n');
                  console.log(error);
              });
          })
          .then(function () {
            return fs.writeFileAsync(weAddedPluginsFile, 'yes');
          });
      }
    })
    .then(function () {
      // Success
      callback();
    })
    .catch(function (error) {
      callback(error, null);
    });
};
<commit_msg>trigger CI build<commit_after>'use strict';

var exec = require('child-process-promise').exec;
var path = require('path');
var spawn = require('child_process').spawn;
var https = require('https');
var unzip = require('unzip');
var Promise = require('lie');
var fs = require('fs-extra-promise');
var url = require('url');
var FILE_NOT_FOUND = 'ENOENT';

// If this file exists in the thaliDontCheckIn directory then
// we will copy the Cordova plugin from a sibling Thali_CordovaPlugin
// project to this Cordova project.
var MAGIC_DIRECTORY_NAME_FOR_LOCAL_DEPLOYMENT = 'localdev';

// Unfortunately the obvious library, request-promise, doesn't handle streams
// well so it would take the multi-megabyte ZIP response file and turn it into
// an in-memory string. So we use this instead.
function httpRequestPromise(method, urlObject) {
  if (method !== 'GET' && method !== 'HEAD') {
    return Promise.reject(new Error('We only support GET or HEAD requests'));
  }

  return new Promise(function (resolve, reject) {
    var httpsRequestOptions = {
      host: urlObject.host,
      method: method,
      path: urlObject.path,
      keepAlive: true
    };

    var req = https.request(httpsRequestOptions, function (res) {
      if (res.statusCode !== 200) {
        reject(new Error('Did not get 200 for ' + urlObject.href +
          ', instead got ' + res.statusCode));
        return;
      }

      resolve(res);
    }).on('error', function (e) {
      reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
    });

    req.end();
  });
}

function getEtagFileLocation(depotName, branchName, directoryToInstallIn) {
  return path.join(directoryToInstallIn,
                   'etag-' + depotName + '-' + branchName);
}

function getEtagFromEtagFile(depotName, branchName, directoryToInstallIn) {
  var etagFileLocation =
    getEtagFileLocation(depotName, branchName, directoryToInstallIn);
  return fs.readFileAsync(etagFileLocation)
    .catch(function (err) {
      if (err.code !== FILE_NOT_FOUND) {
        return Promise.reject(err);
      } else {
        return Promise.resolve();
      }
    });
}

/**
 * This method is used to retrieve the release configuration data
 * stored in the releaseConfig.json
 *
 * @returns {Promise}
 */
function getReleaseConfig() {
  var configFileName = path.join(__dirname, '../', 'package.json');

  return fs.readFileAsync(configFileName, "utf-8")
    .then(function (data) {
      var conf;
      try {
        conf = JSON.parse(data);
        if (conf && conf.thaliInstall) {
          return conf.thaliInstall;
        }
        return Promise.reject("Configuration error!");
      }
      catch (err) {
        return Promise.reject(new Error(err));
      }
    });
}

function returnEtagFromResponse(httpResponse) {
  // The etag value is returned with quotes but when we set the header it adds
  // its own quotes so we need to strip those quotes here
  return httpResponse && httpResponse.headers && httpResponse.headers.etag &&
    httpResponse.headers.etag.substring(1,
                                        httpResponse.headers.etag.length - 1);
}

function writeToEtagFile(depotName, branchName, directoryToInstallIn,
                         httpResponse) {
  var etag = returnEtagFromResponse(httpResponse);

  if (etag == null) {
    return Promise.reject(
      new Error('Did not get ETag header, something is wrong because Github' +
        'always sends one!'));
  }

  var etagFileLocation =
    getEtagFileLocation(depotName, branchName, directoryToInstallIn);
  return fs.writeFileAsync(etagFileLocation, etag);
}

function getGitHubZipUrlObject(projectName, depotName, branchName) {
  return url.parse('https://codeload.github.com/' + projectName + '/' +
    depotName + '/zip/' + branchName);
}

/**
 * This method is a hack because I'm having trouble getting GitHub to respect
 * if-none-match headers. So instead I'm doing a HEAD request and manually
 * checking if the etags match.
 *
 * @param {string} projectName
 * @param {string} depotName
 * @param {string} branchName
 * @param {string} directoryToInstallIn
 * @returns {boolean}
 */
function doGitHubEtagsMatch(projectName, depotName, branchName,
                            directoryToInstallIn) {
  return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn)
    .then(function (etagFromFile) {
      if (!etagFromFile) {
        return false;
      }

      return httpRequestPromise('HEAD',
        getGitHubZipUrlObject(projectName, depotName, branchName))
        .then(function (res) {
          var etagFromHeadRequest = returnEtagFromResponse(res);
          return etagFromFile === etagFromHeadRequest;
        });
    });
}

function createUnzippedDirectoryPath(depotName, branchName,
                                     directoryToInstallIn) {
  return path.join(directoryToInstallIn, depotName + '-' + branchName);
}

function createGitHubZipResponse(depotName, branchName, directoryToInstallIn,
                                 directoryUpdated) {
  return {
    unzipedDirectory: createUnzippedDirectoryPath(depotName, branchName,
                                                  directoryToInstallIn),
    directoryUpdated: directoryUpdated
  };
}

function installGitHubZip(projectName, depotName, branchName,
                          directoryToInstallIn) {
  var gitHubZipUrlObject = getGitHubZipUrlObject(projectName, depotName,
                                                 branchName);

  return doGitHubEtagsMatch(projectName, depotName, branchName,
                            directoryToInstallIn)
    .then(function (doTheEtagsMatch) {
      if (doTheEtagsMatch) {
        return createGitHubZipResponse(depotName, branchName,
                                       directoryToInstallIn, false);
      }
      console.log('Starting to download Thali Cordova plugin from: ' +
                  gitHubZipUrlObject.href);
      return httpRequestPromise('GET', gitHubZipUrlObject)
        .then(function (res) {
          return new Promise(function (resolve, reject) {
            res.pipe(unzip.Extract({ path: directoryToInstallIn}))
              .on('close', function () {
                resolve();
              }).on('error', function (e) {
                reject(new Error('Could not extract zip file from ' +
                                 gitHubZipUrlObject.href + ', error was ' + e));
              });
          }).then(function () {
              return writeToEtagFile(depotName, branchName,
                                     directoryToInstallIn, res);
            }).then(function () {
              return createGitHubZipResponse(depotName, branchName,
                                             directoryToInstallIn, true);
            });
        });
    });
}

function uninstallPluginsIfNecessary(weAddedPluginsFile, appRootDirectory) {
  return fs.readFileAsync(weAddedPluginsFile).catch(function (err) {
    if (err) {
      if (err.code === FILE_NOT_FOUND) {
        return Promise.resolve(false);
      }
      return Promise.reject(err);
    }
    return Promise.resolve(true);
  }).then(function (doWeNeedToUninstall) {
    if (!doWeNeedToUninstall) {
      return Promise.resolve();
    }
    console.log('Trying to remove previously installed Thali Cordova plugin');
    var pluginRemoveCommand = 'cordova plugin remove org.thaliproject.p2p';
    return exec(pluginRemoveCommand, { cwd: appRootDirectory })
    .catch(function (err) {
      console.log('Ignoring a non-critical error: ' + err);
      // Resolve the promise even if plugin removal fails, because it is
      // possible that the user has removed the plugin outside of this install
      // script, but there is still the left-over file that says this script has
      // added the plugins.
      return Promise.resolve();
    });
  });
}

/**
 * This will copy the contents of a Thali_CordovaPlugin local depot to the right
 * directory in the current Cordova project so it will be installed. This is
 * used for local development only.
 *
 * @param {string} appRootDirectory
 * @param {string} thaliDontCheckIn
 * @param {string} depotName
 * @param {string} branchName
 * @returns {Promise<Object|Error>}
 */
function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
                                                    thaliDontCheckIn,
                                                    depotName,
                                                    branchName) {
  var targetDirectory = createUnzippedDirectoryPath(depotName, branchName,
                                                    thaliDontCheckIn);
  var sourceDirectory = path.join(appRootDirectory, '../Thali_CordovaPlugin');
  return new Promise(function (resolve, reject) {
    fs.remove(targetDirectory, function (err) {
      if (err) {
        reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' +
                         'failed with ' + err));
        return;
      }
      console.log('Copying files from ' + sourceDirectory + ' to ' +
                  targetDirectory);
      fs.copy(sourceDirectory, targetDirectory, function (err) {
        if (err) {
          reject(
            new Error('copyDevelopmentThaliCordovaPluginToProject failed with' +
                      err));
          return;
        }
        resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn,
                                        true));
      });
    });
  });
}

function doesMagicDirectoryNamedExist(thaliDontCheckIn) {
  var magicFileLocation = path.join(thaliDontCheckIn,
    MAGIC_DIRECTORY_NAME_FOR_LOCAL_DEPLOYMENT);
  return fs.existsSync(magicFileLocation);
}

function fetchAndInstallJxCoreCordovaPlugin(baseDir, jxCoreVersionNumber, jxCoreUrl) {
  return new Promise(function (resolve, reject) {
    console.log('Trying to install jxcore-cordova version: ' +
                jxCoreVersionNumber);
    var jxcBin =
      path.join(__dirname, 'node_modules', 'jxc', 'bin', 'jxc.bin.js');
    var jxcInstall =
      spawn('jx',
        [
          jxcBin, 'install', jxCoreVersionNumber,
          '--use-url', jxCoreUrl
        ],
        { cwd: baseDir }
      );
    jxcInstall.stdout.on('data', function (data) {
      console.log(data + '');
    });
    jxcInstall.stderr.on('data', function (data) {
      console.log(data + '');
    });
    jxcInstall.on('close', function (code) {
      if (code === 0) {
        resolve();
      } else {
        reject('jxc install exited with code: ' + code);
      }
    });
  });
}

module.exports = function (callback, appRootDirectory) {
  // Get the app root as an argument or from app/www/jxcore/node_modules/thali.
  // Passing as argument can be leveraged in local development and testing
  // scenarios.
  appRootDirectory = appRootDirectory ||
                     path.join(__dirname, '../../../../../');
  var thaliDontCheckIn = path.join(appRootDirectory, 'thaliDontCheckIn' );
  var appScriptsFolder =
    path.join(appRootDirectory, 'plugins/org.thaliproject.p2p/scripts');

  var thaliProjectName, thaliDepotName, thaliBranchName, btconnectorlib2;

  getReleaseConfig(thaliDontCheckIn)
    .then(function (conf) {

      thaliProjectName = conf.thali.projectName;
      thaliDepotName = conf.thali.depotName;
      thaliBranchName = conf.thali.branchName;
      btconnectorlib2 = conf.btconnectorlib2;

      return fetchAndInstallJxCoreCordovaPlugin(appRootDirectory, conf["jxcore-cordova"], conf["jxcore-cordova-url"]);
    })
    .then(function () {
      if (doesMagicDirectoryNamedExist(thaliDontCheckIn)) {
        return copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
                                                          thaliDontCheckIn,
                                                          thaliDepotName,
                                                          thaliBranchName);
      } else {
        return installGitHubZip(thaliProjectName, thaliDepotName,
                                thaliBranchName, thaliDontCheckIn);
      }
    })
    .then(function(thaliCordovaPluginUnZipResult) {
      // This step is used to prepare the gradle.properties file
      // containing the btconnectorlib2 version
      var projectDir = createUnzippedDirectoryPath(thaliDepotName, thaliBranchName, thaliDontCheckIn);
      var gradleFileName = path.join(projectDir, 'src', 'android', 'gradle.properties');

      return fs.writeFileAsync(gradleFileName,
        "btconnectorlib2Version=" + btconnectorlib2)
        .then(function() {
          return thaliCordovaPluginUnZipResult;
        });
    })
    .then(function (thaliCordovaPluginUnZipResult) {
      if (thaliCordovaPluginUnZipResult.directoryUpdated) {
        var weAddedPluginsFile = path.join(thaliDontCheckIn, 'weAddedPlugins');

        return uninstallPluginsIfNecessary(weAddedPluginsFile, appRootDirectory)
          .then(function () {
            console.log('Adding Thali Cordova plugin from: ' +
              thaliCordovaPluginUnZipResult.unzipedDirectory);

            return exec('cordova plugins add ' +
              thaliCordovaPluginUnZipResult.unzipedDirectory + ' -d',
                { cwd : appRootDirectory })
              .then(function (result) {
                if (result.stdout) {
                  console.log('Added Thali Cordova plugin successfully\n');
                  console.log(result.stdout);
                }

                if (result.stderr) {
                  console.log('Added Thali Cordova plugin with errors\n');
                  console.log(result.stderr);
                }

                return;
              })
              .catch(function (error) {
                  console.log('Failed adding Thali Cordova plugin\n');
                  console.log(error);
              });
          })
          .then(function () {
            return fs.writeFileAsync(weAddedPluginsFile, 'yes');
          });
      }
    })
    .then(function () {
      // Success
      callback();
    })
    .catch(function (error) {
      callback(error, null);
    });
};
<|endoftext|>


<commit_before>const assert = require('assert');
const Version = require('../lib');
const Sequelize = require('sequelize');
const cls = require('continuation-local-storage');
const env = process.env;

const namespace = cls.createNamespace('my-very-own-namespace');
Sequelize.useCLS(namespace);

const sequelize = new Sequelize(env.DB_TEST, env.DB_USER, env.DB_PWD, {
    logging: () => {},
    dialect: 'postgres',
    define: {
        timestamps: false,
    }
});

const TestModel = sequelize.define('test', {
    id: {
        type: Sequelize.BIGINT,
        autoIncrement: true,
        primaryKey: true,
    },
    name: {
        type: Sequelize.STRING,
    }
});

const VersionTestModel = new Version(TestModel);

before(done => {

    sequelize.sync({force: true}).then(() => done()).catch(err => done(err));

});

describe('sequelize-version', () => {

    it ('basic usage', done => {

        const teste = async() => {

            try{

                const testInstance = await TestModel.build({name: 'test'}).save();

                const versionInstance = await VersionTestModel.find({where : {
                    id: testInstance.id
                }});

                return assert.equal(versionInstance.id, testInstance.id);

            }catch(err){

                return err;
            }

        }

        teste().then(result => done(result)).catch(err => done(err));

    })

    it ('must support transaction with cls', done => {

        const ERR_MSG = 'ROLLBACK_CLS_TEST';

        const teste = async() => {

            try{

                await TestModel.destroy({truncate: true}),
                await VersionTestModel.destroy({truncate: true}),
                await sequelize.transaction(async() => {

                    console.log('executando')

                    return Promise.all([
                         TestModel.build({name: 'test transaction cls'}).save().then(() => Promise.reject(new Error(ERR_MSG))),
                    ]);

                }).catch(async err => {

                    if (err.message === ERR_MSG){
                        const versions = await VersionTestModel.findAll();
                        assert.equal(versions.length, 0);

                    }else{
                        assert.fail(err);
                    }

                });

            }catch(err){

                return err;

            }

        }

        teste().then(result => done(result)).catch(err => done(err));

    });

    it ('Must deal with custom options', () => {

        const schema = 'test2';
        const prefix = 'version';
        const suffix = 'log';

        const V2 = new Version(TestModel, {schema, prefix, suffix});

        assert.equal(V2.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V2.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V2.options.tableName));

    })

});<commit_msg>test travis<commit_after>const assert = require('assert');
const Version = require('../lib');
const Sequelize = require('sequelize');
const cls = require('continuation-local-storage');
const env = process.env;

const namespace = cls.createNamespace('my-very-own-namespace');
Sequelize.useCLS(namespace);

const sequelize = new Sequelize(env.DB_TEST, env.DB_USER, env.DB_PWD, {
    logging: () => {},
    dialect: 'postgres',
    define: {
        timestamps: false,
    }
});

const TestModel = sequelize.define('test', {
    id: {
        type: Sequelize.BIGINT,
        autoIncrement: true,
        primaryKey: true,
    },
    name: {
        type: Sequelize.STRING,
    }
});

const VersionTestModel = new Version(TestModel);

before(done => {

    sequelize.sync({force: true}).then(() => done()).catch(err => done(err));

});

describe('sequelize-version', () => {

    it ('basic usage', done => {

        const test = async() => {

            try{

                const testInstance = await TestModel.build({name: 'test'}).save();

                const versionInstance = await VersionTestModel.find({where : {
                    id: testInstance.id
                }});

                return assert.equal(versionInstance.id, testInstance.id);

            }catch(err){

                return err;
            }

        }

        test().then(result => done(result)).catch(err => done(err));

    })

    it ('must support transaction with cls', done => {

        const ERR_MSG = 'ROLLBACK_CLS_TEST';

        const test = async() => {

            try{

                await TestModel.destroy({truncate: true}),
                await VersionTestModel.destroy({truncate: true}),
                await sequelize.transaction(async() => {

                    return Promise.all([
                         TestModel.build({name: 'test transaction cls'}).save().then(() => Promise.reject(new Error(ERR_MSG))),
                    ]);

                }).catch(async err => {

                    if (err.message === ERR_MSG){
                        const versions = await VersionTestModel.findAll();
                        assert.equal(versions.length, 0);

                    }else{
                        assert.fail(err);
                    }

                });

            }catch(err){

                return err;

            }

        }

        test().then(result => done(result)).catch(err => done(err));

    });

    it ('Must support custom options', () => {

        const schema = 'test2';
        const prefix = 'version';
        const suffix = 'log';

        const V2 = new Version(TestModel, {schema, prefix, suffix});

        assert.equal(V2.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V2.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V2.options.tableName));

    })

});<|endoftext|>


<commit_before>define(['js/models', 'js/views'], function(Models, Views) {

    describe('The timer', function() {

        var clock;

        before(function () {
            clock = sinon.useFakeTimers();
        });

        after(function () {
            clock.restore();
        });

        it('should display 00:00 by default', function() {
            var view = new Views.TimerView();
            expect(view.render().$el.text()).to.be.equal('00:00');
        });

        it('should be updated as soon as the pomodoro starts', function() {
            var pomodoro = new Models.Pomodoro({duration: 10000});
            pomodoro.start();

            var view = new Views.TimerView();
            view.startRunning(pomodoro);

            expect(view.$el.text()).to.be.equal('00:10');
        });

        it('should be decremented every second', function() {
            var pomodoro = new Models.Pomodoro({duration: 1500000});
            pomodoro.start();

            var view = new Views.TimerView();
            view.startRunning(pomodoro);

            clock.tick(1000);
            expect(view.$el.text()).to.be.equal('24:59');

            clock.tick(1000);
            expect(view.$el.text()).to.be.equal('24:58');

            clock.tick(10000);
            expect(view.$el.text()).to.be.equal('24:48');
        });

        it('should display 00:00 when it stops running', function() {
            var pomodoro = new Models.Pomodoro({duration: 1500000});
            var view = new Views.TimerView();
            view.startRunning(pomodoro);
            view.stopRunning();
            expect(view.$el.text()).to.be.equal('00:00');
        });
    });
});
<commit_msg>Correct some tests<commit_after>define(['js/models', 'js/views'], function(Models, Views) {

    describe('The timer', function() {

        var clock;

        before(function () {
            clock = sinon.useFakeTimers();
        });

        after(function () {
            clock.restore();
        });

        it('should display 00:00 by default', function() {
            var view = new Views.TimerView();
            expect(view.render().$el.text()).to.be.equal('00:00');
        });

        it('should be updated shortly after the pomodoro starts', function() {
            var pomodoro = new Models.Pomodoro({duration: 10000});
            pomodoro.start();

            var view = new Views.TimerView();
            view.startRunning(pomodoro);

            clock.tick(500);

            expect(view.$el.text()).to.be.equal('00:10');
        });

        it('should be decremented every second', function() {
            var pomodoro = new Models.Pomodoro({duration: 1500000});
            pomodoro.start();

            var view = new Views.TimerView();
            view.startRunning(pomodoro);

            clock.tick(1500);
            expect(view.$el.text()).to.be.equal('24:59');

            clock.tick(1000);
            expect(view.$el.text()).to.be.equal('24:58');

            clock.tick(10000);
            expect(view.$el.text()).to.be.equal('24:48');
        });

        it('should display 00:00 when it stops running', function() {
            var pomodoro = new Models.Pomodoro({duration: 1500000});
            var view = new Views.TimerView();
            view.startRunning(pomodoro);
            view.stopRunning();
            expect(view.$el.text()).to.be.equal('00:00');
        });
    });
});
<|endoftext|>


<commit_before>describe('Unit: Logger', function () {
    var loggerService,
        loggerProvider,
        $log;

    beforeEach(module('angular-cc-logger'));

    /**
     * First mocked handler
     *
     * @param level
     * @param message
     */
    var test_1 = function(level, message){
        console.log('Created to check if test_1 runs properly');
    };

    /**
     * Second mocked handler
     *
     * @param level
     * @param message
     */
    var test_2 = function(level, message){
        console.info('Created to check if test_2 runs properly');
    };

    /**
     * Injecting and creating mocked service and provider objects
     */
    beforeEach(inject(['angular-cc-logger.Logger', 'angular-cc-logger.$logger', '$log', function (Logger, provider, log) {
        loggerService = Logger;
        loggerProvider = provider;
        $log = log;
    }]));

    /**
     * Tests
     */
    it('should be defined', shouldBeDefined);

    /**
     * Checking if mocked objects are defined
     */
    function shouldBeDefined(){
        expect(loggerService).toBeDefined();
        expect(loggerProvider).toBeDefined();
    }

    /**
     * Tests for Logger service
     */
    describe('testing each of Logger function', function(){

        /**
         * Filling handlers table with two mocked functions and start to spy on $log functions
         */
        beforeEach(function () {
            loggerProvider.pushHandler(test_1);
            loggerProvider.pushHandler(test_2);

            spyOn($log, 'error');
            spyOn($log, 'warn');
            spyOn($log, 'log');
            spyOn($log, 'info');

            spyOn(console, 'log');
            spyOn(console, 'info');
        });

        /**
         * Tests
         */
        it('should be defined (handler)', shouldBeDefinedHandler);
        it('should run logger with disabled debugger', shouldRunLoggerWithDisabledDebugger);
        it('should run logger error', shouldRunLoggerError);
        it('should run logger warning', shouldRunLoggerWarn);
        it('should run logger notice', shouldRunLoggerNotice);
        it('should run logger info', shouldRunLoggerInfo);

        /**
         * Checking if handlers are defined and if are functions
         */
        function shouldBeDefinedHandler(){
            for(var i in loggerProvider.handlers){
                expect(loggerProvider.handlers[i]).toBeDefined();
                expect(angular.isFunction(loggerProvider.handlers[i])).toBe(true);
            }
        }

        function shouldRunLoggerWithDisabledDebugger(){
            loggerProvider.debug = false;

            loggerService.error('error');
            expect(console.log).not.toHaveBeenCalled();

        }

        /**
         * Running logger.error function
         */
        function shouldRunLoggerError(){
            loggerService.error('error');
            expect($log.error).toHaveBeenCalled();
            expect($log.warn).not.toHaveBeenCalled();
            expect($log.log).not.toHaveBeenCalled();
            expect($log.info).not.toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.warn function
         */
        function shouldRunLoggerWarn(){
            loggerService.warn('warn');
            expect($log.error).not.toHaveBeenCalled();
            expect($log.warn).toHaveBeenCalled();
            expect($log.log).not.toHaveBeenCalled();
            expect($log.info).not.toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.notice function
         */
        function shouldRunLoggerNotice(){
            loggerService.notice('notice');
            expect($log.error).not.toHaveBeenCalled();
            expect($log.warn).not.toHaveBeenCalled();
            expect($log.log).toHaveBeenCalled();
            expect($log.info).not.toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.info function
         */
        function shouldRunLoggerInfo(){
            loggerService.info('info');
            expect($log.error).not.toHaveBeenCalled();
            expect($log.warn).not.toHaveBeenCalled();
            expect($log.log).not.toHaveBeenCalled();
            expect($log.info).toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }
    });
});

//beforeEach(module('angular-cc-logger'),function($provide) {
//    loggerServiceMocked = {};
//
//    loggerServiceMocked.error = function (message) {
//        var indicator = 0;
//        if (!loggerProvider.debug) {
//            return;
//        }
//
//        for (var handler in loggerProvider.handlers) {
//            loggerProvider.handlers[handler](250, message);
//            indicator++;
//        }
//        $log.error(message);
//        return indicator;
//    };
//
//    $provide.value('loggerService.error', loggerServiceMocked.error);
//});<commit_msg>tests<commit_after>describe('Unit: Logger', function () {
    var loggerService,
        loggerProvider,
        $log;

    beforeEach(module('angular-cc-logger'));

    /**
     * First mocked handler
     *
     * @param level
     * @param message
     */
    var test_1 = function(level, message){
        console.log('Created to check if test_1 runs properly');
    };

    /**
     * Second mocked handler
     *
     * @param level
     * @param message
     */
    var test_2 = function(level, message){
        console.info('Created to check if test_2 runs properly');
    };

    /**
     * Injecting and creating mocked service and provider objects
     */
    beforeEach(inject(['angular-cc-logger.Logger', 'angular-cc-logger.$logger', '$log', function (Logger, provider, log) {
        loggerService = Logger;
        loggerProvider = provider;
        $log = log;
    }]));

    /**
     * Tests
     */
    it('should be defined', shouldBeDefined);

    /**
     * Checking if mocked objects are defined
     */
    function shouldBeDefined(){
        expect(loggerService).toBeDefined();
        expect(loggerProvider).toBeDefined();
    }

    /**
     * Tests for Logger service
     */
    describe('testing each of Logger function', function(){

        /**
         * Filling handlers table with two mocked functions and start to spy on $log functions
         */
        beforeEach(function () {
            loggerProvider.pushHandler(test_1);
            loggerProvider.pushHandler(test_2);

            spyOn($log, 'error');
            spyOn($log, 'warn');
            spyOn($log, 'log');
            spyOn($log, 'info');

            spyOn(console, 'log');
            spyOn(console, 'info');
        });

        /**
         * Tests
         */
        it('should be defined (handler)', shouldBeDefinedHandler);
        it('should run logger with disabled debugger', shouldRunLoggerWithDisabledDebugger);
        it('should run logger error', shouldRunLoggerError);
        it('should run logger warning', shouldRunLoggerWarn);
        it('should run logger notice', shouldRunLoggerNotice);
        it('should run logger info', shouldRunLoggerInfo);

        /**
         * Checking if handlers are defined and if are functions
         */
        function shouldBeDefinedHandler(){
            for(var i in loggerProvider.handlers){
                expect(loggerProvider.handlers[i]).toBeDefined();
                expect(angular.isFunction(loggerProvider.handlers[i])).toBe(true);
            }
        }

        function shouldRunLoggerWithDisabledDebugger(){
            loggerProvider.debug = false;

            loggerService.error('error');
            expect(console.log).not.toHaveBeenCalled();

        }

        /**
         * Running logger.error function
         */
        function shouldRunLoggerError(){
            loggerService.error('error');
            expect($log.error).toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.warn function
         */
        function shouldRunLoggerWarn(){
            loggerService.warn('warn');
            expect($log.warn).toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.notice function
         */
        function shouldRunLoggerNotice(){
            loggerService.notice('notice');
            expect($log.log).toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }

        /**
         * Running logger.info function
         */
        function shouldRunLoggerInfo(){
            loggerService.info('info');
            expect($log.info).toHaveBeenCalled();

            expect(console.log).toHaveBeenCalled();
            expect(console.info).toHaveBeenCalled();
        }
    });
});

//beforeEach(module('angular-cc-logger'),function($provide) {
//    loggerServiceMocked = {};
//
//    loggerServiceMocked.error = function (message) {
//        var indicator = 0;
//        if (!loggerProvider.debug) {
//            return;
//        }
//
//        for (var handler in loggerProvider.handlers) {
//            loggerProvider.handlers[handler](250, message);
//            indicator++;
//        }
//        $log.error(message);
//        return indicator;
//    };
//
//    $provide.value('loggerService.error', loggerServiceMocked.error);
//});<|endoftext|>


<commit_before>'use strict'

const Test = require('tape')
const Mock = require('mock-fs')

const Punc = require('../')

/* MOCK FILE SYSTEM */
let aliceStub = new Buffer('-;alice,in.wonder\'land(-;-.,""')

Mock({ 'books': { 'alice.txt': aliceStub } })

/* TESTS */
Test('Punc: exists?', t => {
  t.plan(1)
  t.equal(typeof Punc, 'function', 'it exists')
})

Test('Punc: handles null filePath argument?', t => {
  t.plan(1)
  t.throws(_ => Punc(), 'error throws')
})

Test('Punc: returns a Promise?', t => {
  t.plan(2)
  let module = Punc('books/alice.txt')
  t.ok(module.then, 'is then-able')
  t.ok(module.catch, 'is catch-able')
})

Test('Punc: punctuation count', t => {
  t.plan(1)
  let aliceCheatSheet = { ';': 2
    , ':': 0
    , '\'': 1
    , '"': 2
    , ',': 2
    , '!': 0
    , '?': 0
    , '.': 2
    , '(': 1
    , ')': 0
    , '-': 3
  }

  Punc('books/alice.txt')
    .then(book => {
      t.ok(book.count, 'count property exists on returned object')
      for (let key in book.count) {

        if (!aliceCheatSheet.hasOwnProperty(key)) {
          return t.fail(`Key not found: ${key}`)
        }

        if (aliceCheatSheet[key] !== book.count[key]) {
          return t.fail(`Value mismatch.\n\
            Punctuation: ${key}\n\
            Expected: ${aliceCheatSheet[key]}.\n\
            Actual: ${book.count[key]}`)
        }
      }
    })
    .catch(err => t.fail(err))
})

Test('Punc: punctuation body', t => {
  t.plan(2)
  Punc('books/alice.txt')
    .then(book => {
      t.ok(book.body, 'body property exists on returned object')
      t.equals(book.body, '-;,.\'(-;-.,""')
    })
    .catch(err => t.fail(err))
})<commit_msg>adds word count tests<commit_after>'use strict'

const Test = require('tape')
const Mock = require('mock-fs')

const Punc = require('../')

/* MOCK FILE SYSTEM */
let aliceStub = new Buffer('-;alice,in.wonder\'land(-;-.,""')
let word_count_stub = new Buffer('one.\
  twotwo.\
  threethreethree.\
  fourfourfourfour.')

Mock({ 'books': { 'alice.txt': aliceStub
  , 'word_count.txt': word_count_stub
  }
})

/* TESTS */
Test('Punc: exists?', t => {
  t.plan(1)
  t.equal(typeof Punc, 'function', 'it exists')
})

Test('Punc: handles null filePath argument?', t => {
  t.plan(1)
  t.throws(_ => Punc(), 'error throws')
})

Test('Punc: returns a Promise?', t => {
  t.plan(2)
  let module = Punc('books/alice.txt')
  t.ok(module.then, 'is then-able')
  t.ok(module.catch, 'is catch-able')
})

Test('Punc: punctuation count', t => {
  t.plan(1)
  let aliceCheatSheet = { ';': 2
    , ':': 0
    , '\'': 1
    , '"': 2
    , ',': 2
    , '!': 0
    , '?': 0
    , '.': 2
    , '(': 1
    , ')': 0
    , '-': 3
  }

  Punc('books/alice.txt')
    .then(book => {
      t.ok(book.count, 'count property exists on returned object')
      for (let key in book.count) {

        if (!aliceCheatSheet.hasOwnProperty(key)) {
          return t.fail(`Key not found: ${key}`)
        }

        if (aliceCheatSheet[key] !== book.count[key]) {
          return t.fail(`Value mismatch.\n\
            Punctuation: ${key}\n\
            Expected: ${aliceCheatSheet[key]}.\n\
            Actual: ${book.count[key]}`)
        }
      }
    })
    .catch(err => t.fail(err))
})

Test('Punc: punctuation body', t => {
  t.plan(2)
  Punc('books/alice.txt')
    .then(book => {
      t.ok(book.body, 'body property exists on returned object')
      t.equals(book.body, '-;,.\'(-;-.,""')
    })
    .catch(err => t.fail(err))
})

Test('Punc: words per sentence', t => {
  t.plan(2)
  Punc('books/word_count.txt')
    .then(book => {
      t.ok(book.wordCount, 'wordCount property exists on returned object')
      t.equals(book.wordCount, '2.5')
    })
    .catch(err => t.fail(err))
})<|endoftext|>


<commit_before>//window = {};
<commit_msg>fix(test): active window<commit_after>window = {};
<|endoftext|>


<commit_before>var _ = require('underscore');
var Game = require('../game.js')

describe('multi-libs', function() {
  var playerList = [
    "Player1",
    "Player2",
    "Player3",
    "Player4"
  ];
  var gameId = "ANewGame";
  var currentGame;

  function createGame() {
    Game.addGame({ id: gameId, name: "some game" });
    currentGame = Game.getGame(gameId);
  };

  function joinCurrentGame(playerId) {
    Game.joinGame(currentGame, { id: playerId, name: playerId });
  };

  function playCard(playerId) {
    var player = _.findWhere(currentGame.players, { id: playerId });
    expect(player.isCzar).toBe(false);
    Game.selectCard(currentGame.id, playerId, player.cards[0]);
    currentGame = Game.getGame(gameId);
  };

  function allPlayersButCzarPlayCard() {
      _.map(playerList, function(p) {
          var player = _.findWhere(currentGame.players, { id: p });
          if(!player.isCzar) {
              playCard(p);
          }
      });
  };

  function getFirstNonCzar(game) {
      return _.find(currentGame.players, function(p) {
          return p.isCzar === false;
      })
  };

  function startGame() {
    createGame();
    _.map(playerList, function(p) {
      joinCurrentGame(p);
    });
    currentGame = Game.getGame(gameId);
  };

  beforeEach(Game.reset);

  describe('creating a game', function() {
    beforeEach(createGame);

    it('the game isn\'t considered started', function() {
      expect(currentGame.isStarted).toBe(false);
    });

    it('a deck is created', function() {
      expect(currentGame.deck.black.length).toBe(Game.getDeck().black.length);
      expect(currentGame.deck.white.length).toBe(Game.getDeck().white.length);
    });

    it('the game is listed for joining', function() {
      expect(Game.list()[0].id).toBe(gameId);
    });
  });

  describe('4 people join a game', function() {
    beforeEach(startGame);

    it('the game is started with', function() {
      expect(currentGame.isStarted).toBe(true);
    });

    it('the black card is selected for play', function() {
      expect(currentGame.currentBlackCard).toBeTruthy();
    });

    it('player one is selected as the Card Czar', function() {
      expect(currentGame.players[0].isCzar).toBe(true);
    });

    it('each player has 7 cards drawn', function() {
      expect(currentGame.players[0].cards.length).toBe(7);
      expect(currentGame.players[1].cards.length).toBe(7);
      expect(currentGame.players[2].cards.length).toBe(7);
      expect(currentGame.players[3].cards.length).toBe(7);
    });
  });

  describe('player leaves during the game', function() {
    beforeEach(startGame);

    it('should have 3 players when first player leaves', function() {
      expect(currentGame.players.length).toBe(4);
      Game.departGame(gameId, currentGame.players[0].id);
      expect(currentGame.players.length).toBe(3);
    });
  });

  describe('round', function() {
    beforeEach(startGame);

    describe('each player except the czar plays a card', function() {
      beforeEach(function() {
          allPlayersButCzarPlayCard();
      });

      it('the round is ready for scoring', function() {
        expect(currentGame.isReadyForScoring).toBe(true);
      });

      describe('card czar selects winner', function() {
        var cardId;

        beforeEach(function() {
          var playerToPick = getFirstNonCzar(currentGame);
          cardId = playerToPick.cards[0];
          Game.selectWinner(gameId, cardId);
          currentGame = Game.getGame(gameId);
        });

        it('sets the winning card for the round', function() {
          expect(currentGame.winningCardId).toBe(cardId);
        });

        it('the round is ready for review', function() {
          expect(currentGame.isReadyForReview).toBe(true);
        });

        it('player is given awesome points', function() {
          expect(currentGame.players[1].awesomePoints).toBe(1);
        });

        describe('everyone has reviewed the cards', function() {
          var whiteCardCount;
          var blackCardCount
          var blackCard;

          beforeEach(function() {
            whiteCardCount = currentGame.deck.white.length;
            blackCardCount = currentGame.deck.black.length;
            blackCard = currentGame.currentBlackCard;
            _.map(currentGame.players, function(p) {
              Game.readyForNextRound(gameId, p.id);
            });
            currentGame = Game.getGame(gameId);
          });

          it("the round is restarted with new czar", function() {
            expect(currentGame.isReadyForScoring).toBe(false);
            expect(currentGame.isReadyForReview).toBe(false);
            expect(currentGame.winningCardId).toBe(null);
            expect(currentGame.players[1].isCzar).toBe(true);
          });

          it("a new black card is selected", function() {
            expect(currentGame.deck.black.length).toBe(blackCardCount - 1);
            expect(currentGame.currentBlackCard).toNotBe(blackCard);
          });

          it("each player (except the czar) is given a new white card", function() {
            expect(currentGame.deck.white.length).toBe(whiteCardCount - 3);
            expect(currentGame.players[0].cards.length).toBe(7);
            expect(currentGame.players[1].cards.length).toBe(7);
            expect(currentGame.players[2].cards.length).toBe(7);
            expect(currentGame.players[3].cards.length).toBe(7);
          });
        });
      });
    });
  });

  describe('fullGame', function() {
      beforeEach(startGame);
      describe('play enough rounds to reach the pointsToWin', function() {

          beforeEach(function() {
              var maxScore = 0;
              while(maxScore < currentGame.pointsToWin) {
                  allPlayersButCzarPlayCard();
                  var playerToPick = getFirstNonCzar(currentGame);
                  var cardId = playerToPick.cards[0];
                  Game.selectWinner(gameId, cardId);
                  maxScore = _.max(currentGame.players, function(p) {
                      return p.awesomePoints;
                  }).awesomePoints;
                  if(maxScore < currentGame.pointsToWin){
                      //everyone ready for next round
                      _.map(currentGame.players, function(p) {
                          Game.readyForNextRound(gameId, p.id);
                      });
                  }
              }
          });

          it('game is over after last round is played', function() {
              expect(currentGame.isOver).toBe(true);
          });

          describe('all players ready after winning round', function() {
              beforeEach(function() {
                  _.map(currentGame.players, function(p) {
                      Game.readyForNextRound(gameId, p.id);
                  });
              });

              it('game isOver should be false and all player points should be zero', function() {
                  expect(currentGame.isOver).toBe(false);
                  expect(currentGame.isStarted).toBe(true);
                  _.map(currentGame.players, function(p) {
                      expect(p.awesomePoints).toBe(0);
                  })
              });
          });

      });
  });

});
<commit_msg>new tests<commit_after>var _ = require('underscore');
var Game = require('../game.js')

describe('multi-libs', function() {
  var playerList = [
    "Player1",
    "Player2",
    "Player3",
    "Player4"
  ];
  var gameId = "ANewGame";
  var currentGame;

  function createGame() {
    Game.addGame({ id: gameId, name: "some game" });
    currentGame = Game.getGame(gameId);
  };

  function joinCurrentGame(playerId) {
    Game.joinGame(currentGame, { id: playerId, name: playerId });
  };

  function playCard(playerId) {
    var player = _.findWhere(currentGame.players, { id: playerId });
    expect(player.isCzar).toBe(false);
    Game.selectCard(currentGame.id, playerId, player.cards[0]);
    currentGame = Game.getGame(gameId);
  };

  function allPlayersButCzarPlayCard() {
      _.map(playerList, function(p) {
          var player = _.findWhere(currentGame.players, { id: p });
          if(!player.isCzar) {
              playCard(p);
          }
      });
  };

  function getFirstNonCzar(game) {
      return _.find(currentGame.players, function(p) {
          return p.isCzar === false;
      })
  };

  function startGame() {
    createGame();
    _.map(playerList, function(p) {
      joinCurrentGame(p);
    });
    currentGame = Game.getGame(gameId);
  };

  beforeEach(Game.reset);

  describe('creating a game', function() {
    beforeEach(createGame);

    it('the game isn\'t considered started', function() {
      expect(currentGame.isStarted).toBe(false);
    });

    it('a deck is created', function() {
      expect(currentGame.deck.black.length).toBe(Game.getDeck().black.length);
      expect(currentGame.deck.white.length).toBe(Game.getDeck().white.length);
    });

    it('the game is listed for joining', function() {
      expect(Game.list()[0].id).toBe(gameId);
    });
  });

  describe('4 people join a game', function() {
    beforeEach(startGame);

    it('the game is started with', function() {
      expect(currentGame.isStarted).toBe(true);
    });

    it('the black card is selected for play', function() {
      expect(currentGame.currentBlackCard).toBeTruthy();
    });

    it('player one is selected as the Card Czar', function() {
      expect(currentGame.players[0].isCzar).toBe(true);
    });

    it('each player has 7 cards drawn', function() {
      expect(currentGame.players[0].cards.length).toBe(7);
      expect(currentGame.players[1].cards.length).toBe(7);
      expect(currentGame.players[2].cards.length).toBe(7);
      expect(currentGame.players[3].cards.length).toBe(7);
    });
  });

  describe('player leaves during the game', function() {
    beforeEach(startGame);

    it('should have 3 players when first player leaves', function() {
      expect(currentGame.players.length).toBe(4);
      Game.departGame(gameId, currentGame.players[0].id);
      expect(currentGame.players.length).toBe(3);
    });
  });

  describe('All four players leave the game', function() {
    beforeEach(startGame);

    it('should remove the current game from the array of gameList', function() {
      expect(currentGame.players.length).toBe(4);
      var AvailableGames = Game.listAll();
      expect(AvailableGames.length).toBe(1);
    //expect(Game.list()[0].id).toBe(gameId);
      //var thisGameIDIndex = AvailableGamesArray.indexOf(currentGame.gameId);

      //expect(currentGame.gameList.indexOf(currentGame.gameId)).toBe(0);
      Game.departGame(gameId, currentGame.players[3].id);
      Game.departGame(gameId, currentGame.players[2].id);
      Game.departGame(gameId, currentGame.players[1].id);
      Game.departGame(gameId, currentGame.players[0].id);
      var AvailableGames2 = Game.listAll();
      expect(AvailableGames2.length).toBe(0);
      //expect(Game.list()[0].id).toNotBe(gameId);
      //expect(currentGame.gameList.indexOf(currentGame.gameId)).toBe(-1);
    });
  });

  describe('round', function() {
    beforeEach(startGame);

    describe('each player except the czar plays a card', function() {
      beforeEach(function() {
          allPlayersButCzarPlayCard();
      });

      it('the round is ready for scoring', function() {
        expect(currentGame.isReadyForScoring).toBe(true);
      });

      describe('card czar selects winner', function() {
        var cardId;

        beforeEach(function() {
          var playerToPick = getFirstNonCzar(currentGame);
          cardId = playerToPick.cards[0];
          Game.selectWinner(gameId, cardId);
          currentGame = Game.getGame(gameId);
        });

        it('sets the winning card for the round', function() {
          expect(currentGame.winningCardId).toBe(cardId);
        });

        it('the round is ready for review', function() {
          expect(currentGame.isReadyForReview).toBe(true);
        });

        it('player is given awesome points', function() {
          expect(currentGame.players[1].awesomePoints).toBe(1);
        });

        describe('everyone has reviewed the cards', function() {
          var whiteCardCount;
          var blackCardCount
          var blackCard;

          beforeEach(function() {
            whiteCardCount = currentGame.deck.white.length;
            blackCardCount = currentGame.deck.black.length;
            blackCard = currentGame.currentBlackCard;
            _.map(currentGame.players, function(p) {
              Game.readyForNextRound(gameId, p.id);
            });
            currentGame = Game.getGame(gameId);
          });

          it("the round is restarted with new czar", function() {
            expect(currentGame.isReadyForScoring).toBe(false);
            expect(currentGame.isReadyForReview).toBe(false);
            expect(currentGame.winningCardId).toBe(null);
            expect(currentGame.players[1].isCzar).toBe(true);
          });

          it("a new black card is selected", function() {
            expect(currentGame.deck.black.length).toBe(blackCardCount - 1);
            expect(currentGame.currentBlackCard).toNotBe(blackCard);
          });

          it("each player (except the czar) is given a new white card", function() {
            expect(currentGame.deck.white.length).toBe(whiteCardCount - 3);
            expect(currentGame.players[0].cards.length).toBe(7);
            expect(currentGame.players[1].cards.length).toBe(7);
            expect(currentGame.players[2].cards.length).toBe(7);
            expect(currentGame.players[3].cards.length).toBe(7);
          });
        });
      });
    });
  });

  describe('fullGame', function() {
      beforeEach(startGame);
      describe('play enough rounds to reach the pointsToWin', function() {

          beforeEach(function() {
              var maxScore = 0;
              while(maxScore < currentGame.pointsToWin) {
                  allPlayersButCzarPlayCard();
                  var playerToPick = getFirstNonCzar(currentGame);
                  var cardId = playerToPick.cards[0];
                  Game.selectWinner(gameId, cardId);
                  maxScore = _.max(currentGame.players, function(p) {
                      return p.awesomePoints;
                  }).awesomePoints;
                  if(maxScore < currentGame.pointsToWin){
                      //everyone ready for next round
                      _.map(currentGame.players, function(p) {
                          Game.readyForNextRound(gameId, p.id);
                      });
                  }
              }
          });

          it('game is over after last round is played', function() {
              expect(currentGame.isOver).toBe(true);
          });

          describe('all players ready after winning round', function() {
              beforeEach(function() {
                  _.map(currentGame.players, function(p) {
                      Game.readyForNextRound(gameId, p.id);
                  });
              });

              it('game isOver should be false and all player points should be zero', function() {
                  expect(currentGame.isOver).toBe(false);
                  expect(currentGame.isStarted).toBe(true);
                  _.map(currentGame.players, function(p) {
                      expect(p.awesomePoints).toBe(0);
                  })
              });
          });

      });
  });

});
<|endoftext|>


<commit_before>// Karma configuration

var requirejsOptions = require('../js/config'),
    files = [];

for (var key in requirejsOptions.paths) {
  files.push({
    pattern: requirejsOptions.paths[key] + '.js',
    included: false
  });
}
files.push({pattern: 'tests/example-resource*', included: false});
files.push({pattern: 'tests/fakeserver*', included: false});
files.push({pattern: 'tests/**/*-test.js', included: false});
files.push('js/config.js');
files.push('tests/config.js');

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // frameworks to use
    frameworks: ['mocha', 'requirejs'],

    // list of files / patterns to load in the browser
    files: files,

    // list of files to exclude
    exclude: [
      // TODO: we need to fix this tests
      'tests/iframe-test.js',
      'tests/pattern-formunloadalert-test.js',
      'tests/pattern-preventdoublesubmit-test.js'
    ],

    preprocessors: {
      'js/**/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: dots || progress || growl
    reporters: ['dots', 'progress', 'coverage'],

    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    plugins: [
      'karma-mocha',
      'karma-coverage',
      'karma-requirejs',
      'karma-sauce-launcher',
      'karma-chrome-launcher',
      'karma-junit-reporter'
    ]
  });
}
<commit_msg>decreasing level of output<commit_after>// Karma configuration

var requirejsOptions = require('../js/config'),
    files = [];

for (var key in requirejsOptions.paths) {
  files.push({
    pattern: requirejsOptions.paths[key] + '.js',
    included: false
  });
}
files.push({pattern: 'tests/example-resource*', included: false});
files.push({pattern: 'tests/fakeserver*', included: false});
files.push({pattern: 'tests/**/*-test.js', included: false});
files.push('js/config.js');
files.push('tests/config.js');

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // frameworks to use
    frameworks: ['mocha', 'requirejs'],

    // list of files / patterns to load in the browser
    files: files,

    // list of files to exclude
    exclude: [
      // TODO: we need to fix this tests
      'tests/iframe-test.js',
      'tests/pattern-formunloadalert-test.js',
      'tests/pattern-preventdoublesubmit-test.js'
    ],

    preprocessors: {
      'js/**/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: dots || progress || growl
    reporters: ['dots', 'progress', 'coverage'],

    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    plugins: [
      'karma-mocha',
      'karma-coverage',
      'karma-requirejs',
      'karma-sauce-launcher',
      'karma-chrome-launcher',
      'karma-junit-reporter'
    ]
  });
}
<|endoftext|>


<commit_before>// @flow
import fs from 'fs';
import zlib from 'zlib';

import {expect} from 'chai';

import {scenarios, setupForRspec, setupForAva, Stage} from '../index';
import {
    computeScenarioFileName,
    GroupReport,
    ScenarioPart,
    ScenarioReport,
    Step,
} from '../src/reports';
import {generateJGivenReportDataFiles} from '../src/generateReport';

if (global.describe && global.it) {
    setupForRspec(describe, it);
} else {
    const test = require('ava');
    setupForAva(test);
}

class JGivenReportStage extends Stage {
    scenario: ScenarioReport;
    groupName = 'Group';
    scenarioName = 'Scenario';

    a_simple_jsgiven_report(): this {
        const groupReport = new GroupReport(this.groupName);
        const givenPart = new ScenarioPart('GIVEN', [
            new Step("given", [], true),
            new Step("some_eggs", [], false),
        ]);
        const whenPart = new ScenarioPart('WHEN', [
            new Step("when", [], true),
            new Step("i_break_the_eggs", [], false),
        ]);
        const thenPart = new ScenarioPart('THEN', [
            new Step("then", [], true),
            new Step("the_eggs_are_broken", [], false),
        ]);
        const scenario = new ScenarioReport(groupReport, this.scenarioName,
            [givenPart, whenPart, thenPart]);
        scenario.dumpToFile();
        return this;
    }

    the_jgiven_report_is_generated(): this {
        const scenarioFileName = computeScenarioFileName(this.groupName, this.scenarioName);
        generateJGivenReportDataFiles(fileName => fileName === scenarioFileName);
        return this;
    }

    the_data0_js_file_is_generated(): this {
        expect(fs.existsSync('./jGiven-report/data0.js')).to.be.true;
        return this;
    }

    zippedScenariosData: ?string = undefined;

    the_data0_js_file_can_be_executed(): this {
        const data0Content = fs.readFileSync('./jGiven-report/data0.js', 'utf-8');
        global.jgivenReport = {addZippedScenarios: data => this.zippedScenariosData = data};
        eval(data0Content);
        delete global.jgivenReport;
        return this;
    }

    it_has_called_the_jgivenReport_addZippedScenarios_method(): this {
        expect(this.zippedScenariosData).to.exist;
        return this;
    }

    the_zipped_scenarios_can_be_decoded(): this {
        if (this.zippedScenariosData) {
            const bufferZipped = new Buffer(this.zippedScenariosData, 'base64');
            const buffer = zlib.gunzipSync(bufferZipped);
            const json = buffer.toString('utf-8');
            const scenarios = JSON.parse(json);
            console.log(scenarios);
        } else {
            expect('zippedScenariosData should not be null').to.be.true;
        }
        return this;
    }
}

scenarios('JGiven report', JGivenReportStage, ({given, when, then}) => {
    return {
        a_simple_report_is_generated() {
            given().a_simple_jsgiven_report();

            when().the_jgiven_report_is_generated();

            then().the_data0_js_file_is_generated().and()
                .the_data0_js_file_can_be_executed().and()
                .it_has_called_the_jgivenReport_addZippedScenarios_method().and()
                .the_zipped_scenarios_can_be_decoded();
        },
    };
});
<commit_msg>Fix tests<commit_after>// @flow
import fs from 'fs';
import zlib from 'zlib';

import {expect} from 'chai';

import {scenarios, setupForRspec, setupForAva, Stage} from '../index';
import {
    computeScenarioFileName,
    GroupReport,
    ScenarioPart,
    ScenarioReport,
    Step,
} from '../src/reports';
import {generateJGivenReportDataFiles} from '../src/generateReport';

if (global.describe && global.it) {
    setupForRspec(describe, it);
} else {
    const test = require('ava');
    setupForAva(test);
}

class JGivenReportStage extends Stage {
    scenario: ScenarioReport;
    groupName = 'Group';
    scenarioName = 'Scenario';

    an_existing_jgiven_directory(): this {
        try {
            fs.mkdirSync('./jGiven-report');
        } catch (error) {
            if (error.code !== 'EEXIST') {
                throw error;
            } else {
                // do nothing
            }
        }

        return this;
    }

    a_simple_jsgiven_report(): this {
        const groupReport = new GroupReport(this.groupName);
        const givenPart = new ScenarioPart('GIVEN', [
            new Step("given", [], true),
            new Step("some_eggs", [], false),
        ]);
        const whenPart = new ScenarioPart('WHEN', [
            new Step("when", [], true),
            new Step("i_break_the_eggs", [], false),
        ]);
        const thenPart = new ScenarioPart('THEN', [
            new Step("then", [], true),
            new Step("the_eggs_are_broken", [], false),
        ]);
        const scenario = new ScenarioReport(groupReport, this.scenarioName,
            [givenPart, whenPart, thenPart]);
        scenario.dumpToFile();
        return this;
    }

    the_jgiven_report_is_generated(): this {
        const scenarioFileName = computeScenarioFileName(this.groupName, this.scenarioName);
        generateJGivenReportDataFiles(fileName => fileName === scenarioFileName);
        return this;
    }

    the_data0_js_file_is_generated(): this {
        expect(fs.existsSync('./jGiven-report/data0.js')).to.be.true;
        return this;
    }

    zippedScenariosData: ?string = undefined;

    the_data0_js_file_can_be_executed(): this {
        const data0Content = fs.readFileSync('./jGiven-report/data0.js', 'utf-8');
        global.jgivenReport = {addZippedScenarios: data => this.zippedScenariosData = data};
        eval(data0Content);
        delete global.jgivenReport;
        return this;
    }

    it_has_called_the_jgivenReport_addZippedScenarios_method(): this {
        expect(this.zippedScenariosData).to.exist;
        return this;
    }

    the_zipped_scenarios_can_be_decoded(): this {
        if (this.zippedScenariosData) {
            const bufferZipped = new Buffer(this.zippedScenariosData, 'base64');
            const buffer = zlib.gunzipSync(bufferZipped);
            const json = buffer.toString('utf-8');
            const scenarios = JSON.parse(json);
            console.log(scenarios);
        } else {
            expect('zippedScenariosData should not be null').to.be.true;
        }
        return this;
    }
}

scenarios('JGiven report', JGivenReportStage, ({given, when, then}) => {
    return {
        a_simple_report_is_generated() {
            given().an_existing_jgiven_directory().and()
                .a_simple_jsgiven_report();

            when().the_jgiven_report_is_generated();

            then().the_data0_js_file_is_generated().and()
                .the_data0_js_file_can_be_executed().and()
                .it_has_called_the_jgivenReport_addZippedScenarios_method().and()
                .the_zipped_scenarios_can_be_decoded();
        },
    };
});
<|endoftext|>


<commit_before>"use strict";function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}(function(a){var b=a.prototype,c=b.parseFromString;try{if(new a().parseFromString("","text/html"))return}catch(d){}b.parseFromString=function(d,e){if(/^\s*text\/html\s*(?:;|$)/i.test(e)){var f=document.implementation.createHTMLDocument("");return-1<d.toLowerCase().indexOf("<!doctype")?f.documentElement.innerHTML=d:f.body.innerHTML=d,f}return c.apply(this,arguments)}})(DOMParser);var PurifyHtmlStyles=function(){function a(b){_classCallCheck(this,a),this.xml=b}return a.prototype.parser=function(c){var d=null;if(window.DOMParser){var b=new DOMParser;d=b.parseFromString(c,"text/html")}else window.ActiveXObject&&(d=new ActiveXObject("Microsoft.XMLDOM"),d.async=!1,d.loadXML(c));return d},a.prototype.createKey=function(){var c=Math.random().toString(36).substr(2,6)+Math.random().toString(36).substr(2,4);return"css__"+c+"__class"},a.prototype.run=function(){var c=this.parser("

"),d=c.getElementById("purifyStyleMyStyler");d.innerHTML=this.xml;var e=c.createElement("style");e.type="text/css",e.setAttribute("data-css-purify-styler",Date.now()),e.appendChild(document.createTextNode(""));for(var f="",g=c.querySelectorAll("[style]"),h=0;h<g.length;h++){var j=g[h],k=j.getAttribute("style");if(k){var l=this.createKey();f+="."+l+"{"+k+"}\n";var m=j.className||"";j.className+=-1==m.indexOf(l)?l:""}j.removeAttribute("style")}return e.innerHTML=f,d.appendChild(e),d.innerHTML},a}();
<commit_msg>Update html-purify-styles.min.js<commit_after>"use strict";function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}(function(a){var b=a.prototype,c=b.parseFromString;try{if(new a().parseFromString("","text/html"))return}catch(d){}b.parseFromString=function(d,e){if(/^\s*text\/html\s*(?:;|$)/i.test(e)){var f=document.implementation.createHTMLDocument("");return-1<d.toLowerCase().indexOf("<!doctype")?f.documentElement.innerHTML=d:f.body.innerHTML=d,f}return c.apply(this,arguments)}})(DOMParser);var PurifyHtmlStyles=function(){function a(b){_classCallCheck(this,a),this.xml=b}return a.prototype.parser=function(c){var d=null;if(window.DOMParser){var b=new DOMParser;d=b.parseFromString(c,"text/html")}else window.ActiveXObject&&(d=new ActiveXObject("Microsoft.XMLDOM"),d.async=!1,d.loadXML(c));return d},a.prototype.createKey=function(){var c=Math.random().toString(36).substr(2,6);return"sty__"+c+"__cls"},a.prototype.groupStyleTagRules=function(c){for(var d={},e=[],g=0;g<c.length;g++)for(var h=c[g],l=h.sheet.cssRules||h.sheet.rules,m=0,n=l.length;m<n;m++){var o=l[m],p=o.selectorText,q=d[p],s=o.style.cssText;d[p]=q?q+s:s}for(var t in d)e.push(t);return{selectors:e,rules:d}},a.prototype.mergeStyles=function(c){for(var g,d=c.trim().split(";"),e={},f=0;f<d.length;f++)if(g=d[f].trim(),g){var h=g.split(":"),l=h[0].trim(),m=h[1].trim();e[l]=m}var n="";for(var o in e)n+=o+": "+e[o]+";";return n},a.prototype.run=function(){var c=this.parser("

"),d=c.getElementById("purifyStyleMyStyler");d.innerHTML=this.xml;for(var e=c.querySelectorAll("[data-css-purify-styler]"),f=Object.assign({},this.groupStyleTagRules(e)),g=f.selectors,h=f.rules,l=c.querySelectorAll("[style]"),m=0;m<l.length;m++){var n=l[m],o=n.getAttribute("style");if(o){var p=(n.className||"").trim(),q=("."+p.replace(/ /g," .")).split(" "),s="",t=q.some(function(C){var D=g.indexOf(C);return s=g[D],0<=D}),u=s?s:"."+this.createKey(),v=h[s]||"";h[u]=v?this.mergeStyles(v+o):o;var w=p?" ":"",x=u.replace(".","");n.className+=-1==p.indexOf(x)?w+x:""}n.removeAttribute("style")}var y="";for(var z in h){var A=h[z];y+=z+"{"+A+"}\n"}var B=c.createElement("style");return B.type="text/css",B.setAttribute("data-css-purify-styler",Date.now()),B.appendChild(document.createTextNode("")),B.innerHTML=y,Array.prototype.forEach.call(e,function(C){C.parentNode.removeChild(C)}),d.appendChild(B),d.innerHTML},a}();
<|endoftext|>


<commit_before>import { add, MatrixError } from '../source/matrix';
import assert from 'assert';

describe('matrix.add', () => {
    it('should perform matrix addition when given two matrices with the '
    + 'same dimensions', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given two matrices with different '
    + 'dimensions', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[1, 2], [3, 4], [5, 6]];
        assert.throws(() => add(a, b), MatrixError,
            'Matrices are not of the same dimensions.');
    });

    it('should perform scalar addition when given a matrix and a scalar '
    + 'value', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = 2;
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should perform scalar addition when given a scalar value and a '
    + 'matrix', () => {
        var a = 2;
        var b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', () => {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        assert.throws(() => add(a, b), MatrixError,
            'A given matrix is invalid.');
    });

    it('should throw MatrixError when not given any matrices', () => {
        var a = 2;
        var b = 3;
        assert.throws(() => add(a, b), MatrixError, 'No matrices given.');
    });

    it('should be integrated to Array.prototype', () => {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('add');
        assert.equal(expected, actual);
    });

    it('should add valid matrices through the Array.prototype '
    + 'property', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = a.add(b);
        assert.deepEqual(expected, actual);
    });
});
<commit_msg>test(coverage): achieve full test coverage for add method<commit_after>import { add, MatrixError } from '../source/matrix';
import assert from 'assert';

describe('matrix.add', () => {
    it('should perform matrix addition when given two matrices with the '
    + 'same dimensions', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given two matrices with different '
    + 'dimensions', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[1, 2], [3, 4], [5, 6]];
        assert.throws(() => add(a, b), MatrixError,
            'Matrices are not of the same dimensions.');
    });

    it('should perform scalar addition when given a matrix and a scalar '
    + 'value', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = 2;
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should perform scalar addition when given a scalar value and a '
    + 'matrix', () => {
        var a = 2;
        var b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', () => {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        assert.throws(() => add(a, b), MatrixError,
            'A given matrix is invalid.');

        b = 3;
        assert.throws(() => add(a, b), MatrixError,
            'A given matrix is invalid.');
    });

    it('should throw MatrixError when not given any matrices', () => {
        var a = 2;
        var b = 3;
        assert.throws(() => add(a, b), MatrixError, 'No matrices given.');
    });

    it('should be integrated to Array.prototype', () => {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('add');
        assert.equal(expected, actual);
    });

    it('should add valid matrices through the Array.prototype '
    + 'property', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = a.add(b);
        assert.deepEqual(expected, actual);
    });
});
<|endoftext|>


<commit_before>describe("Applait.Finder.prototype splitname function", function () {

    var finder = new Applait.Finder();
    var splitname = finder.splitname("/sdcard/DCIM/100MZLLA/1.jpg");

    it("it should have the basename of the file with extension ", function (){
        expect(splitname.name).toBe("1.jpg");
    });

    it("it should have path to the file's directory", function (){
        expect(splitname.path).toBe("/sdcard/DCIM/100MZLLA");
    });
});
<commit_msg>Fixes #4: Added tests for checkhidden method<commit_after>describe("Applait.Finder.prototype splitname function", function () {

    var finder = new Applait.Finder();
    var splitname = finder.splitname("/sdcard/DCIM/100MZLLA/1.jpg");

    it("it should have the basename of the file with extension ", function (){
        expect(splitname.name).toBe("1.jpg");
    });

    it("it should have path to the file's directory", function (){
        expect(splitname.path).toBe("/sdcard/DCIM/100MZLLA");
    });
});

describe("Applait.Finder.prototype.checkhidden method", function() {

    describe("when this.hidden is true", function () {

        var finder = new Applait.Finder({ hidden: true });

        it("should return true when file path has hidden elements.", function (){
            expect(finder.checkhidden("/sdcard/DCIM/100MZLLA/.1.jpg")).toBe(true);
            expect(finder.checkhidden("/sdcard/DCIM/.100MZLLA/.1.jpg")).toBe(true);
            expect(finder.checkhidden("/sdcard/DCIM/.100MZLLA/1.jpg")).toBe(true);
        });

        it("should return true when file path does not have hidden elements.", function (){
            expect(finder.checkhidden("/sdcard/DCIM/100MZLLA/1.jpg")).toBe(true);
        });

    });

    describe("when this.hidden is false", function () {

        var finder = new Applait.Finder({ hidden: false });

        it("should return true when file path does not have hidden elements.", function (){
            expect(finder.checkhidden("/sdcard/DCIM/100MZLLA/1.jpg")).toBe(true);
        });

        it("should return false when file path has hidden elements.", function (){
            expect(finder.checkhidden("/sdcard/DCIM/100MZLLA/.1.jpg")).toBe(false);
            expect(finder.checkhidden("/sdcard/DCIM/.100MZLLA/.1.jpg")).toBe(false);
            expect(finder.checkhidden("/sdcard/DCIM/.100MZLLA/1.jpg")).toBe(false);
        });

    });

});<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');

describe('Brackets mocha runner', function () {
    this.timeout(0);

    before("Before all hook", function (done) {
        console.info("before all");
        //throw new Error("whatever");
        done();
    });

    it('should start log', function (done) {
        console.info("Hello");
        done();
    });

    describe('Handle console output', function () {
        it('should not throw', function () {
            console.error(new Error("test1"));
            console.log('sgsdglknsldgnslkdgnlasgndl;asdgnlasdgnasldg0');
        });

        it('should return console log text', function () {
            console.info("test2");
            assert.equal('1', 1);
        });

        it('should return console log text', function () {
            console.info("test2");
            var foo = {
                "largestCities": [
                          "São Paulo",
                          "Buenos Aires",
                          "Rio de Janeiro",
                          "Lima",
                          "Bogotá"
                          ],
                "languages": [
                        "spanish",
                        "portuguese",
                        "english",
                        "dutch",
                        "french",
                        "quechua",
                        "guaraní",
                        "aimara",
                        "mapudungun"
                      ]
            };
            var bar = {
                "largestCities": [
                                  "São Paulo",
                                  "Buenos Aires",
                                  "Rio de Janeiro",
                                  "Lima",
                                  "Bogotá"
                                  ],
                "languages": [
                            "spanish",
                            "portuguese",
                            "inglés",
                            "dutch",
                            "french",
                            "quechua",
                            "guaraní",
                            "aimara",
                            "mapudungun"
                            ]
            };
            assert.deepEqual(foo, bar);
        });

        it('should return console log text 3', function () {
            assert.equal(true, false);
        });

        describe('Handle console output deeper', function () {
            it('should log something', function (done) {
                console.info("test3");
                assert.ok(true);
                setTimeout(done, 1000);
            });
        });

        after("after this describe hook", function () {
            console.info("after hook");
        });
    });

    describe('Handle console output1', function () {
        it('should return console log text', function () {
            console.info("pass");
        });
    });
});
<commit_msg>better descriptions for sample test<commit_after>'use strict';

var assert = require('assert');

describe('Brackets mocha runner', function () {
    this.timeout(0);

    before("Before all hook", function (done) {
        console.info("before all");
        //throw new Error("whatever");
        done();
    });

    it('should start log', function (done) {
        console.info("Hello");
        done();
    });

    describe('Handle console output', function () {
        it('should throw', function () {
            console.error(new Error("test#1"));
            console.log('sgsdglknsldgnslkdgnlasgndl;asdgnlasdgnasldg0');
        });

        it('should return console log text', function () {
            console.info("test#2");
            assert.equal('1', 1);
        });

        it('should compare two objects', function () {
            console.info("test#3");
            var foo = {
                "largestCities": [
                          "São Paulo",
                          "Buenos Aires",
                          "Rio de Janeiro",
                          "Lima",
                          "Bogotá"
                          ],
                "languages": [
                        "spanish",
                        "portuguese",
                        "english",
                        "dutch",
                        "french",
                        "quechua",
                        "guaraní",
                        "aimara",
                        "mapudungun"
                      ]
            };
            var bar = {
                "largestCities": [
                                  "São Paulo",
                                  "Buenos Aires",
                                  "Rio de Janeiro",
                                  "Lima",
                                  "Bogotá"
                                  ],
                "languages": [
                            "spanish",
                            "portuguese",
                            "inglés",
                            "dutch",
                            "french",
                            "quechua",
                            "guaraní",
                            "aimara",
                            "mapudungun"
                            ]
            };
            assert.deepEqual(foo, bar);
        });

        it('should compare true and false', function () {
            assert.equal(true, false);
        });

        describe('Handle console output deeper', function () {
            it('should delay test and pass', function (done) {
                console.info("test with delay");
                assert.ok(true);
                setTimeout(done, 1000);
            });
        });

        after("after this describe hook", function () {
            console.info("after hook");
        });
    });

    describe('Handle console output1', function () {
        it('should return console log text', function () {
            console.info("test pass");
        });
    });
});
<|endoftext|>