<commit_before>var Element = require( '../../lib/element' )

describe( 'Element', function () {
	var elem = new Element()
	var elemInstance
	//create element
	describe( 'var elem = new Element() //create new element', function(){
		it( 'elem is instance of Element', function () {
			expect(elem).to.be.instanceOf(Element);
		})

		it( 'elem has no key by default', function () {
			expect(elem._$key).to.equal(void 0);
		})

		it( 'elem has no path', function () {
			expect(elem.$path.length).to.equal(0);
		})

		it( 'elem has no context', function () {
			expect(elem._$context).to.not.be.ok;
		})
	})

	//set key
	describe( 'elem.set({ $key:\'elemKey\' }) //set key', function(){

		it( 'elem now has key \'elemKey\'', function () {
			elem.set({$key:'elemKey'})
			expect(elem._$key).to.equal('elemKey');
		})

		it( 'elem now has a path [\'elemKey\']', function () {
			expect(elem.$path).to.deep.equal(['elemKey']);
		})

		it( 'elem still has no context', function () {
			expect(elem._$context).to.not.be.ok;
		})

	})

	//add child
	describe( 'elem.set({ elemChild:{}, elemChild2:{} }) //add children', function(){

		it( 'elem.elemChild is instance of Element', function () {
			elem.set({ elemChild:{}, elemChild2:{} })
			expect(elem.elemChild instanceof Element).to.equal(true);
		})

		it( 'elem.elemChild has key \'elemChild\'', function () {
			expect(elem.elemChild._$key).to.equal('elemChild');
		})

		it( "elem.elemChild has path ['elemKey','elemChild']", function () {
			expect(elem.elemChild.$path).to.deep.equal(['elemKey','elemChild']);
		})

		it( 'elem.elemChild has no context', function () {
			expect(elem.elemChild._$context).to.not.be.ok;
		})

	})

	//create instance of elem
	describe( 'var elemInstance = new elem.$Constructor() //create instance', function(){
		elemInstance = new elem.$Constructor()

		it( 'elemInstance is instance of elem._$Constructor', function () {
			expect(elemInstance).to.be.instanceOf(elem._$Constructor);
		})

		it( 'elemInstance.elemChild is instance of elem.elemChild._$Constructor', function () {
			expect(elemInstance.elemChild).to.be.instanceOf(elem.elemChild._$Constructor);
		})

		it( 'elemInstance has the same key as elem: \'elemKey\'', function () {
			expect(elem._$key).to.equal(elemInstance._$key).to.equal('elemKey');
		})

		it( 'elemInstance has no context', function () {
			expect(elemInstance._$context).to.not.be.ok;
		})

		it( 'elemInstance.elemChild has context elemInstance', function () {
			expect(elemInstance.elemChild._$context).to.equal(elemInstance);
		})

		it( 'elem.elemChild still has no context', function () {
			expect(elem.elemChild._$context).to.not.be.ok;
		})
	})

	//set key
	describe( 'elemInstance.set({ $key:\'elemInstanceKey\' }) //change instance key', function(){

		it( 'elemInstance now has key \'elemInstanceKey\'', function () {
			elemInstance.set({$key:'elemInstanceKey'})
			expect(elemInstance._$key).to.equal('elemInstanceKey');
		})

		it( 'elem now has a path [\'elemInstanceKey\']', function () {
			expect(elemInstance.$path).to.deep.equal(['elemInstanceKey']);
		})

	})

	//add child to elemInstance
	describe( 'elemInstance.set({ elemInstanceChild:{} }) //add child to instance', function(){
		it( 'elem does not have child elemInstanceChild', function () {
			elemInstance.set({ elemInstanceChild:{} })
			expect(elem.elemInstanceChild).to.not.be.ok
		})

		it( 'elemInstance.elemInstanceChild is instance of Element', function () {
			expect(elemInstance.elemInstanceChild).to.be.instanceOf(Element);
		})

		it( 'elemInstance.elemInstanceChild has path [\'elemInstanceKey\',\'elemInstanceChild\']', function () {
			expect(elemInstance.elemInstanceChild.$path).to.deep.equal(['elemInstanceKey','elemInstanceChild']);
		})

	})

	//remove child from original
	describe( 'elem.elemChild.remove() //remove child from original', function(){

		it( 'elem.elemChild is removed', function () {
			elem.elemChild.remove()
			expect(elem.elemChild).to.not.be.ok
		})

		it( 'elemInstance.elemChild also is removed', function () {
			expect(elemInstance.elemChild).to.not.be.ok
		})

	})

	//remove child from instance
	describe( 'elemInstance.elemChild2.remove() //remove child from instance', function(){

		it( 'elemInstance.elemChild2 is removed', function () {
			elemInstance.elemChild2.remove()
			expect(elemInstance.elemChild2).to.not.be.ok
		})

		it( 'elem.elemChild2 is not removed', function () {
			expect(elem.elemChild2).to.be.ok
		})

	})

})<commit_msg>Little refactor<commit_after>var Element = require( '../../lib/element' )

describe( 'Element', function () {
	var elem = new Element()
	var elemInstance
	//create element
	describe( 'var elem = new Element() //create new element', function(){
		it( 'elem is instance of Element', function () {
			expect(elem).to.be.instanceOf(Element);
		})

		it( 'elem has no key by default', function () {
			expect(elem._$key).to.equal(void 0);
		})

		it( 'elem has no path', function () {
			expect(elem.$path.length).to.equal(0);
		})

		it( 'elem has no context', function () {
			expect(elem._$context).to.not.be.ok;
		})
	})

	//set key
	describe( 'elem.set({ $key:\'elemKey\' }) //set key', function(){

		it( 'elem now has key \'elemKey\'', function () {
			elem.set({$key:'elemKey'})
			expect(elem._$key).to.equal('elemKey');
		})

		it( 'elem now has a path [\'elemKey\']', function () {
			expect(elem.$path).to.deep.equal(['elemKey']);
		})

		it( 'elem still has no context', function () {
			expect(elem._$context).to.not.be.ok;
		})

	})

	//add child
	describe( 'elem.set({ elemChild:{}, elemChild2:{} }) //add children', function(){

		it( 'elem.elemChild is instance of Element', function () {
			elem.set({ elemChild:{}, elemChild2:{} })
			expect(elem.elemChild instanceof Element).to.equal(true);
		})

		it( 'elem.elemChild has key \'elemChild\'', function () {
			expect(elem.elemChild._$key).to.equal('elemChild');
		})

		it( "elem.elemChild has path ['elemKey','elemChild']", function () {
			expect(elem.elemChild.$path).to.deep.equal(['elemKey','elemChild']);
		})

		it( 'elem.elemChild has no context', function () {
			expect(elem.elemChild._$context).to.not.be.ok;
		})

	})

	//create instance of elem
	describe( 'var elemInstance = new elem.$Constructor() //create instance', function(){
		elemInstance = new elem.$Constructor()

		it( 'elemInstance is instance of elem._$Constructor', function () {
			expect(elemInstance).to.be.instanceOf(elem._$Constructor);
		})

		it( 'elemInstance.elemChild is instance of elem.elemChild._$Constructor', function () {
			expect(elemInstance.elemChild).to.be.instanceOf(elem.elemChild._$Constructor);
		})

		it( 'elemInstance has the same key as elem: \'elemKey\'', function () {
			expect(elem._$key).to.equal(elemInstance._$key).to.equal('elemKey');
		})

		it( 'elemInstance has no context', function () {
			expect(elemInstance._$context).to.not.be.ok;
		})

		it( 'elemInstance.elemChild has context elemInstance', function () {
			expect(elemInstance.elemChild._$context).to.equal(elemInstance);
		})

		it( 'elem.elemChild still has no context', function () {
			expect(elem.elemChild._$context).to.not.be.ok;
		})
	})

	//set key
	describe( 'elemInstance.set({ $key:\'elemInstanceKey\' }) //change instance key', function(){

		it( 'elemInstance now has key \'elemInstanceKey\'', function () {
			elemInstance.set({$key:'elemInstanceKey'})
			expect(elemInstance._$key).to.equal('elemInstanceKey');
		})

		it( 'elemInstance now has a path [\'elemInstanceKey\']', function () {
			expect(elemInstance.$path).to.deep.equal(['elemInstanceKey']);
		})

	})

	//add child to elemInstance
	describe( 'elemInstance.set({ elemInstanceChild:{} }) //add child to instance', function(){
		it( 'elem does not have child elemInstanceChild', function () {
			elemInstance.set({ elemInstanceChild:{} })
			expect(elem.elemInstanceChild).to.not.be.ok
		})

		it( 'elemInstance.elemInstanceChild is instance of Element', function () {
			expect(elemInstance.elemInstanceChild).to.be.instanceOf(Element);
		})

		it( 'elemInstance.elemInstanceChild has path [\'elemInstanceKey\',\'elemInstanceChild\']', function () {
			expect(elemInstance.elemInstanceChild.$path).to.deep.equal(['elemInstanceKey','elemInstanceChild']);
		})

	})

	//remove child from original
	describe( 'elem.elemChild.remove() //remove child from original', function(){

		it( 'elem.elemChild is removed', function () {
			elem.elemChild.remove()
			expect(elem.elemChild).to.not.be.ok
		})

		it( 'elemInstance.elemChild also is removed', function () {
			expect(elemInstance.elemChild).to.not.be.ok
		})

	})

	//remove child from instance
	describe( 'elemInstance.elemChild2.remove() //remove child from instance', function(){

		it( 'elemInstance.elemChild2 is removed', function () {
			elemInstance.elemChild2.remove()
			expect(elemInstance.elemChild2).to.not.be.ok
		})

		it( 'elem.elemChild2 is not removed', function () {
			expect(elem.elemChild2).to.be.ok
		})

	})

})<|endoftext|>


<commit_before>var acquit = require('acquit');
var assert = require('assert');

describe('acquit-markdown', function() {
  afterEach(function() {
    acquit.removeAllOutputProcessors();
  });

  it('converts acquit output to a simple markdown format', function() {
    var acquit = require('acquit');
    require('acquit-markdown')();

    var code = [
      'describe("My feature", function() {',
      '  /** This is a very important feature */',
      '  describe("My subfeature", function() {',
      '    it("works", function() {',
      '      // code here',
      '    })',
      '  })',
      '})'
    ].join('\n');

    assert.equal(acquit.parse(code), [
      '# My feature',
      '',
      '## My subfeature',
      '',
      'This is a very important feature',
      '',
      '### It works',
      '',
      '```javascript',
      '',
      '      // code here',
      '    ',
      '```'
    ].join('\n'));
  });

  it('can use acquit constructor', function() {
    var acquit = require('acquit')();
    require('acquit-markdown')(acquit);

    var code = [
      'describe("My feature", function() {',
      '  /** This is a very important feature */',
      '  describe("My subfeature", function() {',
      '    it("works", function() {',
      '      // code here',
      '    })',
      '  })',
      '})'
    ].join('\n');

    assert.equal(acquit.parse(code), [
      '# My feature',
      '',
      '## My subfeature',
      '',
      'This is a very important feature',
      '',
      '### It works',
      '',
      '```javascript',
      '',
      '      // code here',
      '    ',
      '```'
    ].join('\n'));
  });
});
<commit_msg>Update examples.test.js<commit_after>var acquit = require('acquit');
var assert = require('assert');

describe('acquit-markdown', function() {
  afterEach(function() {
    acquit.removeAllOutputProcessors();
  });

  /**
   * The acquit-markdown plugin adds an output processor to acquit that
   * transforms acquit's syntax tree output into a markdown string. It
   * converts mocha descriptions into headers, comments into paragraphs,
   * and wraps code in backticks.
   */
  it('converts acquit output to a simple markdown format', function() {
    var acquit = require('acquit');
    require('acquit-markdown')();

    var code = [
      'describe("My feature", function() {',
      '  /** This is a very important feature */',
      '  describe("My subfeature", function() {',
      '    it("works", function() {',
      '      // code here',
      '    })',
      '  })',
      '})'
    ].join('\n');

    assert.equal(acquit.parse(code), [
      '# My feature',
      '',
      '## My subfeature',
      '',
      'This is a very important feature',
      '',
      '### It works',
      '',
      '```javascript',
      '',
      '      // code here',
      '    ',
      '```'
    ].join('\n'));
  });

  it('can use acquit constructor', function() {
    var acquit = require('acquit')();
    require('acquit-markdown')(acquit);

    var code = [
      'describe("My feature", function() {',
      '  /** This is a very important feature */',
      '  describe("My subfeature", function() {',
      '    it("works", function() {',
      '      // code here',
      '    })',
      '  })',
      '})'
    ].join('\n');

    assert.equal(acquit.parse(code), [
      '# My feature',
      '',
      '## My subfeature',
      '',
      'This is a very important feature',
      '',
      '### It works',
      '',
      '```javascript',
      '',
      '      // code here',
      '    ',
      '```'
    ].join('\n'));
  });
});
<|endoftext|>


<commit_before>/*globals it, describe, beforeEach, afterEach */
import mock from 'mock-fs';
import _ from 'lodash';
import * as assertFile from './utils/assertFile';
import mockPrompter from './utils/mockPrompter';
import fsRenamer  from '../src/fsRenamer';
import chai, { assert } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

const testDirectory = {
    testfile1: 'content of testfile1',
    testfile2: 'content of testfile2',
    testfile3: 'content of testfile3'
};

beforeEach(() => {
    mock(testDirectory);
    assertFile.setup(testDirectory);
});

afterEach(() => {
    mock.restore()
    assertFile.teardown();
});

describe('fsRenamer', () => {
    it('takes array of src/dest pairs and moves files', () => {
        const pairs = [
            [ 'testfile1', 'foobarbaz' ],
            [ 'testfile2', 'bazbarfoo' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('does not error on empty array', () => {
        const promise = fsRenamer([]);
        return assert.isFulfilled(promise);
    });

    it('returns error if source does not exist', () => {
        const pairs = [
            [ 'this-file-doesnt-exist', 'foobarbaz' ]
        ];
        const promise = fsRenamer(pairs);
        return assert.isRejected(promise);
    });

    it('can create new directories', () => {
        const pairs = [
            [ 'testfile1', 'foo/bar/testfile1' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('does not overwrite existing file', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.unmoved(oldfile))));
    });

    it('overwrites existing file if passed force flag', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ]
        ];
        const promise = fsRenamer(pairs, { force: true });
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('creates backup when passed backup flag', () => {
        const oldfile = 'testfile1';
        const backup = oldfile + '.bak';
        const newfile = 'asdf';
        const pairs = [
            [ oldfile, newfile ]
        ];
        const promise = fsRenamer(pairs, { backup: true });
        return promise.then(() =>
            Promise.all([
                assertFile.moved(oldfile, newfile),
                assertFile.moved(oldfile, backup)
            ]));
    });

    it('can perform cyclical rename', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ],
            [ 'testfile2', 'testfile3' ],
            [ 'testfile3', 'testfile1' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile, { noSrcMove: true }))));
    });

    it('prompts for to rename files if passed interactive flag', () => {
        const pairs = [
            [ 'testfile1', 'not-renamed' ],
            [ 'testfile2', 'renamed' ],
        ];
        const options = { interactive: true };
        fsRenamer.__inject(mockPrompter('n', 'y'))
        const promise = fsRenamer(pairs, options);
        return promise.then(() =>
            Promise.all([
                assertFile.unmoved(pairs[0][0], pairs[0][1]),
                assertFile.moved(pairs[1][0], pairs[1][1])
            ]))
    });
});
<commit_msg>Make interactive test more thorough<commit_after>/*globals it, describe, beforeEach, afterEach */
import mock from 'mock-fs';
import _ from 'lodash';
import * as assertFile from './utils/assertFile';
import mockPrompter from './utils/mockPrompter';
import fsRenamer  from '../src/fsRenamer';
import chai, { assert } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

const testDirectory = {
    testfile1: 'content of testfile1',
    testfile2: 'content of testfile2',
    testfile3: 'content of testfile3'
};

beforeEach(() => {
    mock(testDirectory);
    assertFile.setup(testDirectory);
});

afterEach(() => {
    mock.restore()
    assertFile.teardown();
});

describe('fsRenamer', () => {
    it('takes array of src/dest pairs and moves files', () => {
        const pairs = [
            [ 'testfile1', 'foobarbaz' ],
            [ 'testfile2', 'bazbarfoo' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('does not error on empty array', () => {
        const promise = fsRenamer([]);
        return assert.isFulfilled(promise);
    });

    it('returns error if source does not exist', () => {
        const pairs = [
            [ 'this-file-doesnt-exist', 'foobarbaz' ]
        ];
        const promise = fsRenamer(pairs);
        return assert.isRejected(promise);
    });

    it('can create new directories', () => {
        const pairs = [
            [ 'testfile1', 'foo/bar/testfile1' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('does not overwrite existing file', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.unmoved(oldfile))));
    });

    it('overwrites existing file if passed force flag', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ]
        ];
        const promise = fsRenamer(pairs, { force: true });
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile))));
    });

    it('creates backup when passed backup flag', () => {
        const oldfile = 'testfile1';
        const backup = oldfile + '.bak';
        const newfile = 'asdf';
        const pairs = [
            [ oldfile, newfile ]
        ];
        const promise = fsRenamer(pairs, { backup: true });
        return promise.then(() =>
            Promise.all([
                assertFile.moved(oldfile, newfile),
                assertFile.moved(oldfile, backup)
            ]));
    });

    it('can perform cyclical rename', () => {
        const pairs = [
            [ 'testfile1', 'testfile2' ],
            [ 'testfile2', 'testfile3' ],
            [ 'testfile3', 'testfile1' ]
        ];
        const promise = fsRenamer(pairs);
        return promise.then(() =>
            Promise.all(_.map(pairs, ([ oldfile, newfile ]) => assertFile.moved(oldfile, newfile, { noSrcMove: true }))));
    });

    it('prompts for to rename files if passed interactive flag', () => {
        const pairs = [
            [ 'testfile1', 'not-renamed' ],
            [ 'testfile2', 'renamed' ],
            [ 'testfile3', 'alsorenamed' ]
        ];
        const options = { interactive: true };
        // use dependency injection to simulate keypress prompt library:
        fsRenamer.__inject(mockPrompter('y', 'n', 'y'));
        const promise = fsRenamer(pairs, options);
        return promise.then(() =>
            Promise.all([
                assertFile.moved(pairs[0][0], pairs[0][1]),
                assertFile.unmoved(pairs[1][0], pairs[1][1]),
                assertFile.moved(pairs[2][0], pairs[2][1])
            ]))
    });
});
<|endoftext|>


<commit_before>var filename = require('../lib/filename');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var exists = fs.existsSync || path.existsSync;
var combinations = require('../lib/combinations');

suite('generate', function() {
  test('make sure all files have been generated', function() {

    var combos = combinations();

    combos.forEach(function(combo) {
      var f1 = filename(combo, false);
      assert.equal(exists(path.join(__dirname, '../dist/'+f1)), true, f1)
      var f2 = filename(combo, true);
      assert.equal(exists(path.join(__dirname, '../dist/'+f2)), true, f2)
    });

  });
});

<commit_msg>updated tests<commit_after>var filename = require('../lib/filename');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var exists = fs.existsSync || path.existsSync;
var combinations = require('../lib/combinations');
var data = require('../data.json');

suite('generate', function() {
  test('make sure all files have been generated', function() {

    var combos = combinations();
    var versions = data.versions

    versions.forEach(function(version) {

      combos.forEach(function(combo) {
        var f1 = filename(combo, false);
        assert.equal(exists(path.join(__dirname, '../dist/'+version+'/'+f1)), true, f1)
        var f2 = filename(combo, true);
        assert.equal(exists(path.join(__dirname, '../dist/'+version+'/'+f2)), true, f2)
      });
    })

  });
});

<|endoftext|>


<commit_before>var _       = require( 'lodash' );
var should  = require( 'should' );
var sinon   = require( 'sinon' );
var pequire = require( 'proxyquire' );

// Happy-path proxyquire dependencies, i.e., dependencies that will allow
// gulp-hub to complete without errors
var HAPPY_PROXY_DEPS = {
    'gulp-util': {
        log:    _.noop,
        colors: { yellow: _.noop }
    },
    './resolve-glob': _.noop,
    './get-subfiles': function () { return [] },
    './load-subfile': _.noop,
    './add-task':     _.noop,
};

// Proxyquire gulp-hub, optionally extending the happy-path proxy dependencies
var getHub = function ( proxyDeps ) {
    return pequire( '../lib/index', _.assign( {}, HAPPY_PROXY_DEPS, proxyDeps ) );
};

describe( 'gulp-hub', function () {

    it( 'is a function', function () {
        getHub().should.be.an.instanceOf( Function );
    } );

    it( 'takes a glob or an array of globs', function () {
        var hub = getHub();
        var INVALID_VALUES = [ '', 0, 1, true, false, [], {}, { a: 'foo' }, null, undefined ];

        // Assert we get an error for invalid values
        INVALID_VALUES.forEach( function ( testValue ) {
            hub.bind( null, testValue ).should.throw(
                'A glob pattern or an array of glob patterns is required.'
            );
        } );

        // Assert we don't get an error for a valid glob (non-empty string)
        hub.bind( null, 'ok' ).should.not.throw();
    } );

    it( 'resolves a glob pattern to a file list', function () {
        var resolveGlobSpy = sinon.spy();
        var hub = getHub( { './resolve-glob': resolveGlobSpy } );
        hub( 'test-pattern' );
        resolveGlobSpy.calledOnce.should.be.true;
        resolveGlobSpy.calledWith( 'test-pattern' );
    } );

    it( 'creates a list of Gulp Hub files from a file list', function () {
        var spy = sinon.spy( HAPPY_PROXY_DEPS[ './get-subfiles' ] );
        var hub = getHub( {
            './resolve-glob': function () { return 'resolve-glob-return' },
            './get-subfiles': spy
        } );
        hub( 'test-pattern' );
        spy.calledOnce.should.be.true;
        spy.calledWith( 'resolve-glob-return' ).should.be.true;
    } );

    it( 'logs each file it loads, path in yellow', function () {
        var logSpy = sinon.spy();
        var colorSpy = sinon.spy( function ( s ) { return 'yellow-' + s } );

        var hub = getHub( {
            'gulp-util': {
                log:    logSpy,
                colors: { yellow: colorSpy }
            },
            './get-subfiles': function () { return [
                { relativePath: 'rel-path-1' },
                { relativePath: 'rel-path-2' }
            ] }
        } );

        hub( 'test-pattern' );

        logSpy.calledTwice.should.be.true;
        logSpy.calledWith( 'Loading', 'yellow-rel-path-1' ).should.be.true;
        logSpy.calledWith( 'Loading', 'yellow-rel-path-2' ).should.be.true;

        colorSpy.calledTwice.should.be.true;
        colorSpy.calledWith( 'rel-path-1' ).should.be.true;
        colorSpy.calledWith( 'rel-path-2' ).should.be.true;
    } );

    it( 'loads each subfile', function () {
        var loadSpy = sinon.spy();
        var hub = getHub( {
            './get-subfiles': function () { return [
                { relativePath: 'rel-path-1' },
                { relativePath: 'rel-path-2' }
            ] },
            './load-subfile': loadSpy
        } );
        hub( 'test-pattern' );
        loadSpy.calledTwice.should.be.true;
        loadSpy.calledWith( { relativePath: 'rel-path-1' }, {} ).should.be.true;
        loadSpy.calledWith( { relativePath: 'rel-path-2' }, {} ).should.be.true;
    } );

    it( 'adds each discovered task' );
} );
<commit_msg>Add addTask test<commit_after>var _       = require( 'lodash' );
var should  = require( 'should' );
var sinon   = require( 'sinon' );
var pequire = require( 'proxyquire' );

// Happy-path proxyquire dependencies, i.e., dependencies that will allow
// gulp-hub to complete without errors
var HAPPY_PROXY_DEPS = {
    'gulp-util': {
        log:    _.noop,
        colors: { yellow: _.noop }
    },
    './resolve-glob': _.noop,
    './get-subfiles': function () { return [] },
    './load-subfile': _.noop,
    './add-task':     _.noop,
};

// Proxyquire gulp-hub, optionally extending the happy-path proxy dependencies
var getHub = function ( proxyDeps ) {
    return pequire( '../lib/index', _.assign( {}, HAPPY_PROXY_DEPS, proxyDeps ) );
};

describe( 'gulp-hub', function () {

    it( 'is a function', function () {
        getHub().should.be.an.instanceOf( Function );
    } );

    it( 'takes a glob or an array of globs', function () {
        var hub = getHub();
        var INVALID_VALUES = [ '', 0, 1, true, false, [], {}, { a: 'foo' }, null, undefined ];

        // Assert we get an error for invalid values
        INVALID_VALUES.forEach( function ( testValue ) {
            hub.bind( null, testValue ).should.throw(
                'A glob pattern or an array of glob patterns is required.'
            );
        } );

        // Assert we don't get an error for a valid glob (non-empty string)
        hub.bind( null, 'ok' ).should.not.throw();
    } );

    it( 'resolves a glob pattern to a file list', function () {
        var resolveGlobSpy = sinon.spy();
        var hub = getHub( { './resolve-glob': resolveGlobSpy } );
        hub( 'test-pattern' );
        resolveGlobSpy.calledOnce.should.be.true;
        resolveGlobSpy.calledWith( 'test-pattern' );
    } );

    it( 'creates a list of Gulp Hub files from a file list', function () {
        var spy = sinon.spy( HAPPY_PROXY_DEPS[ './get-subfiles' ] );
        var hub = getHub( {
            './resolve-glob': function () { return 'resolve-glob-return' },
            './get-subfiles': spy
        } );
        hub( 'test-pattern' );
        spy.calledOnce.should.be.true;
        spy.calledWith( 'resolve-glob-return' ).should.be.true;
    } );

    it( 'logs each file it loads, path in yellow', function () {
        var logSpy = sinon.spy();
        var colorSpy = sinon.spy( function ( s ) { return 'yellow-' + s } );

        var hub = getHub( {
            'gulp-util': {
                log:    logSpy,
                colors: { yellow: colorSpy }
            },
            './get-subfiles': function () { return [
                { relativePath: 'rel-path-1' },
                { relativePath: 'rel-path-2' }
            ] }
        } );

        hub( 'test-pattern' );

        logSpy.calledTwice.should.be.true;
        logSpy.calledWith( 'Loading', 'yellow-rel-path-1' ).should.be.true;
        logSpy.calledWith( 'Loading', 'yellow-rel-path-2' ).should.be.true;

        colorSpy.calledTwice.should.be.true;
        colorSpy.calledWith( 'rel-path-1' ).should.be.true;
        colorSpy.calledWith( 'rel-path-2' ).should.be.true;
    } );

    it( 'loads each subfile', function () {
        var loadSpy = sinon.spy();
        var hub = getHub( {
            './get-subfiles': function () { return [
                { relativePath: 'rel-path-1' },
                { relativePath: 'rel-path-2' }
            ] },
            './load-subfile': loadSpy
        } );
        hub( 'test-pattern' );
        loadSpy.calledTwice.should.be.true;
        loadSpy.calledWith( { relativePath: 'rel-path-1' }, {} ).should.be.true;
        loadSpy.calledWith( { relativePath: 'rel-path-2' }, {} ).should.be.true;
    } );

    it( 'adds each subfile\'s task', function () {
        var addTaskSpy = sinon.spy();
        var hub = getHub( {
            './get-subfiles': function () { return [ 1, 2 ] },
            './load-subfile': function ( subfile, tasks ) {
                tasks.a = 'foo';
                tasks.b = 'bar';
            },
            './add-task': addTaskSpy
        } );
        hub( 'test-pattern' );
        addTaskSpy.calledTwice.should.be.true;
        addTaskSpy.calledWith( 'foo' ).should.be.true;
        addTaskSpy.calledWith( 'bar' ).should.be.true;
    } );
} );
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Joyent, Inc. All rights reserved.
 *
 * Test the importer.
 */

var fs      = require('fs');
var Logger  = require('bunyan');
var path    = require('path');
var restify = require('restify');
var spawn   = require('child_process').spawn;
var test    = require('tap').test;
var papi    = require('../lib/papi');

var DEFAULT_CFG_PATH = path.resolve(__dirname, '../etc/config.json');
var TEST_LDIF_PATH   = path.resolve(__dirname, 'importer.test.ldif');
var TEST_JSON_PATH   = path.resolve(__dirname, 'importer.test.json');
var IMPORTER_PATH    = path.resolve(__dirname, '../bin/importer');

var server, client, backend, cfgPath;

test('setup', function (t) {
    cfgPath = fs.existsSync(DEFAULT_CFG_PATH) ? DEFAULT_CFG_PATH :
              path.resolve(__dirname, '../etc/config.test.json');

    var config = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));

    var logger = new Logger({
        level: process.env.LOG_LEVEL || 'info',
        name: 'sdc-package-importer-test',
        stream: process.stdout,
        serializers: restify.bunyan.serializers
    });

    papi.createServer({
        config: cfgPath,
        log: logger,
        overrides: {},
        test: true
    }, function (err, s) {
        t.ok(s, 'server ok');
        t.ok(s.backend, 'server backend ok');
        server = s;
        backend = s.backend;

        client = restify.createJsonClient({
            log: s.log,
            url: 'http://127.0.0.1:' + config.port,
            version: '*',
            retryOptions: {
                retry: 0
            }
        });

        t.ok(client, 'client ok');
        t.end();
    });
});

test('Clean up stale state (before)', cleanUp);
test('Check no stale packages (before)', checkNoPkgs);

test('Run importer with ldif', importLdif);
test('GET /packages/b65b8ce2-29e7-4f63-b529-357f42bf0742', checkPkg1);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);
test('GET /packages/487997df-a4da-4fd3-bcfc-98f100178241', checkPkg3);

test('Mutate b8c43025-cfd9-446d-a871-4444c15d9648', mutatePkg2);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkMutatedPkg2);
test('Run importer with ldif', importLdif);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkMutatedPkg2);
test('Run importer with overwrite', importLdifOverwrite);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);

test('Clean up stale state (after ldif)', cleanUp);
test('Check no stale packages (after ldif)', checkNoPkgs);

test('Run importer with json', importJson);
test('GET /packages/b65b8ce2-29e7-4f63-b529-357f42bf0742', checkPkg1);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);
test('GET /packages/487997df-a4da-4fd3-bcfc-98f100178241', checkPkg3);

test('Clean up stale state (after json)', cleanUp);
test('Check no stale packages (after json)', checkNoPkgs);

test('Run importer with dryrun', importLdifDryrun);
test('Check no stale packages (after dryrun)', checkNoPkgs);

test('teardown', function (t) {
    t.end();

    // hack until I figure out why process is hanging when tests complete
    setTimeout(function () { process.exit(0); }, 200);
});

function importLdif(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH]);

//    importer.stdout.on('data', function (data) {
//        console.log('stdout: ' + data);
//    });
//
//    importer.stderr.on('data', function (data) {
//        console.log('stderr: ' + data);
//    });

    importer.on('close', function (code) {
        t.end();
    });
}

function importLdifDryrun(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH,
                                         '--dryrun']);
    importer.on('close', function (code) {
        t.end();
    });
}

function importLdifOverwrite(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH,
                                         '--overwrite']);
    importer.on('close', function (code) {
        t.end();
    });
}

function importJson(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--json=' + TEST_JSON_PATH]);

    importer.on('close', function (code) {
        t.end();
    });
}

function mutatePkg2(t) {
    var change = { max_physical_memory: 16384, max_swap: 32768 };

    client.put('/packages/b8c43025-cfd9-446d-a871-4444c15d9648?force=true',
               change, function (err, req, res, obj) {
        t.ifError(err, 'POST /packages error');
        t.equal(res.statusCode, 200);
        t.end();
    });
}

function cleanUp(t) {
    var deletePkgs = ['b65b8ce2-29e7-4f63-b529-357f42bf0742',
                      'b8c43025-cfd9-446d-a871-4444c15d9648',
                      '487997df-a4da-4fd3-bcfc-98f100178241'];

    var deletePkg = function () {
        var uuid = deletePkgs.pop();
        var url = '/packages/' + uuid + '?force=true';

        client.del(url, function (err, req, res, obj) {
            if (err && err.statusCode !== 404)
                t.ifError(err);

            if (deletePkgs.length > 0)
                return deletePkg();

            return t.end();
        });
    };

    deletePkg();
}

function checkNoPkgs(t) {
    var checkPkgs = ['b65b8ce2-29e7-4f63-b529-357f42bf0742',
                     'b8c43025-cfd9-446d-a871-4444c15d9648',
                     '487997df-a4da-4fd3-bcfc-98f100178241'];

    var checkPkg = function () {
        var uuid = checkPkgs.pop();
        var url = '/packages/' + uuid;

        client.get(url, function (err, req, res, obj) {
            t.equal(err.statusCode, 404);

            if (checkPkgs.length > 0)
                return checkPkg();

            return t.end();
        });
    };

    checkPkg();
}

function checkMutatedPkg2(t) {
    client.get('/packages/b8c43025-cfd9-446d-a871-4444c15d9648',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        var now = +new Date();
        var created = +new Date(obj.created_at);
        var updated = +new Date(obj.updated_at);
        t.ok(now - created < 1000);
        t.ok(now - updated < 1000);
        delete obj.created_at;
        delete obj.updated_at;

        var expectedResults = {
            active: false,
            cpu_cap: 300,
            default: true,
            max_lwps: 2000,
            max_physical_memory: 16384,
            max_swap: 32768,
            name: 'test-2',
            quota: 81920,
            uuid: 'b8c43025-cfd9-446d-a871-4444c15d9648',
            version: '1.0.1',
            zfs_io_priority: 50
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

function checkPkg1(t) {
    client.get('/packages/b65b8ce2-29e7-4f63-b529-357f42bf0742',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        var now = +new Date();
        var created = +new Date(obj.created_at);
        var updated = +new Date(obj.updated_at);
        t.ok(now - created < 1000);
        t.ok(now - updated < 1000);
        delete obj.created_at;
        delete obj.updated_at;

        var expectedResults = {
            active: true,
            common_name: 'Test 1',
            cpu_burst_ratio: 0.5,
            cpu_cap: 200,
            default: false,
            description: '4GB RAM, 1 CPUs and bursting, and 131GB Disk.',
            fss: 200,
            group: 'Test',
            max_lwps: 4000,
            max_physical_memory: 4096,
            max_swap: 8192,
            min_platform: { '7.0': '20130917T001310Z' },
            name: 'test-1',
            networks: [ '9ec60129-9034-47b4-b111-3026f9b1a10f',
                        '5983940e-58a5-4543-b732-c689b1fe4c08' ],
            os: 'smartos',
            overprovision_cpu: 2,
            overprovision_io: 2,
            overprovision_memory: 1,
            overprovision_network: 4,
            overprovision_storage: 1,
            owner_uuids: [ '7b315468-c6be-46dc-b99b-9c1f59224693',
                           '1d09a48c-d1ee-42b0-a22f-0baf42daac2b',
                           '67e48d3a-35e7-40a3-beee-55a1e4588500',
                           'ec473ba8-0d5a-4000-9fc9-20b43397ac7d' ],
            parent: 'g3-standard-4-smartos',
            quota: 134144,
            ram_ratio: 3.990024938,
            traits: { ssd: true, img_mgmt: true },
            urn: 'sdc:test-1:1.0.0',
            uuid: 'b65b8ce2-29e7-4f63-b529-357f42bf0742',
            vcpus: 2,
            version: '1.0.0',
            zfs_io_priority: 100
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

function checkPkg2(t) {
    client.get('/packages/b8c43025-cfd9-446d-a871-4444c15d9648',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        var now = +new Date();
        var created = +new Date(obj.created_at);
        var updated = +new Date(obj.updated_at);
        t.ok(now - created < 1000);
        t.ok(now - updated < 1000);
        delete obj.created_at;
        delete obj.updated_at;

        var expectedResults = {
            active: false,
            cpu_cap: 300,
            default: true,
            max_lwps: 2000,
            max_physical_memory: 2048,
            max_swap: 4096,
            name: 'test-2',
            quota: 81920,
            uuid: 'b8c43025-cfd9-446d-a871-4444c15d9648',
            version: '1.0.1',
            zfs_io_priority: 50
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

/*
 * This package is missing a required attribute (active), so shouldn't have
 * been imported.
 */

function checkPkg3(t) {
    client.get('/packages/487997df-a4da-4fd3-bcfc-98f100178241',
               function (err, req, res, obj) {
        t.equal(res.statusCode, 404);
        t.end();
    });
}
<commit_msg>PAPI-76 - alter date checking in importer.test.js.<commit_after>/*
 * Copyright (c) 2014, Joyent, Inc. All rights reserved.
 *
 * Test the importer.
 */

var fs      = require('fs');
var Logger  = require('bunyan');
var path    = require('path');
var restify = require('restify');
var spawn   = require('child_process').spawn;
var test    = require('tap').test;
var papi    = require('../lib/papi');

var DEFAULT_CFG_PATH = path.resolve(__dirname, '../etc/config.json');
var TEST_LDIF_PATH   = path.resolve(__dirname, 'importer.test.ldif');
var TEST_JSON_PATH   = path.resolve(__dirname, 'importer.test.json');
var IMPORTER_PATH    = path.resolve(__dirname, '../bin/importer');

var server, client, backend, cfgPath, startTime;

test('setup', function (t) {
    cfgPath = fs.existsSync(DEFAULT_CFG_PATH) ? DEFAULT_CFG_PATH :
              path.resolve(__dirname, '../etc/config.test.json');

    var config = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));

    var logger = new Logger({
        level: process.env.LOG_LEVEL || 'info',
        name: 'sdc-package-importer-test',
        stream: process.stdout,
        serializers: restify.bunyan.serializers
    });

    papi.createServer({
        config: cfgPath,
        log: logger,
        overrides: {},
        test: true
    }, function (err, s) {
        t.ok(s, 'server ok');
        t.ok(s.backend, 'server backend ok');
        server = s;
        backend = s.backend;

        client = restify.createJsonClient({
            log: s.log,
            url: 'http://127.0.0.1:' + config.port,
            version: '*',
            retryOptions: {
                retry: 0
            }
        });

        t.ok(client);

        startTime = +new Date();

        t.end();
    });
});

test('Clean up stale state (before)', cleanUp);
test('Check no stale packages (before)', checkNoPkgs);

test('Run importer with ldif', importLdif);
test('GET /packages/b65b8ce2-29e7-4f63-b529-357f42bf0742', checkPkg1);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);
test('GET /packages/487997df-a4da-4fd3-bcfc-98f100178241', checkPkg3);

test('Mutate b8c43025-cfd9-446d-a871-4444c15d9648', mutatePkg2);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkMutatedPkg2);
test('Run importer with ldif', importLdif);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkMutatedPkg2);
test('Run importer with overwrite', importLdifOverwrite);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);

test('Clean up stale state (after ldif)', cleanUp);
test('Check no stale packages (after ldif)', checkNoPkgs);

test('Run importer with json', importJson);
test('GET /packages/b65b8ce2-29e7-4f63-b529-357f42bf0742', checkPkg1);
test('GET /packages/b8c43025-cfd9-446d-a871-4444c15d9648', checkPkg2);
test('GET /packages/487997df-a4da-4fd3-bcfc-98f100178241', checkPkg3);

test('Clean up stale state (after json)', cleanUp);
test('Check no stale packages (after json)', checkNoPkgs);

test('Run importer with dryrun', importLdifDryrun);
test('Check no stale packages (after dryrun)', checkNoPkgs);

test('teardown', function (t) {
    t.end();

    // hack until I figure out why process is hanging when tests complete
    setTimeout(function () { process.exit(0); }, 200);
});

function importLdif(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH]);

//    importer.stdout.on('data', function (data) {
//        console.log('stdout: ' + data);
//    });
//
//    importer.stderr.on('data', function (data) {
//        console.log('stderr: ' + data);
//    });

    importer.on('close', function (code) {
        t.end();
    });
}

function importLdifDryrun(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH,
                                         '--dryrun']);
    importer.on('close', function (code) {
        t.end();
    });
}

function importLdifOverwrite(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--ldif=' + TEST_LDIF_PATH,
                                         '--overwrite']);
    importer.on('close', function (code) {
        t.end();
    });
}

function importJson(t) {
    var importer = spawn(IMPORTER_PATH, ['--config=' + cfgPath,
                                         '--json=' + TEST_JSON_PATH]);

    importer.on('close', function (code) {
        t.end();
    });
}

function mutatePkg2(t) {
    var change = { max_physical_memory: 16384, max_swap: 32768 };

    client.put('/packages/b8c43025-cfd9-446d-a871-4444c15d9648?force=true',
               change, function (err, req, res, obj) {
        t.ifError(err, 'POST /packages error');
        t.equal(res.statusCode, 200);
        t.end();
    });
}

function cleanUp(t) {
    var deletePkgs = ['b65b8ce2-29e7-4f63-b529-357f42bf0742',
                      'b8c43025-cfd9-446d-a871-4444c15d9648',
                      '487997df-a4da-4fd3-bcfc-98f100178241'];

    var deletePkg = function () {
        var uuid = deletePkgs.pop();
        var url = '/packages/' + uuid + '?force=true';

        client.del(url, function (err, req, res, obj) {
            if (err && err.statusCode !== 404)
                t.ifError(err);

            if (deletePkgs.length > 0)
                return deletePkg();

            return t.end();
        });
    };

    deletePkg();
}

function checkNoPkgs(t) {
    var checkPkgs = ['b65b8ce2-29e7-4f63-b529-357f42bf0742',
                     'b8c43025-cfd9-446d-a871-4444c15d9648',
                     '487997df-a4da-4fd3-bcfc-98f100178241'];

    var checkPkg = function () {
        var uuid = checkPkgs.pop();
        var url = '/packages/' + uuid;

        client.get(url, function (err, req, res, obj) {
            t.equal(err.statusCode, 404);

            if (checkPkgs.length > 0)
                return checkPkg();

            return t.end();
        });
    };

    checkPkg();
}

function checkMutatedPkg2(t) {
    client.get('/packages/b8c43025-cfd9-446d-a871-4444c15d9648',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        checkDate(t, obj);

        var expectedResults = {
            active: false,
            cpu_cap: 300,
            default: true,
            max_lwps: 2000,
            max_physical_memory: 16384,
            max_swap: 32768,
            name: 'test-2',
            quota: 81920,
            uuid: 'b8c43025-cfd9-446d-a871-4444c15d9648',
            version: '1.0.1',
            zfs_io_priority: 50
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

function checkPkg1(t) {
    client.get('/packages/b65b8ce2-29e7-4f63-b529-357f42bf0742',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        checkDate(t, obj);

        var expectedResults = {
            active: true,
            common_name: 'Test 1',
            cpu_burst_ratio: 0.5,
            cpu_cap: 200,
            default: false,
            description: '4GB RAM, 1 CPUs and bursting, and 131GB Disk.',
            fss: 200,
            group: 'Test',
            max_lwps: 4000,
            max_physical_memory: 4096,
            max_swap: 8192,
            min_platform: { '7.0': '20130917T001310Z' },
            name: 'test-1',
            networks: [ '9ec60129-9034-47b4-b111-3026f9b1a10f',
                        '5983940e-58a5-4543-b732-c689b1fe4c08' ],
            os: 'smartos',
            overprovision_cpu: 2,
            overprovision_io: 2,
            overprovision_memory: 1,
            overprovision_network: 4,
            overprovision_storage: 1,
            owner_uuids: [ '7b315468-c6be-46dc-b99b-9c1f59224693',
                           '1d09a48c-d1ee-42b0-a22f-0baf42daac2b',
                           '67e48d3a-35e7-40a3-beee-55a1e4588500',
                           'ec473ba8-0d5a-4000-9fc9-20b43397ac7d' ],
            parent: 'g3-standard-4-smartos',
            quota: 134144,
            ram_ratio: 3.990024938,
            traits: { ssd: true, img_mgmt: true },
            urn: 'sdc:test-1:1.0.0',
            uuid: 'b65b8ce2-29e7-4f63-b529-357f42bf0742',
            vcpus: 2,
            version: '1.0.0',
            zfs_io_priority: 100
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

function checkPkg2(t) {
    client.get('/packages/b8c43025-cfd9-446d-a871-4444c15d9648',
               function (err, req, res, obj) {
        t.ifError(err);
        t.equal(res.statusCode, 200);

        checkDate(t, obj);

        var expectedResults = {
            active: false,
            cpu_cap: 300,
            default: true,
            max_lwps: 2000,
            max_physical_memory: 2048,
            max_swap: 4096,
            name: 'test-2',
            quota: 81920,
            uuid: 'b8c43025-cfd9-446d-a871-4444c15d9648',
            version: '1.0.1',
            zfs_io_priority: 50
        };

        t.equivalent(obj, expectedResults);

        t.end();
    });
}

/*
 * This package is missing a required attribute (active), so shouldn't have
 * been imported.
 */

function checkPkg3(t) {
    client.get('/packages/487997df-a4da-4fd3-bcfc-98f100178241',
               function (err, req, res, obj) {
        t.equal(res.statusCode, 404);
        t.end();
    });
}

function checkDate(t, pkg) {
    var allowedDelta = 5000;

    var created = +new Date(pkg.created_at);
    var updated = +new Date(pkg.updated_at);

    t.ok(created - startTime < allowedDelta);
    t.ok(updated - startTime < allowedDelta);

    delete pkg.created_at;
    delete pkg.updated_at;
}
<|endoftext|>


<commit_before>"use strict";
const assert = require("assert");

const conversions = require("..");

function assertIs(actual, expected, message) {
    if (!Object.is(actual, expected)) {
        assert.fail(actual, expected, message, "is", assertIs);
    }
}

function commonTest(sut) {
    it("should return 0 for 0", () => {
        assertIs(sut(0), 0);
    });

    it("should return 0 for -0", () => {
        assertIs(sut(-0), 0);
    });

    it("should return 0 for -0 with [EnforceRange]", () => {
        assertIs(sut(-0, { enforceRange: true }), 0);
    });

    it("should return 0 for -0 with [Clamp]", () => {
        assertIs(sut(-0, { clamp: true }), 0);
    });

    it("should return 42 for 42", () => {
        assertIs(sut(42), 42);
    });

    it("should return 0 for null", () => {
        assertIs(sut(null), 0);
    });

    it("should return 0 for \"\"", () => {
        assertIs(sut(""), 0);
    });

    it("should return 0 for false", () => {
        assertIs(sut(0), 0);
    });

    it("should return 1 for true", () => {
        assertIs(sut(null), 0);
    });

    it("should return 0 for random whitespace", () => {
        assertIs(sut(" \t\n\t "), 0);
    });

    it("should return 0 for \"123, 123\"", () => {
        assertIs(sut("123,123"), 0);
    });
    it("should return 123 for \" 123 \"", () => {
        assertIs(sut(" 123 "), 123);
    });

    it("should return 123 for \" 123.400 \"", () => {
        assertIs(sut(" 123.400 "), 123);
    });
}

function commonTestNonFinite(sut) {
    it("should return 0 for NaN", () => {
        assertIs(sut(NaN), 0);
    });

    it("should return 0 for +Infinity", () => {
        assertIs(sut(Infinity), 0);
    });

    it("should return 0 for -Infinity", () => {
        assertIs(sut(Infinity), 0);
    });

    it("should throw for NaN with [EnforceRange]", () => {
        assert.throws(() => sut(NaN, { enforceRange: true }), TypeError);
    });

    it("should throw for +Infinity with [EnforceRange]", () => {
        assert.throws(() => sut(Infinity, { enforceRange: true }), TypeError);
    });

    it("should throw for -Infinity with [EnforceRange]", () => {
        assert.throws(() => sut(-Infinity, { enforceRange: true }), TypeError);
    });
}

function generateTests(sut, testCases, options, extraLabel) {
    extraLabel = extraLabel === undefined ? "" : " " + extraLabel;

    for (const testCase of testCases) {
        const input = testCase[0];
        const expected = testCase[1];

        if (expected === TypeError) {
            it("should throw for " + input + extraLabel, () => {
                assert.throws(() => sut(input, options), TypeError);
            });
        } else {
            it(`should return ${expected} for ${input}${extraLabel}`, () => {
                assertIs(sut(input, options), expected);
            });
        }
    }
}

describe("WebIDL byte type", () => {
    const sut = conversions.byte;

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-128, -128],
        [127, 127],
        [128, -128],
        [129, -127],
        [-129, 127],
        [-130, 126],
        [256, 0],
        [257, 1]
    ]);

    generateTests(sut, [
        [-128, -128],
        [-129, -128],
        [-10000, -128],
        [-Infinity, -128],
        [127, 127],
        [128, 127],
        [10000, 127],
        [Infinity, 127]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-128, -128],
        [-129, TypeError],
        [-10000, TypeError],
        [127, 127],
        [128, TypeError],
        [10000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL octet type", () => {
    const sut = conversions.octet;

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL short type", () => {
    const sut = conversions.short;

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL unsigned short type", () => {
    const sut = conversions["unsigned short"];

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL long type", () => {
    const sut = conversions.long;

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL unsigned long type", () => {
    const sut = conversions["unsigned long"];

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL long long type", () => {
    const sut = conversions["long long"];

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL unsigned long long type", () => {
    const sut = conversions["unsigned long long"];

    commonTest(sut);
    commonTestNonFinite(sut);
});
<commit_msg>Add tests for non-problematic integer types<commit_after>"use strict";
const assert = require("assert");

const conversions = require("..");

function assertIs(actual, expected, message) {
    if (!Object.is(actual, expected)) {
        assert.fail(actual, expected, message, "is", assertIs);
    }
}

function commonTest(sut) {
    it("should return 0 for 0", () => {
        assertIs(sut(0), 0);
    });

    it("should return 0 for -0", () => {
        assertIs(sut(-0), 0);
    });

    it("should return 0 for -0 with [EnforceRange]", () => {
        assertIs(sut(-0, { enforceRange: true }), 0);
    });

    it("should return 0 for -0 with [Clamp]", () => {
        assertIs(sut(-0, { clamp: true }), 0);
    });

    it("should return 42 for 42", () => {
        assertIs(sut(42), 42);
    });

    it("should return 0 for null", () => {
        assertIs(sut(null), 0);
    });

    it("should return 0 for \"\"", () => {
        assertIs(sut(""), 0);
    });

    it("should return 0 for false", () => {
        assertIs(sut(0), 0);
    });

    it("should return 1 for true", () => {
        assertIs(sut(null), 0);
    });

    it("should return 0 for random whitespace", () => {
        assertIs(sut(" \t\n\t "), 0);
    });

    it("should return 0 for \"123, 123\"", () => {
        assertIs(sut("123,123"), 0);
    });
    it("should return 123 for \" 123 \"", () => {
        assertIs(sut(" 123 "), 123);
    });

    it("should return 123 for \" 123.400 \"", () => {
        assertIs(sut(" 123.400 "), 123);
    });
}

function commonTestNonFinite(sut) {
    it("should return 0 for NaN", () => {
        assertIs(sut(NaN), 0);
    });

    it("should return 0 for +Infinity", () => {
        assertIs(sut(Infinity), 0);
    });

    it("should return 0 for -Infinity", () => {
        assertIs(sut(Infinity), 0);
    });

    it("should throw for NaN with [EnforceRange]", () => {
        assert.throws(() => sut(NaN, { enforceRange: true }), TypeError);
    });

    it("should throw for +Infinity with [EnforceRange]", () => {
        assert.throws(() => sut(Infinity, { enforceRange: true }), TypeError);
    });

    it("should throw for -Infinity with [EnforceRange]", () => {
        assert.throws(() => sut(-Infinity, { enforceRange: true }), TypeError);
    });
}

function generateTests(sut, testCases, options, extraLabel) {
    extraLabel = extraLabel === undefined ? "" : " " + extraLabel;

    for (const testCase of testCases) {
        const input = testCase[0];
        const expected = testCase[1];

        if (expected === TypeError) {
            it("should throw for " + input + extraLabel, () => {
                assert.throws(() => sut(input, options), TypeError);
            });
        } else {
            it(`should return ${expected} for ${input}${extraLabel}`, () => {
                assertIs(sut(input, options), expected);
            });
        }
    }
}

describe("WebIDL byte type", () => {
    const sut = conversions.byte;

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-128, -128],
        [127, 127],
        [128, -128],
        [129, -127],
        [-129, 127],
        [-130, 126],
        [256, 0],
        [257, 1]
    ]);

    generateTests(sut, [
        [-128, -128],
        [-129, -128],
        [-10000, -128],
        [-Infinity, -128],
        [127, 127],
        [128, 127],
        [10000, 127],
        [Infinity, 127]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-128, -128],
        [-129, TypeError],
        [-10000, TypeError],
        [127, 127],
        [128, TypeError],
        [10000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL octet type", () => {
    const sut = conversions.octet;

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-128, 128],
        [127, 127],
        [128, 128],
        [129, 129],
        [255, 255],
        [256, 0],
        [257, 1],
        [512, 0],
        [-1, 255],
        [-2, 254]
    ]);

    generateTests(sut, [
        [-1, 0],
        [-255, 0],
        [-256, 0],
        [-1000, 0],
        [-Infinity, 0],
        [127, 127],
        [128, 128],
        [255, 255],
        [256, 255],
        [10000, 255],
        [Infinity, 255]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-256, TypeError],
        [-1, TypeError],
        [0, 0],
        [255, 255],
        [256, TypeError],
        [10000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL short type", () => {
    const sut = conversions.short;

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-32768, -32768],
        [32767, 32767],
        [32768, -32768],
        [32769, -32767],
        [-32769, 32767],
        [-32770, 32766],
        [65536, 0],
        [65537, 1]
    ]);

    generateTests(sut, [
        [-32768, -32768],
        [-32769, -32768],
        [-1000000, -32768],
        [-Infinity, -32768],
        [32767, 32767],
        [32768, 32767],
        [1000000, 32767],
        [Infinity, 32767]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-32768, -32768],
        [-32769, TypeError],
        [-100000, TypeError],
        [32767, 32767],
        [32768, TypeError],
        [100000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL unsigned short type", () => {
    const sut = conversions["unsigned short"];

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-32768, 32768],
        [32767, 32767],
        [32768, 32768],
        [32769, 32769],
        [65535, 65535],
        [65536, 0],
        [65537, 1],
        [131072, 0],
        [-1, 65535],
        [-2, 65534]
    ]);

    generateTests(sut, [
        [-1, 0],
        [-32767, 0],
        [-32768, 0],
        [-100000, 0],
        [-Infinity, 0],
        [32767, 32767],
        [32768, 32768],
        [65535, 65535],
        [65536, 65535],
        [100000, 65535],
        [Infinity, 65535]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-65536, TypeError],
        [-1, TypeError],
        [0, 0],
        [65535, 65535],
        [65536, TypeError],
        [100000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL long type", () => {
    const sut = conversions.long;

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-2147483648, -2147483648],
        [2147483647, 2147483647],
        [2147483648, -2147483648],
        [2147483649, -2147483647],
        [-2147483649, 2147483647],
        [-2147483650, 2147483646],
        [4294967296, 0],
        [4294967297, 1]
    ]);

    generateTests(sut, [
        [-2147483648, -2147483648],
        [-2147483649, -2147483648],
        [-10000000000, -2147483648],
        [-Infinity, -2147483648],
        [2147483647, 2147483647],
        [2147483648, 2147483647],
        [10000000000, 2147483647],
        [Infinity, 2147483647]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-2147483648, -2147483648],
        [-2147483649, TypeError],
        [-10000000000, TypeError],
        [2147483647, 2147483647],
        [2147483648, TypeError],
        [10000000000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL unsigned long type", () => {
    const sut = conversions["unsigned long"];

    commonTest(sut);
    commonTestNonFinite(sut);

    generateTests(sut, [
        [-2147483648, 2147483648],
        [2147483647, 2147483647],
        [2147483648, 2147483648],
        [2147483649, 2147483649],
        [4294967295, 4294967295],
        [4294967296, 0],
        [4294967297, 1],
        [8589934592, 0],
        [-1, 4294967295],
        [-2, 4294967294]
    ]);

    generateTests(sut, [
        [-1, 0],
        [-4294967295, 0],
        [-4294967296, 0],
        [-10000000000, 0],
        [-Infinity, 0],
        [2147483647, 2147483647],
        [2147483648, 2147483648],
        [4294967295, 4294967295],
        [4294967296, 4294967295],
        [10000000000, 4294967295],
        [Infinity, 4294967295]
    ], { clamp: true }, "with [Clamp]");

    generateTests(sut, [
        [-4294967296, TypeError],
        [-1, TypeError],
        [0, 0],
        [4294967295, 4294967295],
        [4294967296, TypeError],
        [10000000000, TypeError]
    ], { enforceRange: true }, "with [EnforceRange]");
});

describe("WebIDL long long type", () => {
    const sut = conversions["long long"];

    commonTest(sut);
    commonTestNonFinite(sut);
});

describe("WebIDL unsigned long long type", () => {
    const sut = conversions["unsigned long long"];

    commonTest(sut);
    commonTestNonFinite(sut);
});
<|endoftext|>


<commit_before>import { assert } from 'chai';

import * as RA from '../src';
import element from './shared/element';
import args from './shared/arguments';
import Symbol from './shared/Symbol';

class Bar {
  constructor() {
    this.prop = 'value';
  }
}

describe('isNotPlainObj', function() {
  it('tests a value for POJO', function() {
    assert.isFalse(RA.isNotPlainObj({}));
    assert.isFalse(RA.isNotPlainObj({ prop: 'value' }));
    assert.isFalse(RA.isNotPlainObj({ constructor: Bar }));
    assert.isTrue(RA.isNotPlainObj(new Bar()));
    assert.isTrue(RA.isNotPlainObj(['a', 'b', 'c']));
  });

  it('tests a value with prototype of null', function() {
    assert.isFalse(RA.isNotPlainObj(Object.create(null)));

    const object = Object.create(null);
    object.constructor = Object.prototype.constructor;

    assert.isFalse(RA.isNotPlainObj(object));
  });

  it('tests a value with `valueOf` property', function() {
    assert.isFalse(RA.isNotPlainObj({ valueOf: 1 }));
  });

  it('test a value with custom prototype', function() {
    assert.isFalse(RA.isNotPlainObj(Object.create({ a: 3 })));
  });

  it('test a value that is DOM element', function() {
    if (element) {
      assert.isTrue(RA.isNotPlainObj(element));
    }
  });

  it('test a value for non-objects', function() {
    assert.isTrue(RA.isNotPlainObj(args));
    assert.isTrue(RA.isNotPlainObj(Error));
    assert.isTrue(RA.isNotPlainObj(Math));
    assert.isTrue(RA.isNotPlainObj(true));
    assert.isTrue(RA.isNotPlainObj('abc'));
  });

  it('test a value for Symbol', function() {
    if (Symbol) {
      assert.isTrue(RA.isNotPlainObj(Symbol.for('symbol')));
    }
  });
});

describe('isNotPlainObject', function() {
  it('tests an alias', function() {
    assert.strictEqual(RA.isNotPlainObj, RA.isNotPlainObject);
  });
});
<commit_msg>test(isNotPlainObj): add ramda placeholder and make tests consistent (#1220)<commit_after>import { assert } from 'chai';
import * as R from 'ramda';

import * as RA from '../src';
import element from './shared/element';
import args from './shared/arguments';
import Symbol from './shared/Symbol';

class Bar {
  constructor() {
    this.prop = 'value';
  }
}

describe('isNotPlainObj', function() {
  context('given a POJO value', function() {
    specify('should return false', function() {
      assert.isFalse(RA.isNotPlainObj({}));
      assert.isFalse(RA.isNotPlainObj({ prop: 'value' }));
      assert.isFalse(RA.isNotPlainObj({ constructor: Bar }));
    });
  });

  context('given a non-POJO value', function() {
    specify('should return true', function() {
      assert.isTrue(RA.isNotPlainObj(new Bar()));
      assert.isTrue(RA.isNotPlainObj(['a', 'b', 'c']));
    });
  });

  context('given a value with prototype of null', function() {
    specify('should return false', function() {
      assert.isFalse(RA.isNotPlainObj(Object.create(null)));

      const object = Object.create(null);
      object.constructor = Object.prototype.constructor;

      assert.isFalse(RA.isNotPlainObj(object));
    });
  });

  context('given a value with `valueOf` property', function() {
    specify('should return false', function() {
      assert.isFalse(RA.isNotPlainObj({ valueOf: 1 }));
    });
  });

  context('given a value with custom prototype', function() {
    specify('should return false', function() {
      assert.isFalse(RA.isNotPlainObj(Object.create({ a: 3 })));
    });
  });

  context('given a DOM elemen value', function() {
    specify('should return true', function() {
      if (element) {
        assert.isTrue(RA.isNotPlainObj(element));
      }
    });
  });

  context('given a non-object value', function() {
    specify('should return true', function() {
      assert.isTrue(RA.isNotPlainObj(args));
      assert.isTrue(RA.isNotPlainObj(Error));
      assert.isTrue(RA.isNotPlainObj(Math));
      assert.isTrue(RA.isNotPlainObj(true));
      assert.isTrue(RA.isNotPlainObj('abc'));
    });
  });

  context('given a symbol value', function() {
    specify('should return true', function() {
      if (Symbol !== 'undefined') {
        assert.isTrue(RA.isNotPlainObj(Symbol.for('symbol')));
      }
    });
  });

  it('should support placeholder to specify "gaps"', function() {
    const isNotPlainObj = RA.isNotPlainObj(R.__);

    assert.isTrue(isNotPlainObj(null));
  });
});

describe('isNotPlainObject', function() {
  it('should be an alias for isNotPlainObj', function() {
    assert.strictEqual(RA.isNotPlainObj, RA.isNotPlainObject);
  });
});
<|endoftext|>


<commit_before>import controller from './ngbBlastWholeGenomeView.controller';

export default {
    bindings: {
        chromosomes: '<',
        maxChrSize: '<',
    },
    restrict: 'EA',
    template: require('./ngbBlastWholeGenomeView.tpl.html'),
    controller: controller.UID,
};
<commit_msg>deleted unused code string<commit_after>import controller from './ngbBlastWholeGenomeView.controller';

export default {
    bindings: {
        chromosomes: '<',
    },
    restrict: 'EA',
    template: require('./ngbBlastWholeGenomeView.tpl.html'),
    controller: controller.UID,
};
<|endoftext|>


<commit_before>var suite = require('level-supports/test')

module.exports = function (test, testCommon) {
  test('setUp common', testCommon.setUp)

  suite(test, testCommon)

  test('manifest has status', function (t) {
    var db = testCommon.factory()
    t.is(db.supports.status, true)
    db.close(t.end.bind(t))
  })

  test('tearDown', testCommon.tearDown)
}
<commit_msg>Fix manifest-test to open & close its db (#352)<commit_after>var suite = require('level-supports/test')

module.exports = function (test, testCommon) {
  test('setUp common', testCommon.setUp)

  suite(test, testCommon)

  test('manifest has status', function (t) {
    var db = testCommon.factory()
    t.is(db.supports.status, true)

    // The semantics of not opening or closing a new db are unclear
    // atm, so let's open it before closing, like every other test.
    db.open(function (err) {
      t.ifError(err, 'no open error')
      db.close(t.end.bind(t))
    })
  })

  test('tearDown', testCommon.tearDown)
}
<|endoftext|>


<commit_before>/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2013 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/*global angular: false, moment: false, JSON: false */

angular.module('workflowRemover', [])
    .controller('MainCtrl', ['$scope', '$http', '$timeout',
        function ($scope, $http, $timeout) {

            $scope.app = {
                resource: '',
                running: false,
                refresh: ''
            };

            $scope.form = {
                payloads: [
                    { pattern: '' }
                ],
                models: [],
                statuses: []
            };

            $scope.status = {};

            $scope.formOptions = {};

            $scope.notifications = [];

            /* Methods */

            $scope.init = function () {
                $http({
                    method: 'GET',
                    url: encodeURI($scope.app.resource + '.init.json')
                }).
                    success(function (data, status, headers, config) {
                        $scope.formOptions = data.form || {};
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Unable to initialize form');
                    });

                $scope.getStatus();
            };

            $scope.getStatus = function () {
                $http({
                    method: 'GET',
                    url: encodeURI($scope.app.resource + '/status.json')
                }).
                    success(function (data, status, headers, config) {
                        var startedAtMoment, completedAtMoment;

                        $scope.status = data || {};

                        startedAtMoment = moment($scope.status.startedAt);

                        $scope.status.startedAt = startedAtMoment.format('MMMM Do YYYY, h:mm:ss a');

                        if ($scope.status.status === 'complete') {
                            $scope.app.running = false;

                            completedAtMoment = moment($scope.status.completedAt);

                            $scope.status.completedAt = completedAtMoment.format('MMMM Do YYYY, h:mm:ss a');
                            $scope.status.timeTaken = completedAtMoment.diff(startedAtMoment, 'seconds');

                        } else if ($scope.status.status === 'running') {
                            $scope.app.running = true;

                            $scope.status.timeTaken = moment().diff(startedAtMoment, 'seconds');

                            $scope.app.refresh = $timeout(function () {
                                $scope.getStatus();
                            }, 3000);
                        }
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Unable to initialize form');
                    });

                document.getElementById("scroll-top").scrollTop = 0;
            };

            $scope.remove = function () {
                var payload = angular.copy($scope.form);
                $scope.app.running = true;

                if (payload.olderThan) {
                    payload.olderThan = moment(payload.olderThan, "YYYY-MM-DD HH:MM").valueOf();
                }

                $http({
                    method: 'POST',
                    url: encodeURI($scope.app.resource + '.remove.json'),
                    data: 'params=' + JSON.stringify(payload),
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).
                    success(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.getStatus();
                        $scope.addNotification('info', 'INFO', 'Workflow removal completed');
                    }).
                    error(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.addNotification('error', 'ERROR', 'Workflow removal failed due to: ' + data);
                    });

                $scope.getStatus();
            };

            $scope.reset = function () {
                $http({
                    method: 'POST',
                    url: encodeURI($scope.app.resource + '/status'),
                    data: 'checkedCount@Delete' +
                        '&completedAt@Delete' +
                        '&count@Delete' +
                        '&initiatedBy@Delete' +
                        '&startedAt@Delete' +
                        '&status@Delete',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).
                    success(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.getStatus();
                        $scope.addNotification('info', 'INFO', 'Workflow removal status reset');
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Workflow removal status reset failed due to: ' + data);
                    });

                $scope.getStatus();
            };

            $scope.addNotification = function (type, title, message) {
                var timeout = 10000;

                if (type === 'success') {
                    timeout = timeout / 2;
                }

                $scope.notifications.push({
                    type: type,
                    title: title,
                    message: message
                });

                $timeout(function () {
                    $scope.notifications.shift();
                }, timeout);
            };

            /* Form Methods */
            $scope.toggleStatusSelection = function (status) {
                var idx = $scope.form.statuses.indexOf(status);

                if (idx > -1) {
                    $scope.form.statuses.splice(idx, 1);
                } else {
                    $scope.form.statuses.push(status);
                }
            };

            $scope.toggleModelSelection = function (workflowModelID) {
                var idx = $scope.form.models.indexOf(workflowModelID);

                if (idx > -1) {
                    $scope.form.models.splice(idx, 1);
                } else {
                    $scope.form.models.push(workflowModelID);
                }
            };
        }]);

<commit_msg>Workflow Removal - Handle error response<commit_after>/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2013 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/*global angular: false, moment: false, JSON: false */

angular.module('workflowRemover', [])
    .controller('MainCtrl', ['$scope', '$http', '$timeout',
        function ($scope, $http, $timeout) {

            $scope.app = {
                resource: '',
                running: false,
                refresh: ''
            };

            $scope.form = {
                payloads: [
                    { pattern: '' }
                ],
                models: [],
                statuses: []
            };

            $scope.status = {};

            $scope.formOptions = {};

            $scope.notifications = [];

            /* Methods */

            $scope.init = function () {
                $http({
                    method: 'GET',
                    url: encodeURI($scope.app.resource + '.init.json')
                }).
                    success(function (data, status, headers, config) {
                        $scope.formOptions = data.form || {};
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Unable to initialize form');
                    });

                $scope.getStatus();
            };

            $scope.getStatus = function () {
                $http({
                    method: 'GET',
                    url: encodeURI($scope.app.resource + '/status.json')
                }).
                    success(function (data, status, headers, config) {
                        var startedAtMoment, completedAtMoment;

                        $scope.status = data || {};

                        startedAtMoment = moment($scope.status.startedAt);

                        $scope.status.startedAt = startedAtMoment.format('MMMM Do YYYY, h:mm:ss a');

                        if ($scope.status.status !== 'running') {
                            $scope.app.running = false;

                            completedAtMoment = moment($scope.status.completedAt);

                            $scope.status.completedAt = completedAtMoment.format('MMMM Do YYYY, h:mm:ss a');
                            $scope.status.timeTaken = completedAtMoment.diff(startedAtMoment, 'seconds');

                        } else {
                            // Running
                            $scope.app.running = true;

                            $scope.status.timeTaken = moment().diff(startedAtMoment, 'seconds');

                            $scope.app.refresh = $timeout(function () {
                                $scope.getStatus();
                            }, 3000);
                        }
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Unable to initialize form');
                    });

                document.getElementById("scroll-top").scrollTop = 0;
            };

            $scope.remove = function () {
                var payload = angular.copy($scope.form);
                $scope.app.running = true;

                if (payload.olderThan) {
                    payload.olderThan = moment(payload.olderThan, "YYYY-MM-DD HH:MM").valueOf();
                }

                $http({
                    method: 'POST',
                    url: encodeURI($scope.app.resource + '.remove.json'),
                    data: 'params=' + JSON.stringify(payload),
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).
                    success(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.getStatus();
                        $scope.addNotification('info', 'INFO', 'Workflow removal completed');
                    }).
                    error(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.addNotification('error', 'ERROR', 'Workflow removal failed due to: ' + data);
                    });

                $scope.getStatus();
            };

            $scope.reset = function () {
                $http({
                    method: 'POST',
                    url: encodeURI($scope.app.resource + '/status'),
                    data: 'checkedCount@Delete' +
                        '&completedAt@Delete' +
                        '&count@Delete' +
                        '&initiatedBy@Delete' +
                        '&startedAt@Delete' +
                        '&status@Delete',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).
                    success(function (data, status, headers, config) {
                        $scope.app.running = false;
                        $scope.getStatus();
                        $scope.addNotification('info', 'INFO', 'Workflow removal status reset');
                    }).
                    error(function (data, status, headers, config) {
                        $scope.addNotification('error', 'ERROR', 'Workflow removal status reset failed due to: ' + data);
                    });

                $scope.getStatus();
            };

            $scope.addNotification = function (type, title, message) {
                var timeout = 10000;

                if (type === 'success') {
                    timeout = timeout / 2;
                }

                $scope.notifications.push({
                    type: type,
                    title: title,
                    message: message
                });

                $timeout(function () {
                    $scope.notifications.shift();
                }, timeout);
            };

            /* Form Methods */
            $scope.toggleStatusSelection = function (status) {
                var idx = $scope.form.statuses.indexOf(status);

                if (idx > -1) {
                    $scope.form.statuses.splice(idx, 1);
                } else {
                    $scope.form.statuses.push(status);
                }
            };

            $scope.toggleModelSelection = function (workflowModelID) {
                var idx = $scope.form.models.indexOf(workflowModelID);

                if (idx > -1) {
                    $scope.form.models.splice(idx, 1);
                } else {
                    $scope.form.models.push(workflowModelID);
                }
            };
        }]);

<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const google = require('googleapis');
const youtube = google.youtube('v3');
const User = require('../../models/user');
const config = require('../../../config');
const oauth2Client = require('../../../config/oauth2Client');
const Promise = require('bluebird');

const validateTokens = user =>
    _.isEmpty(user.youtube)
        ? Promise.reject({error: 'missing google oauth token. Please enable youtube in the website first'})
        : Promise.resolve(user.youtube);

const setCredentials = tokens => {
    oauth2Client.setCredentials(tokens);
    Promise.resolve(oauth2Client);
};

const replyErr = (err, reply) =>
    (err.code)
        ? reply({errors: err.errors}).code(403)
        : reply(err).code(404);

Promise.promisifyAll(youtube.playlists);

module.exports = {

    /**
     * GET
     * /api/youtube/playlists
     * shows all youtube playlists for user
     */
    playlists: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findByIdAsync(id)
                .then(validateTokens)
                .then(setCredentials)
                .then(auth => Promise.resolve({
                    auth: auth,
                    part: 'snippet',
                    mine: true
                })
                )
                .then(youtube.playlists.listAsync)
                .then(reply)
                .catch(e => replyErr(e, reply));
        }
    },

    /**
     * GET
     * /api/youtube/playlist/{playlistId}
     * shows youtube playlist by id
     */
    playlistById: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findById(id, (err, user) => {
                if (err) {
                    return reply({error: err});
                }

                const tokens = user.youtube;

                if (_.isEmpty(tokens)) {
                    return reply({error: 'missing google oauth token. Please enable youtube in the website first'});
                }

                oauth2Client.setCredentials(tokens);

                const params = {
                    auth: oauth2Client,
                    part: 'snippet',
                    playlistId: request.params.playlistId
                };

                youtube.playlistItems.list(params, (err, resp) => {
                    if (err) {
                        return reply({error: err});
                    }

                    return reply(resp);
                });
            });
        }
    },

    /**
     * POST
     * /api/youtube/playlist/{playlistId}/items
     * adds an item into a given playlist
     *
     * @param {string} request.params.playlistId playlistId to insert to
     * @param {string} request.payload.videoId
     */
    addPlaylistItem: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findById(id, (err, user) => {
                if (err) {
                    return reply({error: err});
                }

                const tokens = user.youtube;

                if (_.isEmpty(tokens)) {
                    return reply({error: 'missing google oauth token. Please enable youtube in the website first'});
                }

                oauth2Client.setCredentials(tokens);

                const params = {
                    auth: oauth2Client,
                    part: 'snippet',
                    resource: {
                        snippet: {
                            playlistId: request.params.playlistId,
                            resourceId: {
                                kind: 'youtube#video',
                                videoId: request.payload.videoId
                            }
                        }
                    }
                };

                youtube.playlistItems.insert(params, (err, data) => {
                    if (err) {
                        return reply({error: err});
                    }

                    //Note - to watch video , redirect to youtube.com/watch?v=<id>
                    //youtube.com/watch?v=-Fulz4ytZ54
                    return reply(data);
                });
            });
        }
    },

    /**
     * POST
     * /api/youtube/playlists
     * adds an item into a given playlist
     *
     * @param {object} snippet
     * @param {string} snippet.title
     * @param {string=} snippet.description
     * @param {string=} status.privacyStatus
     * @param {array=} snippet.tags[]
     * @param {string=} snippet.defaultLanguage
     * @param {string=} localizations.(key)
     * @param {string=} localizations.(key).title
     * @param {string=} localizations.(key).description
     */
    addPlaylist: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;
            const body = request.payload;

            User.findById(id, (err, user) => {
                if (err) {
                    return reply({error: err});
                }

                const tokens = user.youtube;

                if (_.isEmpty(tokens)) {
                    return reply({error: 'missing google oauth token. Please enable youtube in the website first'});
                }

                oauth2Client.setCredentials(tokens);

                const params = {
                    auth: oauth2Client,
                    part: 'snippet',
                    resource: {
                        snippet: body.snippet
                    }
                };

                youtube.playlists.insert(params, (err, data) => {
                    if (err) {
                        return reply({error: err});
                    }

                    //Note - to watch video , redirect to youtube.com/watch?v=<id>
                    //youtube.com/watch?v=-Fulz4ytZ54
                    return reply(data);
                });
            });
        }
    }
};
<commit_msg>refactoring remaining youtube api calls to use cleaner promise based code<commit_after>'use strict';

const _ = require('lodash');
const google = require('googleapis');
const youtube = google.youtube('v3');
const User = require('../../models/user');
const config = require('../../../config');
const Promise = require('bluebird');
const oauth2Client = require('../../../config/oauth2Client');

const validateTokens = user =>
    _.isEmpty(user.youtube)
        ? Promise.reject({error: 'missing google oauth token. Please enable youtube in the website first'})
        : Promise.resolve(user.youtube);

const setCredentials = tokens => {
    oauth2Client.setCredentials(tokens);
    return Promise.resolve(oauth2Client);
};

const replyErr = (err, reply) =>
    (err.code)
        ? reply({errors: err.errors}).code(403)
        : reply(err).code(404);

Promise.promisifyAll(youtube.playlists);
Promise.promisifyAll(youtube.playlistItems);

module.exports = {

    /**
     * GET
     * /api/youtube/playlists
     * shows all youtube playlists for user
     */
    playlists: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findByIdAsync(id)
                .then(validateTokens)
                .then(setCredentials)
                .then(auth => Promise.resolve({
                        auth: auth,
                        part: 'snippet',
                        mine: true
                    })
                )
                .then(youtube.playlists.listAsync)
                .then(reply)
                .catch(e => replyErr(e, reply));
        }
    },

    /**
     * GET
     * /api/youtube/playlist/{playlistId}
     * shows youtube playlist by id
     */
    playlistById: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findByIdAsync(id)
                .then(validateTokens)
                .then(setCredentials)
                .then(auth => Promise.resolve({
                        auth: auth,
                        part: 'snippet',
                        playlistId: request.params.playlistId
                    })
                )
                .then(youtube.playlistItems.listAsync)
                .then(reply)
                .catch(e => replyErr(e, reply));
        }
    },

    /**
     * POST
     * /api/youtube/playlist/{playlistId}/items
     * adds an item into a given playlist
     *
     * @param {string} request.params.playlistId playlistId to insert to
     * @param {string} request.payload.videoId
     */
    addPlaylistItem: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;

            User.findByIdAsync(id)
                .then(validateTokens)
                .then(setCredentials)
                .then(auth => Promise.resolve({
                        auth: auth,
                        part: 'snippet',
                        resource: {
                            snippet: {
                                playlistId: request.params.playlistId,
                                resourceId: {
                                    kind: 'youtube#video',
                                    videoId: request.payload.videoId
                                }
                            }
                        }
                    })
                )
                .then(youtube.playlistItems.insertAsync)
                .then(reply)
                .catch(e => replyErr(e, reply));
        }
    },

    /**
     * POST
     * /api/youtube/playlists
     * adds an item into a given playlist
     *
     * @param {object} snippet
     * @param {string} snippet.title
     * @param {string=} snippet.description
     * @param {string=} status.privacyStatus
     * @param {array=} snippet.tags[]
     * @param {string=} snippet.defaultLanguage
     * @param {string=} localizations.(key)
     * @param {string=} localizations.(key).title
     * @param {string=} localizations.(key).description
     */
    addPlaylist: {
        auth: 'jwt',
        handler: (request, reply) => {
            const id = request.auth.credentials._id;
            const body = request.payload;

            User.findByIdAsync(id)
                .then(validateTokens)
                .then(setCredentials)
                .then(auth => Promise.resolve({
                        auth: auth,
                        part: 'snippet',
                        resource: {
                            snippet: body.snippet
                        }
                    })
                )
                .then(youtube.playlists.insertAsync)
                .then(reply)
                .catch(e => replyErr(e, reply));
        }
    }
};
<|endoftext|>