Esempio n. 1
0
  describe('#destroyIfExpired', function () {
    var EXPIRED_SESSION_ID = 'expired_' + SESSION_ID;
    var EXPIRED_SESSION_FILE = path.join(SESSIONS_OPTIONS.path, EXPIRED_SESSION_ID + '.json');
    var expiredSession = clone(SESSION);
    expiredSession.__lastAccess = 0;

    var SESSION_FILE = path.join(SESSIONS_OPTIONS.path, SESSION_ID + '.json');
    var session = clone(SESSION);
    session.__lastAccess = new Date().getTime();

    before(function (done) {
      fs.emptyDir(SESSIONS_OPTIONS.path, function () {
        fs.writeJson(EXPIRED_SESSION_FILE, expiredSession, function () {
          fs.writeJson(SESSION_FILE, session, done);
        });
      });
    });

    after(function (done) {
      fs.remove(SESSIONS_OPTIONS.path, done);
    });

    it('should be succeed', function (done) {
      helpers.destroyIfExpired(SESSION_ID, SESSIONS_OPTIONS, function (err) {
        expect(err).to.not.exist;
        done();
      });
    });
  });
WorldBankIndicatorControlsPrototype.setAccessors = function(newAccessors) {
    var controls = this;

    // If there was no argument then use the defaults.
    if (!newAccessors) {
        controls.accessors = controls.defaultAccessors;
        controls.setControlTitles(controls.accessors);
        return;
    }

    // If the new accessors are the same as the current do nothing.
    if (Object.keys(newAccessors).every(function (key) {
        return controls.accessors[key] === newAccessors[key];
    })) {
        return;
    }

    // Else mix the supplied accessors with the current accessors
    _assign(controls.accessors, newAccessors);

    // Falling back to defaults for missing values.
    controls.accessors = _assign(_clone(controls.defaultAccessors), controls.accessors);

    // Set the titles on the input elements.
    controls.setControlTitles(controls.accessors);

    controls.emit('accessorsUpdated', _clone(controls.accessors));
};
Esempio n. 3
0
    before( function () {
        var optionsBase = clone( options );
        optionsBase.id = 1;
        optionsBase.port = 9501;
        optionsBase.logging = false;
        processBase = new Process( { options: optionsBase }, function () {} );

        var optionsFileLogging = clone( options );
        optionsFileLogging.id = 2;
        optionsFileLogging.port = 9502;
        optionsFileLogging.logging = {
            'Dares.log': 'info'
        };
        processFileLogging = new Process( { options: optionsFileLogging }, function () {} );



        var optionsDefaultLogging = clone( options );
        optionsDefaultLogging.id = 6;
        optionsDefaultLogging.port = 9506;
        processDefaultLogging = new Process( { options: optionsDefaultLogging }, function () {} );

        var optionsCustomConsoleLogging = clone( options );
        optionsCustomConsoleLogging.id = 7;
        optionsCustomConsoleLogging.port = 9507;
        optionsCustomConsoleLogging.logging = {
            console: 'silly'
        };
        processCustomConsoleLogging = new Process( { options: optionsCustomConsoleLogging }, function () {} );
    } );
Esempio n. 4
0
  beforeEach(function() {
    credentialsFixture = clone(require('../fixtures/credentials-valid'));
    deviceFixture = clone(require('../fixtures/device'));
    config = {
      credentials: credentialsFixture,
      device: deviceFixture,
      config: {
        trackingIdPrefix: 'spark-js-sdk',
        credentials: {
          oauth: {
            /* eslint camelcase: [0] */
            client_id: process.env.COMMON_IDENTITY_CLIENT_ID,
            client_secret: process.env.COMMON_IDENTITY_CLIENT_SECRET,
            redirect_uri: process.env.COMMON_IDENTITY_REDIRECT_URI,
            scope: 'webexsquare:get_conversation Identity:SCIM',
            service: process.env.COMMON_IDENTITY_SERVICE
          }
        },
        metrics: {
          enableMetrics: false
        }
      }
    };

    spark = new Spark(config);
  });
Esempio n. 5
0
describe('reap', function () {
  var SESSIONS_PATH = path.join(os.tmpdir(), 'sessions');
  var SESSION_ID = 'session_id';
  var SESSION = {
    cookie: {
      originalMaxAge: null,
      expires: null,
      httpOnly: true,
      path: '/'
    },
    views: 9,
    __lastAccess: 1430336255633
  };

  var NOOP_FN = function () {
  };
  var SESSIONS_OPTIONS = helpers.defaults({
    path: SESSIONS_PATH,
    logFn: NOOP_FN
  });

  var EXPIRED_SESSION_ID = 'expired_' + SESSION_ID;
  var EXPIRED_SESSION_FILE = path.join(SESSIONS_OPTIONS.path, EXPIRED_SESSION_ID + '.json');
  var expiredSession = clone(SESSION);
  expiredSession.__lastAccess = 0;

  var SESSION_FILE = path.join(SESSIONS_OPTIONS.path, SESSION_ID + '.json');
  var session = clone(SESSION);
  session.__lastAccess = new Date().getTime();

  beforeEach(function (done) {
    fs.emptyDir(SESSIONS_OPTIONS.path, function () {
      fs.writeJson(EXPIRED_SESSION_FILE, expiredSession, function () {
        fs.writeJson(SESSION_FILE, session, done);
      });
    });
  });

  afterEach(function (done) {
    fs.remove(SESSIONS_OPTIONS.path, done);
  });

  it('should removes stale session file', function (done) {
    helpers.reap(SESSIONS_OPTIONS, function (err) {
      expect(err).to.not.exist;
      done();
    });
  });

  //it('should removes stale session file using distinct process', function (done) {
  //  childProcess.execFile('./reap-worker.js', [SESSIONS_OPTIONS.path, SESSIONS_OPTIONS.ttl], {
  //    cwd: path.join(process.cwd(), 'lib')
  //  }, function (err, stdout, stderr) {
  //    expect(err).to.not.exist;
  //    done();
  //  });
  //});
});
Esempio n. 6
0
  return through.obj(function (file, enc, cb) {

    if (file.isStream()) {
      return cb(new gutil.PluginError('gulp-stylus: Streaming not supported'));
    }
    if (file.isNull()){
      return cb(null, file);
    }
    if (path.extname(file.path) !== '.styl'){
      return cb(null, file);
    }
    var opt = opts ? clone(opts) : {};
    opt.filename = file.path;

    // scope file to its own folder
    // if no paths given
    if (!opt.paths) {
      opt.paths = [];
    }
    opt.paths.push(path.dirname(file.path));

    stylus.render(file.contents.toString('utf8'), opt)
    .catch(function(err){
      cb(new gutil.PluginError('gulp-stylus', err));
    })
    .then(function(css){
      if(!css) return;
      file.path = rext(file.path, '.css');
      file.contents = css ? new Buffer(css) : null;
      cb(null, file);
    });
  });
Esempio n. 7
0
            cache.get(key, function (error, record) {
                if (record) {
                    return callback(error, deepCopy(record));
                }

                var list = callbackList[key] = callbackList[key] || [];
                list.push(callback);

                if (list.length > 1) { return; }

                try {
                    backup_object.reverse(ip, function (err, addresses) {
                        if (err) {
                            list.forEach(function (cb) { cb(err); });
                            delete callbackList[key];
                            return;
                        }
                        cache.set(key, addresses, function () {
                            list.forEach(function (cb) { cb(err, deepCopy(addresses)); });
                            delete callbackList[key];
                        });
                    });
                } catch (err) {
                    /*istanbul ignore next - doesn't throw in node 0.10*/
                    callback(err);
                }
            });
Esempio n. 8
0
      sigList = sigList.map(function(s) {
        var header = clone(s.header || {});
        var protect = s.protected ?
                      JSON.parse(base64url.decode(s.protected, "utf8")) :
                      {};
        header = merge(header, protect);
        var signature = base64url.decode(s.signature);

        // process "crit" first
        var crit = protect.crit;
        if (crit) {
          if (!Array.isArray(crit)) {
            return Promise.reject(new Error("Invalid 'crit' header"));
          }
          for (var idx = 0; crit.length > idx; idx++) {
            if (-1 === handlerKeys.indexOf(crit[idx])) {
              return Promise.reject(new Error(
                  "Critical extension is not supported: " + crit[idx]
              ));
            }
          }
        }
        protect = Object.keys(protect);

        return {
          protected: protect,
          aad: s.protected || "",
          header: header,
          signature: signature
        };
      });
Esempio n. 9
0
 Object.keys(loadedComponents).forEach(function (name) {
   var otherDeps = clone(loadedComponents[name])
   otherDeps.pop()
   if (otherDeps.indexOf(componentName) > -1 && deps.indexOf(name) > -1) {
     circularDependencies.push(componentName + ' and ' + name)
   }
 })
Esempio n. 10
0
module.exports = function(options, cb) {
  var opts = clone(options);
  opts.key = opts.key || 'version';

  var regex = opts.regex || new RegExp(
    '([\'|\"]?' + opts.key + '[\'|\"]?[ ]*:[ ]*[\'|\"]?)(\\d+\\.\\d+\\.\\d+(-' +
    '(?:[0-9A-Za-z-]+)\\.\\d+)?(-\\d+)?)[\\d||A-a|.|-]*([\'|\"]?)', 'i');

  if (opts.global) {
    regex = new RegExp(regex.source, 'gi');
  }

  var parsedOut;
  opts.str = opts.str.replace(regex, function(match, prefix, parsed, pre, nopre, suffix) {
    parsedOut = parsed;
    if (!semver.valid(parsed) && !opts.version) {
      return cb('Invalid semver ' + parsed);
    }
    opts.type = opts.type || 'patch';
    var version = opts.version || semver.inc(parsed, opts.type, opts.preid);
    opts.prev = parsed;
    opts.new = version;
    return prefix + version + (suffix || '');
  });

  if (!parsedOut) {
    return cb('Invalid semver: version key "' + opts.key + '" is not found in file');
  }

  return cb(null, opts);
};
Esempio n. 11
0
  async function invokeChain(chainArr, context) {
    if (!chainArr.length) return Promise.resolve(context);

    const chain = clone(chainArr);
    const link = chain.shift(); // Every thing in the chain will always be a function right?
    const { function: fnName, arguments: fnArgs } = link;
    const fnDef = getByAlias(functions, fnName);

    if (!fnDef) {
      return createError({ message: `Function ${fnName} could not be found.` });
    }

    try {
      // Resolve arguments before passing to function
      // resolveArgs returns an object because the arguments themselves might
      // actually have a 'then' function which would be treated as a promise
      const { resolvedArgs } = await resolveArgs(fnDef, context, fnArgs);
      const newContext = await invokeFunction(fnDef, context, resolvedArgs);

      // if something failed, just return the failure
      if (getType(newContext) === 'error') return newContext;

      // Continue re-invoking chain until it's empty
      return await invokeChain(chain, newContext);
    } catch (e) {
      // Everything that throws from a function will hit this
      // The interpreter should *never* fail. It should always return a `{type: error}` on failure
      e.message = `[${fnName}] > ${e.message}`;
      return createError(e);
    }
  }
Esempio n. 12
0
  components.forEach(function (component) {
    var componentDefinition = component()
      , componentName = Object.keys(componentDefinition)[0]
      , componentParts = componentDefinition[componentName]
      , initFunc = null
      , funcIndex
      , deps

    if (loadedComponents[componentName]) {
      throw new Error('Component with name "' + componentName + '" already loaded')
    }

    if (typeof componentParts === 'function') {
      componentParts = [ componentParts ]
    }
    funcIndex = componentParts.length - 1
    initFunc = componentParts[funcIndex]
    componentParts[funcIndex] = eachFn(initFunc)

    componentDefinition[componentName] = componentParts
    loadedComponents[componentName] = componentDefinition[componentName]

    deps = clone(componentParts)
    deps.pop()
    dependencies = dependencies.concat(deps)

    // identify circular dependencies
    Object.keys(loadedComponents).forEach(function (name) {
      var otherDeps = clone(loadedComponents[name])
      otherDeps.pop()
      if (otherDeps.indexOf(componentName) > -1 && deps.indexOf(name) > -1) {
        circularDependencies.push(componentName + ' and ' + name)
      }
    })
  })
Esempio n. 13
0
  loadModule(isRetry = false) {
    if (this.settings.globals_path) {
      try {
        super.loadModule();
      } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND' && !isRetry) {
          this.modulePath = path.join(Utils.getConfigFolder(this.argv), this.settings.globals_path);
          this.loadModule(true);

          return this;
        }

        err.detailedErr = err.name + ': ' + err.message;
        err.message = `Error reading external global file using "${this.settings.globals_path}"`;

        throw err;
      }

      if (this.settings.persist_globals) {
        Object.assign(this.settings.globals, this.module);
      } else {
        // if we already have globals, make a copy of them
        let existingGlobals = lodashClone(this.settings.globals, true);
        lodashMerge(existingGlobals, this.module);
        this.settings.globals = existingGlobals;
      }

    } else {
      this.__module = this.settings.globals;
    }

    return this;
  }
Esempio n. 14
0
    destroy: function (options) {
        options = options ? clone(options) : {};
        var model = this;
        var success = options.success;

        var destroy = function () {
            model.trigger('destroy', model, model.collection, options);
        };

        options.success = function (body, type, resp) {
            if (options.wait || model.isNew()) destroy();
            if (success) success(model, resp, options);
            if (!model.isNew()) model.trigger('sync', model, resp, options);
        };

        if (this.isNew()) {
            options.success();
            return false;
        }
        wrapError(this, options);

        var sync = this.sync('delete', this, options);
        if (!options.wait) destroy();
        return sync;
    },
Esempio n. 15
0
module.exports = function(config, mixins) {
  var vu = alias(clone(config));
  if (Array.isArray(mixins)) {
    vu.mixins = vu.mixins.concat(mixins);
  }
  return React.createClass(vu);
};
Esempio n. 16
0
    it( 'todo name', function ( done ) {
        var optionsNotAdded = clone( options );
        optionsNotAdded.id = 4;
        optionsNotAdded.port = 9504;
        optionsNotAdded.logging = false;
        var processNotAdded = new Process( {
                options: optionsNotAdded
            }, function () {
                processNotAdded.dataReplicationCoordinator._changeEpoch = function () {
                    var json = {
                        action: 'notAdded'
                    };
                    processNotAdded.tunnel.send( json, '127.0.0.1', 9505 );
                };

                var options5 = clone( options );
                options5.id = 5;
                options5.port = 9505;
                options5.logging = false;
                options5.alreadyRegisteredProcess = '127.0.0.1:9504';
                var process5 = new Process( {
                    options: options5
                }, function () {
                    expect( function () {
                        process5.stop( function ( err ) {
                            expect( err ).to.be.instanceof( Error );
                        } );
                    } ).to.not.throw( Error );

                    done();
                } );
            } );
    } );
Esempio n. 17
0
  async addFileAsync (doc: Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Uploading new file...')
    const stream = await this.other.createReadStreamAsync(doc)
    const [dirPath, name] = conversion.extractDirAndName(path)
    const dir = await this.remoteCozy.findDirectoryByPath(dirPath)

    // Emit events to track the upload progress
    let info = clone(doc)
    info.way = 'up'
    info.eventName = `transfer-up-${doc._id}`
    this.events.emit('transfer-started', info)
    stream.on('data', data => {
      this.events.emit(info.eventName, data)
    })
    stream.on('finish', () => {
      this.events.emit(info.eventName, {finished: true})
    })

    const created = await this.remoteCozy.createFile(stream, {
      name,
      dirID: dir._id,
      executable: doc.executable,
      contentType: doc.mime,
      lastModifiedDate: new Date(doc.updated_at)
    })

    doc.remote = {
      _id: created._id,
      _rev: created._rev
    }

    // TODO do we use the returned values somewhere?
    return conversion.createMetadata(created)
  }
Esempio n. 18
0
 before( function ( done ) {
     var optionsGoodStart = clone( options );
     optionsGoodStart.id = 8;
     optionsGoodStart.port = 9508;
     optionsGoodStart.logging = false;
     optionsGoodStart.alreadyRegisteredProcess = 'localhost:9501';
     processGoodStart = new Process( { options: optionsGoodStart }, done );
 } );
Esempio n. 19
0
  /**
   * Add a new Governor
   *
   * @name laws
   * @instance
   * @memberof Autocrat
   */
  function initGovernorLaws(governor, addLaw, advisors) {
    governor.laws.all = [];
    governor.laws(addLaw, advisors);

    // Get rid of the function. Make it a plain object.
    governor.laws = clone(governor.laws);
    return governor.laws.all;
  }
Esempio n. 20
0
 group.zones = this.zoneManager.getZones().map(function (zone) {
   zone = clone(zone)
   if (group.zones.indexOf(zone.name) > -1) {
     zone.enabled = true
   } else {
     zone.enabled = false
   }
   return zone
 })
Esempio n. 21
0
 it('generates trackingid with specified prefix and suffix', function() {
   var prefix = 'ITCLIENT';
   var suffix = 'imi:true';
   var newConfig = clone(config);
   newConfig.config.trackingIdPrefix = prefix;
   newConfig.config.trackingIdSuffix = suffix;
   spark = new Spark(newConfig);
   assert.isTrue(spark.trackingId.startsWith(prefix));
   assert.isTrue(spark.trackingId.endsWith(suffix));
 });
Esempio n. 22
0
 it('should creates new session file', function (done) {
   var session = clone(SESSION);
   session.__lastAccess = 0;
   helpers.set(SESSION_ID, session, SESSIONS_OPTIONS, function (err, json) {
     expect(err).to.not.exist;
     expect(json).to.have.property('__lastAccess');
     expect(json.__lastAccess).to.not.equal(SESSION.__lastAccess);
     done();
   });
 });
 this.filesSrc.forEach(function (filepath) {
   var options = clone(opts);
  
   options.file = filepath;
   options.body = grunt.file.read(filepath);
   mail(options, function () {
     count--;
     if (count < 1)  { return done(); }
   });
 });
Esempio n. 24
0
  setCurrentEnv() {
    this.moduleCopy = lodashClone(this.module, true);

    // select globals from the current environment
    if (this.currentEnv) {
      if (this.currentEnv && this.__module.hasOwnProperty(this.currentEnv)) {
        Object.assign(this.__module, this.module[this.currentEnv]);
      }
    }
  }
Esempio n. 25
0
  _makeSpark: function _makeSpark(user) {
    user.spark = new Spark({
      credentials: {
        authorization: user.token
      },
      config: clone(require('../fixtures/spark-config'))
    });

    return user.spark.authenticate();
  }
Esempio n. 26
0
 it( 'should false startup', function ( done ) {
     var optionsFalseStartup = clone( options );
     optionsFalseStartup.id = 3;
     optionsFalseStartup.port = 9503;
     optionsFalseStartup.logging = false;
     optionsFalseStartup.alreadyRegisteredProcess = '127.0.0.1:9876';
     processFalseStartup = new Process( { options: optionsFalseStartup }, function ( error ) {
         expect( error.error ).to.be.equal( 'timeout for registration exceeded' );
         done();
     } );
 } );
Esempio n. 27
0
      Utils.processAsyncQueue(workerCount, modulePaths, function(modulePath, index, next) {
        var outputLabel = Utils.getModuleKey(modulePath, self.settings.src_folders, modulePaths);
        var childOutput = self.childProcessOutput[outputLabel] = [];

        // arguments to the new child process, essentially running a single test suite
        var childArgs = args.slice();
        childArgs.push('--test', modulePath, '--test-worker');

        var settings = clone(self.settings);
        settings.output = settings.output && settings.detailed_output;

        var child = new ChildProcess(outputLabel, index, childOutput, settings, childArgs);
        child.setLabel(outputLabel);
        child.on('result', function(childResult) {
          switch (childResult.type) {
            case 'testsuite_finished':
              globalResults.modules[childResult.moduleKey] = childResult.results;
              if (childResult.errmessages.length) {
                globalResults.errmessages.concat(childResult.errmessages);
              }

              globalResults.passed += childResult.passed;
              globalResults.failed += childResult.failed;
              globalResults.errors += childResult.errors;
              globalResults.skipped += childResult.skipped;
              globalResults.tests += childResult.tests;

              self.printChildProcessOutput(childResult.itemKey);
              break;
            case 'testsuite_started':

              break;
          }

        });

        self.runningProcesses[child.itemKey] = child;
        self.runningProcesses[child.itemKey].run(availColors, function (output, exitCode) {
          if (exitCode > 0) {
            globalExitCode = exitCode;
          }
          remaining -=1;
          if (remaining > 0) {
            next();
          } else {

            if (!self.settings.live_output) {
              globalReporter.printTotalResults();
            }

            doneCallback(globalExitCode);
          }
        });
      });
Esempio n. 28
0
function registerClass(styleObj) {
  var styleId = generateValidCSSClassName(hashStyle(styleObj));

  if (global.__RCSS_0_registry[styleId] == null) {
    global.__RCSS_0_registry[styleId] = {
      className: styleId,
      style: styleObj
    };
  }

  return clone(global.__RCSS_0_registry[styleId]);
}
Esempio n. 29
0
          .then(function(bot) {
            var spark = new Spark({
              config: clone(require('../../fixtures/spark-config'))
            });

            return retry(function() {
              return spark.authenticate(bot);
            })
              .then(function() {
                return spark.bot.remove();
              });
          });
Esempio n. 30
0
 fetch: function (options) {
     options = options ? clone(options) : {};
     if (options.parse === void 0) options.parse = true;
     var model = this;
     var success = options.success;
     options.success = function (body, type, resp) {
         if (!model.set(model.parse(body, options), options)) return false;
         if (success) success(model, resp, options);
         model.trigger('sync', model, resp, options);
     };
     wrapError(this, options);
     return this.sync('read', this, options);
 },