<commit_before>import assert from 'chai/chai'
import makeServiceGetters from '~/src/service-module/getters'
import makeServiceMutations from '~/src/service-module/mutations'
import makeServiceState from '~/src/service-module/state'

const options = {
  idField: '_id',
  autoRemove: false
}

const { find, list, current } = makeServiceGetters('todos', options)
const { addItems } = makeServiceMutations('todos', options)

describe('Service Module - Getters', function () {
  beforeEach(function () {
    const state = makeServiceState('todos', options)
    this.items = [
      { _id: 0, otherField: true, test: true },
      { _id: 1, otherField: true, test: true },
      {
        _id: 2,
        name: 'Marshall',
        otherField: true,
        test: true,
        movies: [
          { actors: [ 'Jerry the Mouse' ] }
        ]
      },
      {
        _id: 3,
        otherField: true,
        test: false,
        movies: [
          { actors: [ 'Tom Hanks', 'Tom Cruise', 'Tomcat' ] }
        ]
      }
    ]
    addItems(state, this.items)
    state.currentId = 0
    this.state = state
  })

  it('list', function () {
    const { state, items } = this
    const results = list(state)

    assert.deepEqual(results, items, 'the list was correct')
  })

  it('current with id 0', function () {
    const { state, items } = this
    const result = current(state)

    assert.deepEqual(result, items[0], 'current was correct')
  })

  it('find', function () {
    const { state, items } = this
    const params = { query: {} }
    const results = find(state)(params)

    assert.deepEqual(results.data, items, 'the list was correct')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with query', function () {
    const { state } = this
    const params = { query: { test: false } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')

    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with custom operator', function () {
    const { state } = this
    const params = { query: { test: false, $populateQuery: 'test' } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with paramsForServer option', function () {
    const { state } = this
    state.paramsForServer = [ '_$client' ]
    const params = { query: { test: false, _$client: 'test' } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with non-whitelisted custom operator fails', function () {
    const { state } = this
    const params = { query: { $client: 'test' } }
    let results = []
    try {
      results = find(state)(params)
    } catch (error) {
      assert(error)
    }
    assert(!results.length)
  })

  it('find with whitelisted custom operators', function () {
    const { state } = this
    state.whitelist = ['$regex', '$options']
    const query = {
      name: { $regex: 'marsh', $options: 'igm' }
    }
    const params = { query }
    let results = []
    try {
      results = find(state)(params)
    } catch (error) {
      assert(!error, 'should not have failed with whitelisted custom operator')
    }
    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find works with $elemMatch', function () {
    const { state } = this
    const query = {
      movies: {
        $elemMatch: { actors: 'Jerry the Mouse' }
      }
    }
    const params = { query }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with limit', function () {
    const { state } = this
    const params = { query: { $limit: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 0, 'the correct record was returned')
    assert(results.limit === 1, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with skip', function () {
    const { state } = this
    const params = { query: { $skip: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 3, 'the length was correct')
    assert(results.data[0]._id === 1, 'the correct record was returned')
    assert(results.data[1]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 1, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with limit and skip', function () {
    const { state } = this
    const params = { query: { $limit: 1, $skip: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 1, 'the correct record was returned')
    assert(results.limit === 1, 'limit was correct')
    assert(results.skip === 1, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with select', function () {
    const { state } = this
    const params = { query: { $select: ['otherField'] } }
    const results = find(state)(params)

    assert(results.data.length === 4, 'the length was correct')
    results.data.forEach(result => {
      assert(Object.keys(result).length === 1, 'only one field was returned')
      assert(result.otherField, 'the correct field was returned')
    })
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })
})
<commit_msg>remove white<commit_after>import assert from 'chai/chai'
import makeServiceGetters from '~/src/service-module/getters'
import makeServiceMutations from '~/src/service-module/mutations'
import makeServiceState from '~/src/service-module/state'

const options = {
  idField: '_id',
  autoRemove: false
}

const { find, list, current } = makeServiceGetters('todos', options)
const { addItems } = makeServiceMutations('todos', options)

describe('Service Module - Getters', function () {
  beforeEach(function () {
    const state = makeServiceState('todos', options)
    this.items = [
      { _id: 0, otherField: true, test: true },
      { _id: 1, otherField: true, test: true },
      {
        _id: 2,
        name: 'Marshall',
        otherField: true,
        test: true,
        movies: [
          { actors: [ 'Jerry the Mouse' ] }
        ]
      },
      {
        _id: 3,
        otherField: true,
        test: false,
        movies: [
          { actors: [ 'Tom Hanks', 'Tom Cruise', 'Tomcat' ] }
        ]
      }
    ]
    addItems(state, this.items)
    state.currentId = 0
    this.state = state
  })

  it('list', function () {
    const { state, items } = this
    const results = list(state)

    assert.deepEqual(results, items, 'the list was correct')
  })

  it('current with id 0', function () {
    const { state, items } = this
    const result = current(state)

    assert.deepEqual(result, items[0], 'current was correct')
  })

  it('find', function () {
    const { state, items } = this
    const params = { query: {} }
    const results = find(state)(params)

    assert.deepEqual(results.data, items, 'the list was correct')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with query', function () {
    const { state } = this
    const params = { query: { test: false } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with custom operator', function () {
    const { state } = this
    const params = { query: { test: false, $populateQuery: 'test' } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with paramsForServer option', function () {
    const { state } = this
    state.paramsForServer = [ '_$client' ]
    const params = { query: { test: false, _$client: 'test' } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 3, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with non-whitelisted custom operator fails', function () {
    const { state } = this
    const params = { query: { $client: 'test' } }
    let results = []
    try {
      results = find(state)(params)
    } catch (error) {
      assert(error)
    }
    assert(!results.length)
  })

  it('find with whitelisted custom operators', function () {
    const { state } = this
    state.whitelist = ['$regex', '$options']
    const query = {
      name: { $regex: 'marsh', $options: 'igm' }
    }
    const params = { query }
    let results = []
    try {
      results = find(state)(params)
    } catch (error) {
      assert(!error, 'should not have failed with whitelisted custom operator')
    }
    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find works with $elemMatch', function () {
    const { state } = this
    const query = {
      movies: {
        $elemMatch: { actors: 'Jerry the Mouse' }
      }
    }
    const params = { query }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 1, 'total was correct')
  })

  it('find with limit', function () {
    const { state } = this
    const params = { query: { $limit: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 0, 'the correct record was returned')
    assert(results.limit === 1, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with skip', function () {
    const { state } = this
    const params = { query: { $skip: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 3, 'the length was correct')
    assert(results.data[0]._id === 1, 'the correct record was returned')
    assert(results.data[1]._id === 2, 'the correct record was returned')
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 1, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with limit and skip', function () {
    const { state } = this
    const params = { query: { $limit: 1, $skip: 1 } }
    const results = find(state)(params)

    assert(results.data.length === 1, 'the length was correct')
    assert(results.data[0]._id === 1, 'the correct record was returned')
    assert(results.limit === 1, 'limit was correct')
    assert(results.skip === 1, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })

  it('find with select', function () {
    const { state } = this
    const params = { query: { $select: ['otherField'] } }
    const results = find(state)(params)

    assert(results.data.length === 4, 'the length was correct')
    results.data.forEach(result => {
      assert(Object.keys(result).length === 1, 'only one field was returned')
      assert(result.otherField, 'the correct field was returned')
    })
    assert(results.limit === 0, 'limit was correct')
    assert(results.skip === 0, 'skip was correct')
    assert(results.total === 4, 'total was correct')
  })
})
<|endoftext|>


<commit_before>var routerService = (function(myRoutes) {
	if( !myRoutes ) {
		return null;
	}

	var parseRouteForBackbone = function(myRoutes) {
		var routerObj = {};
		routerObj.routes = {};
		for( var i = 0, ii = myRoutes.length; i < ii; i += 1 ) {
			myRoutes[i].originalPath = myRoutes[i].Path;
			if( myRoutes[i].Path.search('<%') !== -1 ) {
				var tmpArr,
						tmpParam,
						re = /\<\%[\sa-zA-Z0-9]+\%\>/g;
				while( tmpArr = re.exec(myRoutes[i].Path) ) {
					tmpParam = tmpArr[0].replace(/\s+/g, '').slice(2, -2);
					myRoutes[i].Path = myRoutes[i].Path.slice(0, tmpArr.index) + ':' + tmpParam + myRoutes[i].Path.slice(tmpArr.index + tmpArr[0].length);
					re.lastIndex = tmpArr.index + tmpParam.length;
				}
			}
			routerObj.routes[myRoutes[i].Path.slice(1)] = myRoutes[i].Name; // remove first slash from myRoutes[i].Path for backbone
			routerObj[myRoutes[i].Name] = myFunc(myRoutes[i].Name, myRoutes[i].Action);
		}
		return routerObj;
	};

	var getLinkByName = function(name, originalPath) {
		var original = originalPath || 'yes';
		for( var i = 0, ii = myRoutes.length; i < ii; i += 1 )  {
			if( myRoutes[i].Name === name ) {
				if( original === 'yes' ) {
					return myRoutes[i].originalPath;
				} else {
					return myRoutes[i].Path;
				}
			}
		}
	};

	var myFunc = function(name, callback) {
		return function() {
			var params = Array.prototype.slice.call(arguments);
			new ScriptExecutor({getContext: function() {return 'No context';}}).executeScript(callback, { name: name, params: params });
		};
	};

	var routerObj = parseRouteForBackbone(myRoutes);

	var startRouter = function() {
		var Router = Backbone.Router.extend(routerObj);
		InfinniUI.AppRouter = new Router();

		Backbone.history = Backbone.history || new Backbone.History({});
		Backbone.history.start(InfinniUI.config.HistoryAPI);
	};

	return {
		getLinkByName: getLinkByName,
		startRouter: startRouter
	};
})(InfinniUI.config.Routes);

window.InfinniUI.RouterService = routerService;
<commit_msg>UI-2449: Доработать routerService #resolved<commit_after>var routerService = (function(myRoutes) {
	if( !myRoutes ) {
		return null;
	}

	var parseRouteForBackbone = function(myRoutes) {
		var routerObj = {};
		routerObj.routes = {};
		for( var i = 0, ii = myRoutes.length; i < ii; i += 1 ) {
			myRoutes[i].originalPath = myRoutes[i].Path;
			if( myRoutes[i].Path.search('<%') !== -1 ) {
				var tmpArr,
						tmpParam,
						re = /\<\%[\sa-zA-Z0-9]+\%\>/g;
				while( tmpArr = re.exec(myRoutes[i].Path) ) {
					tmpParam = tmpArr[0].replace(/\s+/g, '').slice(2, -2);
					myRoutes[i].Path = myRoutes[i].Path.slice(0, tmpArr.index) + ':' + tmpParam + myRoutes[i].Path.slice(tmpArr.index + tmpArr[0].length);
					re.lastIndex = tmpArr.index + tmpParam.length;
				}
			}
			routerObj.routes[myRoutes[i].Path.slice(1)] = myRoutes[i].Name; // remove first slash from myRoutes[i].Path for backbone
			routerObj[myRoutes[i].Name] = onRouteSelectHandler(myRoutes[i].Name, myRoutes[i].Action);
		}
		return routerObj;
	};

	var getLinkByName = function(name, originalPath) {
		var original = originalPath || 'yes';
		for( var i = 0, ii = myRoutes.length; i < ii; i += 1 )  {
			if( myRoutes[i].Name === name ) {
				if( original === 'yes' ) {
					return myRoutes[i].originalPath;
				} else {
					return myRoutes[i].Path;
				}
			}
		}
	};

	var onRouteSelectHandler = function(name, script) {
		return function() {
			var params = _.extend(Array.prototype.slice.call(arguments),
					{
						routeParams: routerService._params
					});

			new ScriptExecutor({getContext: function() {return routerService._context || "No context";}}).executeScript(script, { name: name, params: params });
		};
	};

	var routerObj = parseRouteForBackbone(myRoutes);

	var startRouter = function() {
		if( !InfinniUI.AppRouter ) {
			var Router = Backbone.Router.extend(routerObj);
			InfinniUI.AppRouter = new Router();

			Backbone.history = Backbone.history || new Backbone.History({});
			Backbone.history.start(InfinniUI.config.HistoryAPI);
		} else {
			console.log("Попытка повторно запустить routerService");
		}
	};

	var setContext = function(context) {
		this._context = context;
	};

	var setParams = function(params) {
		this._params = params;
	};

	var addParams = function(params) {
		this._params = _.extend( this._params||{} ,params);
	};

	var routerService = {
		getLinkByName: getLinkByName,
		startRouter: startRouter,
		setContext: setContext,
		setParams: setParams,
		addParams: addParams
	};

	return routerService;
})(InfinniUI.config.Routes);

window.InfinniUI.RouterService = routerService;
<|endoftext|>


<commit_before>/* @flow */

const autoBind = require('auto-bind')
const Promise = require('bluebird')
const fs = require('fs-extra')
const path = require('path')

const checksumer = require('../../../core/local/checksumer')
const { getPath } = require('../../../core/utils/path')

Promise.promisifyAll(fs) // FIXME: Isn't fs-extra already promisified?
Promise.promisifyAll(checksumer)

/*:: import type { PathObject } from '../../../core/utils/path' */

function posixifyPath (localPath /*: string */) /*: string */ {
  return localPath.split(path.sep).join(path.posix.sep)
}

// A directory in the context of which we want to perform many FS operations.
class ContextDir {
  /*::
  root: string
  */

  constructor (root /*: string */) {
    this.root = root
    autoBind(this)
  }

  abspath (target /*: string|PathObject */) /*: string */ {
    return path.join(this.root, getPath(target))
  }

  relpath (abspath /*: string */) /*: string */ {
    return posixifyPath(abspath.slice(this.root.length + path.sep.length))
  }

  async tree () /*: Promise<string[]> */ {
    const dirsToRead = [this.root]
    const relPaths = []

    while (true) {
      const dir = dirsToRead.shift()
      if (dir == null) break

      for (const name of await fs.readdirAsync(dir)) {
        const absPath = path.join(dir, name)
        const stat = await fs.statAsync(absPath)
        let relPath = this.relpath(absPath)

        if (stat.isDirectory()) {
          dirsToRead.push(absPath)
          relPath = relPath + path.posix.sep
        }

        relPaths.push(relPath)
      }
    }

    return relPaths
      .sort((a, b) => a.localeCompare(b))
      .filter(relPath => relPath !== '.system-tmp-cozy-drive/') // FIXME: hardcoded tmp dir name
  }

  existsSync (target /*: string|PathObject */) /*: bool */ {
    return fs.existsSync(this.abspath(target))
  }

  async ensureDir (target /*: string|PathObject */) {
    await fs.ensureDir(this.abspath(target))
  }

  async unlink (target /*: string|PathObject */) {
    await fs.unlinkAsync(this.abspath(target))
  }

  async rmdir (target /*: string|PathObject */) {
    await fs.rmdirSync(this.abspath(target))
  }

  async readFile (target /*: string|PathObject */) /*: Promise<string> */ {
    return fs.readFile(this.abspath(target), 'utf8')
  }

  async outputFile (target /*: string|PathObject */, data /*: string */) {
    return fs.outputFile(this.abspath(target), data)
  }

  async checksum (target /*: string|PathObject */) /*: Promise<string> */ {
    // $FlowFixMe
    return checksumer.computeChecksumAsync(this.abspath(target))
  }
}

module.exports = {
  ContextDir,
  posixifyPath
}
<commit_msg>test/support: ContextDir#readFile() accepts same options as fs<commit_after>/* @flow */

const autoBind = require('auto-bind')
const Promise = require('bluebird')
const fs = require('fs-extra')
const path = require('path')

const checksumer = require('../../../core/local/checksumer')
const { getPath } = require('../../../core/utils/path')

Promise.promisifyAll(fs) // FIXME: Isn't fs-extra already promisified?
Promise.promisifyAll(checksumer)

/*:: import type { PathObject } from '../../../core/utils/path' */

function posixifyPath (localPath /*: string */) /*: string */ {
  return localPath.split(path.sep).join(path.posix.sep)
}

// A directory in the context of which we want to perform many FS operations.
class ContextDir {
  /*::
  root: string
  */

  constructor (root /*: string */) {
    this.root = root
    autoBind(this)
  }

  abspath (target /*: string|PathObject */) /*: string */ {
    return path.join(this.root, getPath(target))
  }

  relpath (abspath /*: string */) /*: string */ {
    return posixifyPath(abspath.slice(this.root.length + path.sep.length))
  }

  async tree () /*: Promise<string[]> */ {
    const dirsToRead = [this.root]
    const relPaths = []

    while (true) {
      const dir = dirsToRead.shift()
      if (dir == null) break

      for (const name of await fs.readdirAsync(dir)) {
        const absPath = path.join(dir, name)
        const stat = await fs.statAsync(absPath)
        let relPath = this.relpath(absPath)

        if (stat.isDirectory()) {
          dirsToRead.push(absPath)
          relPath = relPath + path.posix.sep
        }

        relPaths.push(relPath)
      }
    }

    return relPaths
      .sort((a, b) => a.localeCompare(b))
      .filter(relPath => relPath !== '.system-tmp-cozy-drive/') // FIXME: hardcoded tmp dir name
  }

  existsSync (target /*: string|PathObject */) /*: bool */ {
    return fs.existsSync(this.abspath(target))
  }

  async ensureDir (target /*: string|PathObject */) {
    await fs.ensureDir(this.abspath(target))
  }

  async unlink (target /*: string|PathObject */) {
    await fs.unlinkAsync(this.abspath(target))
  }

  async rmdir (target /*: string|PathObject */) {
    await fs.rmdirSync(this.abspath(target))
  }

  async readFile (target /*: string|PathObject */, opts /*: * */ = 'utf8') /*: Promise<string> */ {
    return fs.readFile(this.abspath(target), opts)
  }

  async outputFile (target /*: string|PathObject */, data /*: string */) {
    return fs.outputFile(this.abspath(target), data)
  }

  async checksum (target /*: string|PathObject */) /*: Promise<string> */ {
    // $FlowFixMe
    return checksumer.computeChecksumAsync(this.abspath(target))
  }
}

module.exports = {
  ContextDir,
  posixifyPath
}
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
var fse = require('fs-extra');

const expectedFiles = {
    travis: [
        '.travis.yml'
    ],
    jenkins: [
        'Jenkinsfile'
    ],
    gitlab: [
        '.gitlab-ci.yml'
    ],
    circle : [
        'circle.yml'
    ]
};

describe('JHipster CI-CD Sub Generator', function () {
    describe('Gradle Angular1 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng1-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular1 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng1-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular2 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng2-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular2 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Maven Angular1 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng1-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });
    describe('Maven Angular1 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng1-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });
    describe('Maven Angular2 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });
    describe('Maven Angular2 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

});
<commit_msg>ci-cd: add tests<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
var fse = require('fs-extra');

const expectedFiles = {
    travis: [
        '.travis.yml'
    ],
    jenkins: [
        'Jenkinsfile'
    ],
    gitlab: [
        '.gitlab-ci.yml'
    ],
    circle : [
        'circle.yml'
    ]
};

describe('JHipster CI-CD Sub Generator', function () {
    describe('Gradle Angular1 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng1-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular1 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng1-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular2 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng2-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Gradle Angular2 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Maven Angular1 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng1-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Maven Angular1 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng1-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Maven Angular2 NPM', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-npm'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
    });

    describe('Maven Angular2 Yarn', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins',
                        'travis',
                        'gitlab',
                        'circle'
                    ],
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.travis);
            assert.file(expectedFiles.jenkins);
            assert.file(expectedFiles.gitlab);
            assert.file(expectedFiles.circle);
        });
        it('doesn\'t contain Docker, Sonar', function () {
            assert.noFileContent('Jenkinsfile', /docker/);
            assert.noFileContent('Jenkinsfile', /sonar/);
            assert.noFileContent('Jenkinsfile', /heroku/);
            assert.noFileContent('.gitlab-ci.yml', /image: openjdk/);
            assert.noFileContent('.gitlab-ci.yml', /heroku/);
            assert.noFileContent('circle.yml', /heroku/);
        });
    });

    describe('Jenkins', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'jenkins'
                    ],
                    jenkinsIntegrations: [
                        'docker',
                        'sonar',
                        'gitlab'
                    ],
                    heroku: [
                        'jenkins'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.jenkins);
            assert.noFile(expectedFiles.gitlab);
            assert.noFile(expectedFiles.travis);
            assert.noFile(expectedFiles.circle);
        });
        it('contains Docker, Sonar', function () {
            assert.fileContent('Jenkinsfile', /docker/);
            assert.fileContent('Jenkinsfile', /sonar/);
            assert.fileContent('Jenkinsfile', /heroku/);
        });
    });

    describe('GitLab CI', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'gitlab'
                    ],
                    gitlabUseDocker: true,
                    heroku: [
                        'gitlab'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.gitlab);
            assert.noFile(expectedFiles.jenkins);
            assert.noFile(expectedFiles.travis);
            assert.noFile(expectedFiles.circle);
        });
        it('contains image openjdk, heroku', function () {
            assert.fileContent('.gitlab-ci.yml', /image: openjdk/);
            assert.fileContent('.gitlab-ci.yml', /heroku/);
        });
    });

    describe('Circle CI', function () {
        beforeEach(function (done) {
            helpers
                .run(require.resolve('../generators/ci-cd'))
                .inTmpDir(function (dir) {
                    fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ng2-yarn'), dir);
                })
                .withOptions({skipChecks: true})
                .withPrompts({
                    pipelines: [
                        'circle'
                    ],
                    gitlabUseDocker: true,
                    heroku: [
                        'circle'
                    ]
                })
                .on('end', done);
        });
        it('creates expected files', function () {
            assert.file(expectedFiles.circle);
            assert.noFile(expectedFiles.jenkins);
            assert.noFile(expectedFiles.travis);
            assert.noFile(expectedFiles.gitlab);
        });
        it('contains image openjdk, heroku', function () {
            assert.fileContent('circle.yml', /heroku/);
        });
    });

});
<|endoftext|>


<commit_before>var assert = require("assert");
var state_machine = require("../../lib/state_machine");
var states = require("../../lib/states");
var dummy_api = require("../../lib/dummy_api");

function SingleStateIm(state) {
    this.state = state;
    this.states = new state_machine.StateCreator(state ? state.name : "start");
    this.api = new dummy_api.DummyApi();
    this.im = new state_machine.InteractionMachine(this.api, this.states);
    if (state) {
        this.states.add_state(state);
    }
}

describe("test InteractionMachine", function() {
    it("should be creatable", function() {
        var sim = new SingleStateIm();
        assert.ok(sim.im);
    });
    it("should implement switch_state", function() {
        var sim = new SingleStateIm(
            new states.FreeText("start", "next", "Foo"));
        var done = 0;
        sim.im.user = {};
        sim.im.config = {};
        var p = sim.im.switch_state("start");
        p.add_callback(function () {done += 1;});
        assert.equal(done, 1);
        assert.equal(sim.im.current_state, sim.state);
    });
    it("should throw an error on duplicate states", function() {
        var sim = new SingleStateIm(
            new states.FreeText("start", "next", "Foo"));
        assert.throws(
            function () {
                sim.states.add_state(
                    new states.FreeText("start", "next", "Duplicate"));
            },
            states.StateError);
    });
    it("should throw an error on switching to unknown states", function () {
        var sim = new SingleStateIm();
        sim.im.user = {};
        sim.im.config = {};
        assert.throws(
            function () {
                sim.im.switch_state("unknown");
            },
            states.StateError);
    });
    it('should generate an event after a config_read event', function() {
        var states = new state_machine.StateCreator("start");
        var store = {};
        states.on_config_read = function(event) {
            store.event = event;
        };
        assert.equal(store.config, undefined);
        states.on_event({event: 'config_read', config: {foo: 'bar'}});
        assert.equal(store.event.event, 'config_read');
        assert.equal(store.event.config.foo, 'bar');
    });
    it('should generate an event after a inbound_event event', function() {
        var states = new state_machine.StateCreator("start");
        var store = {};
        states.on_inbound_event = function(event) {
            store.event = event;
        };
        assert.equal(store.config, undefined);
        states.on_event({event: 'inbound_event'});
        assert.equal(store.event.event, 'inbound_event');
    });
});

describe("test State", function() {
    // TODO:
});

describe("test StateError", function() {
    it("should be creatable", function() {
        var se = new states.StateError("msg");
        assert.equal(se.message, "msg");
    });
});

describe("test ChoiceState", function() {
});

describe("test FreeText", function() {
});

describe("test EndState", function() {
});<commit_msg>testing event firing from on_inbound_message<commit_after>var assert = require("assert");
var state_machine = require("../../lib/state_machine");
var states = require("../../lib/states");
var dummy_api = require("../../lib/dummy_api");

function SingleStateIm(state) {
    this.state = state;
    this.states = new state_machine.StateCreator(state ? state.name : "start");
    this.api = new dummy_api.DummyApi();
    this.im = new state_machine.InteractionMachine(this.api, this.states);
    if (state) {
        this.states.add_state(state);
    }
}

describe("test InteractionMachine", function() {
    it("should be creatable", function() {
        var sim = new SingleStateIm();
        assert.ok(sim.im);
    });
    it("should implement switch_state", function() {
        var sim = new SingleStateIm(
            new states.FreeText("start", "next", "Foo"));
        var done = 0;
        sim.im.user = {};
        sim.im.config = {};
        var p = sim.im.switch_state("start");
        p.add_callback(function () {done += 1;});
        assert.equal(done, 1);
        assert.equal(sim.im.current_state, sim.state);
    });
    it("should throw an error on duplicate states", function() {
        var sim = new SingleStateIm(
            new states.FreeText("start", "next", "Foo"));
        assert.throws(
            function () {
                sim.states.add_state(
                    new states.FreeText("start", "next", "Duplicate"));
            },
            states.StateError);
    });
    it("should throw an error on switching to unknown states", function () {
        var sim = new SingleStateIm();
        sim.im.user = {};
        sim.im.config = {};
        assert.throws(
            function () {
                sim.im.switch_state("unknown");
            },
            states.StateError);
    });
    it('should generate an event after a config_read event', function() {
        var states = new state_machine.StateCreator("start");
        var store = {};
        states.on_config_read = function(event) {
            store.event = event;
        };
        assert.equal(store.config, undefined);
        states.on_event({event: 'config_read', config: {foo: 'bar'}});
        assert.equal(store.event.event, 'config_read');
        assert.equal(store.event.config.foo, 'bar');
    });
    it('should generate an event after a inbound_event event', function() {
        var states = new state_machine.StateCreator("start");
        var store = {};
        states.on_inbound_event = function(event) {
            store.event = event;
        };
        assert.equal(store.config, undefined);
        states.on_event({event: 'inbound_event'});
        assert.equal(store.event.event, 'inbound_event');
    });
    it('should fire a config_read event on_inbound_message', function() {
        var sim = new SingleStateIm(
            new states.FreeText("start", "start", "Foo"));
        var store = {};
        sim.states.on_config_read = function(event) {
            store.event = event;
        };
        sim.im.fetch_config_value = function(key, json, done) {
            assert.equal(key, 'config');
            assert.ok(json);
            done({'sample': 'config'});
        };
        sim.im.on_inbound_message({
            cmd: "inbound-message",
            msg: {
                from_addr: "from_addr",
                content: "content",
                message_id: "message_id",
                session_event: "continue"
            }
        });
        var config = store.event.data.config;
        assert.equal(config.sample, 'config');
    });
});

describe("test State", function() {
    // TODO:
});

describe("test StateError", function() {
    it("should be creatable", function() {
        var se = new states.StateError("msg");
        assert.equal(se.message, "msg");
    });
});

describe("test ChoiceState", function() {
});

describe("test FreeText", function() {
});

describe("test EndState", function() {
});<|endoftext|>


<commit_before>Webos.Process = function WProcess(options) {
	this.pid = options.pid;
	//var key = options.key;
	this.authorizations = options.authorizations;
	if (typeof options.args != 'undefined') { //Si les arguments ne sont pas vides
		this.args = options.args;
	}

	this._state = 0; // 0 -> ready; 1 -> running; 2 -> idle; 3 -> killed.
	this.main = new Function('args', options.fn);

	if (typeof this.pid != 'undefined') {
		Webos.Process.list[this.pid] = this;
	}

	Webos.Observable.call(this);
};
Webos.Process.prototype = {
	main: function() {},
	getPid: function() {
		return this.pid;
	},
	getAuthorizations: function() {
		return this.authorizations;
	},
	run: function() {
		if (this.state() != 'ready') {
			return;
		}

		var args = this.args;
		if (typeof args == 'undefined') {
			args = new Webos.Arguments();
		}

		this._state = 1;
		Webos.Process.stack.push(this);

		this.notify('start');
		Webos.Process.notify('start', {
			process: this
		});

		try {
			this.main(args);
		} catch(error) {
			Webos.Error.catchError(error);
		}

		Webos.Process.stack.pop();

		if (this.state() != 'killed') {
			this._state = 2;

			this.notify('idle');
			Webos.Process.notify('idle', {
				process: this
			});
		}
	},
	stop: function() {
		if (this.state() != 'running' && this.state() != 'idle') {
			return;
		}

		this._state = 3;

		this.notify('stop');
		Webos.Process.notify('stop', {
			process: this
		});

		delete Webos.Process.list[this.getPid()];
		delete this;
	},
	state: function() {
		var states = ['ready', 'running', 'idle', 'killed'];

		return states[this._state];
	},
	isRunning: function() {
		return (this._state == 1 || this._state == 2);
	},
	toString: function() {
		return '[WProcess #'+this.pid+']';
	}
};
Webos.inherit(Webos.Process, Webos.Observable);

Webos.Process.list = {};
Webos.Process.stack = [];
Webos.Process.get = function(pid) {
	return Webos.Process.list[pid];
};
Webos.Process.current = function() {
	return Webos.Process.stack[Webos.Process.stack.length - 1];
};

Webos.Observable.build(Webos.Process);

Webos.Authorizations = function WAuthorizations(authorizations) {
	this.authorizations = (authorizations) ? authorizations : [];

	this.can = function(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				return true;
			}
		}
		return false;
	};
	this.get = function() {
		return this.authorizations;
	};
	this.set = function(auth) {
		if (auth != this.authorizations) {
			this.authorizations = auth;
		}
	};
	this.add = function(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				return;
			}
		}

		this.authorizations.push(auth);
	};
	this.remove = function(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				delete this.authorizations[i];
			}
		}
	};
	this.model = function(value) {
		var compareArraysFn = function(a, b) {
			if (a.length != b.length) {
				return false;
			}

			for (var i = 0; i < a.length; i++) {
				if (a[i] != b[i]) {
					var found = false;
					for (var j = 0; j < b.length; j++) {
						if (a[i] == b[j]) {
							found = true;
						}
					}
					if (!found) {
						return false;
					}
				}
			}
			return true;
		};

		if (typeof value == 'undefined') { //GETTER
			for (var index in Webos.Authorizations.models) {
				if (compareArraysFn(Webos.Authorizations.models[index], this.authorizations)) {
					return index;
				}
			}
			return 'select';
		} else { //SETTER
			if (typeof Webos.Authorizations.models[value] == 'undefined') {
				return false;
			}

			if (compareArraysFn(Webos.Authorizations.models[value], this.authorizations)) {
				return true;
			}

			this.authorizations = Webos.Authorizations.models[value];

			return true;
		}
	};
};
Webos.Authorizations.all = ['file.user.read',
                       'file.user.write',
                       'file.home.read',
                       'file.home.write',
                       'file.system.read',
                       'file.system.write',
                       'user.read',
                       'user.edit',
                       'user.manage',
                       'package.read',
                       'package.write',
                       'package.checked.manage',
                       'package.unchecked.manage'];
Webos.Authorizations.models = {
	'user': ['file.user.read',
             'file.user.write',
             'package.read',
             'package.checked.manage'],
    'admin': Webos.Authorizations.all,
    'guest': ['file.user.read']
};<commit_msg>Named anonymous functions in /boot/lib/process.js.<commit_after>Webos.Process = function WProcess(options) {
	this.pid = options.pid;
	//var key = options.key;
	this.authorizations = options.authorizations;
	if (typeof options.args != 'undefined') { //Si les arguments ne sont pas vides
		this.args = options.args;
	}

	this._state = 0; // 0 -> ready; 1 -> running; 2 -> idle; 3 -> killed.
	this.main = new Function('args', options.fn);

	if (typeof this.pid != 'undefined') {
		Webos.Process.list[this.pid] = this;
	}

	Webos.Observable.call(this);
};
Webos.Process.prototype = {
	main: function $_WProcess_main() {},
	getPid: function $_WProcess_getPid() {
		return this.pid;
	},
	getAuthorizations: function $_WProcess_getAuthorizations() {
		return this.authorizations;
	},
	run: function $_WProcess_run() {
		if (this.state() != 'ready') {
			return;
		}

		var args = this.args;
		if (typeof args == 'undefined') {
			args = new Webos.Arguments();
		}

		this._state = 1;
		Webos.Process.stack.push(this);

		this.notify('start');
		Webos.Process.notify('start', {
			process: this
		});

		try {
			this.main(args);
		} catch(error) {
			Webos.Error.catchError(error);
		}

		Webos.Process.stack.pop();

		if (this.state() != 'killed') {
			this._state = 2;

			this.notify('idle');
			Webos.Process.notify('idle', {
				process: this
			});
		}
	},
	stop: function $_WProcess_stop() {
		if (this.state() != 'running' && this.state() != 'idle') {
			return;
		}

		this._state = 3;

		this.notify('stop');
		Webos.Process.notify('stop', {
			process: this
		});

		delete Webos.Process.list[this.getPid()];
		delete this;
	},
	state: function $_WProcess_state() {
		var states = ['ready', 'running', 'idle', 'killed'];

		return states[this._state];
	},
	isRunning: function $_WProcess_isRunning() {
		return (this._state == 1 || this._state == 2);
	},
	toString: function $_WProcess_toString() {
		return '[WProcess #'+this.pid+']';
	}
};
Webos.inherit(Webos.Process, Webos.Observable);

Webos.Process.list = {};
Webos.Process.stack = [];
Webos.Process.get = function $_WProcess_get(pid) {
	return Webos.Process.list[pid];
};
Webos.Process.current = function $_WProcess_current() {
	return Webos.Process.stack[Webos.Process.stack.length - 1];
};

Webos.Observable.build(Webos.Process);

Webos.Authorizations = function WAuthorizations(authorizations) {
	this.authorizations = authorizations || [];
};
Webos.Authorizations.prototype = {
	can: function $_WAuthorizations_can(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				return true;
			}
		}
		return false;
	},
	get: function $_WAuthorizations_get() {
		return this.authorizations;
	},
	set: function $_WAuthorizations_set(auth) {
		if (auth != this.authorizations) {
			this.authorizations = auth;
		}
	},
	add: function $_WAuthorizations_add(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				return;
			}
		}

		this.authorizations.push(auth);
	},
	remove: function $_WAuthorizations_remove(auth) {
		for (var i = 0; i < this.authorizations.length; i++) {
			if (this.authorizations[i] == auth) {
				delete this.authorizations[i];
			}
		}
	},
	model: function $_WAuthorizations_model(value) {
		var compareArraysFn = function(a, b) {
			if (a.length != b.length) {
				return false;
			}

			for (var i = 0; i < a.length; i++) {
				if (a[i] != b[i]) {
					var found = false;
					for (var j = 0; j < b.length; j++) {
						if (a[i] == b[j]) {
							found = true;
						}
					}
					if (!found) {
						return false;
					}
				}
			}
			return true;
		};

		if (typeof value == 'undefined') { //GETTER
			for (var index in Webos.Authorizations.models) {
				if (compareArraysFn(Webos.Authorizations.models[index], this.authorizations)) {
					return index;
				}
			}
			return 'select';
		} else { //SETTER
			if (typeof Webos.Authorizations.models[value] == 'undefined') {
				return false;
			}

			if (compareArraysFn(Webos.Authorizations.models[value], this.authorizations)) {
				return true;
			}

			this.authorizations = Webos.Authorizations.models[value];

			return true;
		}
	}
};

Webos.Authorizations.all = ['file.user.read',
                       'file.user.write',
                       'file.home.read',
                       'file.home.write',
                       'file.system.read',
                       'file.system.write',
                       'user.read',
                       'user.edit',
                       'user.manage',
                       'package.read',
                       'package.write',
                       'package.checked.manage',
                       'package.unchecked.manage'];
Webos.Authorizations.models = {
	'user': ['file.user.read',
             'file.user.write',
             'package.read',
             'package.checked.manage'],
    'admin': Webos.Authorizations.all,
    'guest': ['file.user.read']
};<|endoftext|>


<commit_before>/**
 * test-merge.js - tests the merge() function.
 */
exports['corridor.merge(objects)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: {},
      other: { b: 'hi' },
      expected: { b: 'hi' },
      reason: 'all keys should be added to empty objects'
    },{
      obj: { a: 'whut' },
      other: { b: 'hi' },
      expected: { a: 'whut', b: 'hi' },
      reason: 'missing keys should be added to non-empty objects'
    },{
      obj: { "person": { "name": "Bob" } },
      other: { "person": { "email": "bob@company.com" } },
      expected: { "person": { "name": "Bob", "email": "bob@company.com" } },
      reason: 'nested objects should safely merge'
    },{
      obj: { "person": { "name": "Bob" } },
      other: { "person": { "name": "Alice" } },
      expected: { "person": { "name": "Alice" } },
      reason: 'nested conflicting objects should have their keys take precidence'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other);
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

exports['corridor.merge(arrays)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: ['a'],
      other: ['b'],
      expected: ['a', 'b'],
      reason: 'arrays of primitives should concatenate'
    },{
      obj: [{a: 'hi'}],
      other: [{a: 'there'}],
      expected: [{a: 'hi'}, {a: 'there'}],
      reason: 'arrays of conflicting objects should concatenate'
    },{
      obj: [{a: 'hi'}],
      other: [{b: 'there'}],
      expected: [{a: 'hi', b: 'there'}],
      reason: 'arrays of non-conflicting objects should merge'
    },{
      obj: {list: ['hi']},
      other: {list: ['there']},
      expected: {list: ['hi','there']},
      reason: 'nested arrays of primitives should concatenate'
    },{
      obj: {list: ['hi'], foo: 7},
      other: {foo: 8, list: ['there']},
      expected: {list: ['hi','there'], foo: 8},
      reason: 'primitves should overwrite each other while arrays concatenate'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other);
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

<commit_msg>adding merge tests for explicit concat and extend mode<commit_after>/**
 * test-merge.js - tests the merge() function.
 */
exports['corridor.merge(objects)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: {},
      other: { b: 'hi' },
      expected: { b: 'hi' },
      reason: 'all keys should be added to empty objects'
    },{
      obj: { a: 'whut' },
      other: { b: 'hi' },
      expected: { a: 'whut', b: 'hi' },
      reason: 'missing keys should be added to non-empty objects'
    },{
      obj: { "person": { "name": "Bob" } },
      other: { "person": { "email": "bob@company.com" } },
      expected: { "person": { "name": "Bob", "email": "bob@company.com" } },
      reason: 'nested objects should safely merge'
    },{
      obj: { "person": { "name": "Bob" } },
      other: { "person": { "name": "Alice" } },
      expected: { "person": { "name": "Alice" } },
      reason: 'nested conflicting objects should have their keys take precidence'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other);
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

exports['corridor.merge(arrays)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: ['a'],
      other: ['b'],
      expected: ['a', 'b'],
      reason: 'arrays of primitives should concatenate'
    },{
      obj: [{a: 'hi'}],
      other: [{a: 'there'}],
      expected: [{a: 'hi'}, {a: 'there'}],
      reason: 'arrays of conflicting objects should concatenate'
    },{
      obj: [{a: 'hi'}],
      other: [{b: 'there'}],
      expected: [{a: 'hi', b: 'there'}],
      reason: 'arrays of non-conflicting objects should merge'
    },{
      obj: {list: ['hi']},
      other: {list: ['there']},
      expected: {list: ['hi','there']},
      reason: 'nested arrays of primitives should concatenate'
    },{
      obj: {list: ['hi'], foo: 7},
      other: {foo: 8, list: ['there']},
      expected: {list: ['hi','there'], foo: 8},
      reason: 'primitves should overwrite each other while arrays concatenate'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other);
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

exports['corridor.merge(concat)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: [{a: 'hi'}],
      other: [{b: 'there'}],
      expected: [{a: 'hi'}, {b: 'there'}],
      reason: 'arrays of non-conflicting objects should concatenate in concat mode'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other, {merge:'concat'});
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

exports['corridor.merge(extend)'] = function(test) {

  var

    corridor = require('../src/corridor.js'),

    suite = [{
      obj: [{a: 'hi'}],
      other: [{b: 'there'}],
      expected: [{a: 'hi', b: 'there'}],
      reason: 'arrays of non-conflicting objects should concatenate in extend mode'
    },{
      obj: [{a: 'hi'}, {b: 'sneak attack!'}],
      other: [{b: 'there'}],
      expected: [{a: 'hi', b: 'there'}, {b: 'sneak attack!'}],
      reason: 'arrays of objects should merge in extend mode'
    }];

  test.expect(suite.length);

  for (var i = 0, ii = suite.length; i < ii; i++) {
    (function(data){
      var actual = corridor.merge(data.obj, data.other, {merge:'extend'});
      test.deepEqual(actual, data.expected, data.reason);
    })(suite[i]);
  }

  test.done();

};

<|endoftext|>


<commit_before>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * fiware-iotagent-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

/* jshint camelcase: false */

var migration = require('../../../lib/command/migration'),
    mongo = require('mongodb').MongoClient,
    mongoUtils = require('../mongodb/mongoDBUtils'),
    utils = require('../../tools/utils'),
    logger = require('logops'),
    async = require('async'),
    apply = async.apply,
    should = require('should'),
    deviceCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/devices.json'),
    configurationCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/configurations.json'),
    originDb,
    targetDb;

describe.only('MongoDB migration', function() {
    beforeEach(function(done) {
        logger.setLevel('FATAL');

        mongo.connect('mongodb://localhost:27017/iotOrigin', function(err, db) {
            originDb = db;
            mongo.connect('mongodb://localhost:27017/iotTarget', function(err, db) {
                targetDb = db;
                async.series([
                    apply(mongoUtils.populate, 'localhost', 'iotOrigin', deviceCollection, 'DEVICE'),
                    apply(mongoUtils.populate, 'localhost', 'iotOrigin', configurationCollection, 'SERVICE')
                ], done);
            });
        });
    });

    afterEach(function(done) {
        mongoUtils.cleanDb('localhost', 'iotTarget', function(error) {
            mongoUtils.cleanDb('localhost', 'iotOrigin', function(error) {
                originDb.close(function(error) {
                    targetDb.close(function(error) {
                        done();
                    });
                });
            });
        });
    });

    describe('When the full migration command is executed for two databases', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate all the services', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('groups').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(3);
                    done();
                });
            });
        });
        it('should migrate all the devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(4);
                    done();
                });
            });
        });
        it('should migrate all the fields for each device', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('groups').find({
                    service: 'dumb_mordor'
                }).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    should.exist(docs[0].apikey);
                    should.exist(docs[0].cbHost);
                    should.exist(docs[0].resource);
                    should.exist(docs[0].service);
                    should.exist(docs[0].subservice);
                    should.exist(docs[0].type);
                    should.exist(docs[0].staticAttributes);
                    done();
                });
            });
        });
        it('should migrate all the fields for each service', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('devices').find({
                    id: 'gk20'
                }).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    should.exist(docs[0].id);
                    should.exist(docs[0].name);
                    should.exist(docs[0].protocol);
                    should.exist(docs[0].service);
                    should.exist(docs[0].subservice);
                    should.exist(docs[0].type);
                    should.exist(docs[0].active);
                    should.exist(docs[0].staticAttributes);
                    docs[0].id = 'gk20';
                    docs[0].name = 'The GK20 Entity';
                    docs[0].protocol = 'PDI-IoTA-UltraLight';
                    docs[0].service = 'smart_gondor';
                    docs[0].subservice = '/gardens';
                    docs[0].type = 'acme.lights.sensor';
                    done();
                });
            });
        });
    });

    describe('When a service migration command is executed', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate just the service\'s  configurations', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() {
                targetDb.collection('groups').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    done();
                });
            });
        });
        it('should migrate just the service\'s devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(3);
                    done();
                });
            });
        });
    });

    describe('When a subservice migration command is executed', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate just the subservice\'s devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    done();
                });
            });
        });
    });
});
<commit_msg>Remove only from tests<commit_after>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * fiware-iotagent-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[contacto@tid.es]
 */
'use strict';

/* jshint camelcase: false */

var migration = require('../../../lib/command/migration'),
    mongo = require('mongodb').MongoClient,
    mongoUtils = require('../mongodb/mongoDBUtils'),
    utils = require('../../tools/utils'),
    logger = require('logops'),
    async = require('async'),
    apply = async.apply,
    should = require('should'),
    deviceCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/devices.json'),
    configurationCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/configurations.json'),
    originDb,
    targetDb;

describe('MongoDB migration', function() {
    beforeEach(function(done) {
        logger.setLevel('FATAL');

        mongo.connect('mongodb://localhost:27017/iotOrigin', function(err, db) {
            originDb = db;
            mongo.connect('mongodb://localhost:27017/iotTarget', function(err, db) {
                targetDb = db;
                async.series([
                    apply(mongoUtils.populate, 'localhost', 'iotOrigin', deviceCollection, 'DEVICE'),
                    apply(mongoUtils.populate, 'localhost', 'iotOrigin', configurationCollection, 'SERVICE')
                ], done);
            });
        });
    });

    afterEach(function(done) {
        mongoUtils.cleanDb('localhost', 'iotTarget', function(error) {
            mongoUtils.cleanDb('localhost', 'iotOrigin', function(error) {
                originDb.close(function(error) {
                    targetDb.close(function(error) {
                        done();
                    });
                });
            });
        });
    });

    describe('When the full migration command is executed for two databases', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate all the services', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('groups').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(3);
                    done();
                });
            });
        });
        it('should migrate all the devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(4);
                    done();
                });
            });
        });
        it('should migrate all the fields for each device', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('groups').find({
                    service: 'dumb_mordor'
                }).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    should.exist(docs[0].apikey);
                    should.exist(docs[0].cbHost);
                    should.exist(docs[0].resource);
                    should.exist(docs[0].service);
                    should.exist(docs[0].subservice);
                    should.exist(docs[0].type);
                    should.exist(docs[0].staticAttributes);
                    done();
                });
            });
        });
        it('should migrate all the fields for each service', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() {
                targetDb.collection('devices').find({
                    id: 'gk20'
                }).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    should.exist(docs[0].id);
                    should.exist(docs[0].name);
                    should.exist(docs[0].protocol);
                    should.exist(docs[0].service);
                    should.exist(docs[0].subservice);
                    should.exist(docs[0].type);
                    should.exist(docs[0].active);
                    should.exist(docs[0].staticAttributes);
                    docs[0].id = 'gk20';
                    docs[0].name = 'The GK20 Entity';
                    docs[0].protocol = 'PDI-IoTA-UltraLight';
                    docs[0].service = 'smart_gondor';
                    docs[0].subservice = '/gardens';
                    docs[0].type = 'acme.lights.sensor';
                    done();
                });
            });
        });
    });

    describe('When a service migration command is executed', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate just the service\'s  configurations', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() {
                targetDb.collection('groups').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    done();
                });
            });
        });
        it('should migrate just the service\'s devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(3);
                    done();
                });
            });
        });
    });

    describe('When a subservice migration command is executed', function() {
        var config = {
            host: 'localhost',
            port: '27017'
        };

        it('should migrate just the subservice\'s devices', function(done) {
            migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function() {
                targetDb.collection('devices').find({}).toArray(function(err, docs) {
                    should.not.exist(err);
                    docs.length.should.equal(1);
                    done();
                });
            });
        });
    });
});
<|endoftext|>