<commit_before>'use strict'

import { app, BrowserWindow } from 'electron'
import OAuthTwitter from 'electron-oauth-twitter'
import config from 'config'
import storage from 'electron-json-storage-sync'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  const oauthInfo = storage.get('oauthInfo')

  if (oauthInfo.status && oauthInfo.data.oauth_access_token && oauthInfo.data.oauth_access_token_secret) {
    openWindow()
  } else {
    const twitterAuthWindow = new OAuthTwitter({
      key: config.get('consumerKey'),
      secret: config.get('consumerSecret')
    })

    twitterAuthWindow.startRequest()
      .then((res) => {
        const result = storage.set('oauthInfo', res)
        if (result.status) {
          openWindow()
        } else {
          console.error('Token save failed!')
        }
      })
      .catch((err) => {
        console.error(err, err.stack)
      })
  }
}

function openWindow () {
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 500
  })

  mainWindow.loadURL(winURL)
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
<commit_msg>Add json key<commit_after>'use strict'

import { app, BrowserWindow } from 'electron'
import OAuthTwitter from 'electron-oauth-twitter'
import config from 'config'
import storage from 'electron-json-storage-sync'

const OAUTH_TOKEN_KEY = 'oauthToken'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  const oauthInfo = storage.get(OAUTH_TOKEN_KEY)

  if (oauthInfo.status && oauthInfo.data.oauth_access_token && oauthInfo.data.oauth_access_token_secret) {
    openWindow()
  } else {
    const twitterAuthWindow = new OAuthTwitter({
      key: config.get('consumerKey'),
      secret: config.get('consumerSecret')
    })

    twitterAuthWindow.startRequest()
      .then((res) => {
        const result = storage.set(OAUTH_TOKEN_KEY, res)
        if (result.status) {
          openWindow()
        } else {
          console.error('Token save failed!')
        }
      })
      .catch((err) => {
        console.error(err, err.stack)
      })
  }
}

function openWindow () {
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 500
  })

  mainWindow.loadURL(winURL)
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
<|endoftext|>


<commit_before>/**
 * @file   modules/board/js/board.js
 * @author NHN (developers@xpressengine.com)
 * @brief  board 모듈의 javascript
 **/

/* 글쓰기 작성후 */
function completeDocumentInserted(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var category_srl = ret_obj['category_srl'];

    //alert(message);

    var url;
    if(!document_srl)
    {
        url = current_url.setQuery('mid',mid).setQuery('act','');
    }
    else
    {
        url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    }
    if(category_srl) url = url.setQuery('category',category_srl);
    location.href = url;
}

/* 글 삭제 */
function completeDeleteDocument(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('act','').setQuery('document_srl','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 검색 실행 */
function completeSearch(ret_obj, response_tags, params, fo_obj) {
    fo_obj.submit();
}

function completeVote(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    alert(message);
    location.href = location.href;
}

// 현재 페이지 reload
function completeReload(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];

    location.href = location.href;
}

/* 댓글 글쓰기 작성후 */
function completeInsertComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var comment_srl = ret_obj['comment_srl'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(comment_srl) url = url.setQuery('rnd',comment_srl)+"#comment_"+comment_srl;

    //alert(message);

    location.href = url;
}

/* 댓글 삭제 */
function completeDeleteComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 트랙백 삭제 */
function completeDeleteTrackback(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 카테고리 이동 */
function doChangeCategory() {
    var category_srl = jQuery('#board_category option:selected').val();
    location.href = decodeURI(current_url).setQuery('category',category_srl);
}

/* 스크랩 */
function doScrap(document_srl) {
    var params = new Array();
    params["document_srl"] = document_srl;
    exec_xml("member","procMemberScrapDocument", params, null);
}

jQuery(function($){
	$(document.body).click(function(e){
		var t=$(e.target),act,params={};

		if(t.parents('.layer_voted_member').length==0 && !t.is('.layer_voted_member')){
			$('.layer_voted_member').hide().remove();
		}

		if(!t.is('a[class^=voted_member_]')) return;

		var srl = parseInt(t.attr('class').replace(/[^0-9]/g,''));
		if(!srl) return;

		if(t.hasClass('comment')){
			act = 'comment.getCommentVotedMemberList';
			params = {'comment_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}else{
			act = 'document.getDocumentVotedMemberList';
			params = {'document_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}

		$.exec_json(act, params, function(data){
				var l = data.voted_member_list;
				var ul = [];

				if(l.length==0) return;

				$.each(l,function(){
					ul.push(this.nick_name);
				});

				t.after($('
')
					.addClass('layer_voted_member')
					.css({'position':'absolute','top':e.pageY+5,'left':e.pageX})
					.append('
'+ul.join('

')+'
'));
			});
	});
});

<commit_msg>r75 추가<commit_after>/**
 * @file   modules/board/js/board.js
 * @author NHN (developers@xpressengine.com)
 * @brief  board 모듈의 javascript
 **/

/* 글쓰기 작성후 */
function completeDocumentInserted(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var category_srl = ret_obj['category_srl'];

    //alert(message);

    var url;
    if(!document_srl)
    {
        url = current_url.setQuery('mid',mid).setQuery('act','');
    }
    else
    {
        url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    }
    if(category_srl) url = url.setQuery('category',category_srl);
    location.href = url;
}

/* 글 삭제 */
function completeDeleteDocument(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('act','').setQuery('document_srl','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 검색 실행 */
function completeSearch(ret_obj, response_tags, params, fo_obj) {
    fo_obj.submit();
}

function completeVote(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    alert(message);
    location.href = location.href;
}

// 현재 페이지 reload
function completeReload(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];

    location.href = location.href;
}

/* 댓글 글쓰기 작성후 */
function completeInsertComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var comment_srl = ret_obj['comment_srl'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(comment_srl) url = url.setQuery('rnd',comment_srl)+"#comment_"+comment_srl;

    //alert(message);

    location.href = url;
}

/* 댓글 삭제 */
function completeDeleteComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 트랙백 삭제 */
function completeDeleteTrackback(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* 카테고리 이동 */
function doChangeCategory() {
    var category_srl = jQuery('#board_category option:selected').val();
    location.href = decodeURI(current_url).setQuery('category',category_srl);
}

/* 스크랩 */
function doScrap(document_srl) {
    var params = new Array();
    params["document_srl"] = document_srl;
    exec_xml("member","procMemberScrapDocument", params, null);
}

jQuery(function($){
	$(document.body).click(function(e){
		var t=$(e.target),act,params={};

		if(t.parents('.layer_voted_member').length==0 && !t.is('.layer_voted_member')){
			$('.layer_voted_member').hide().remove();
		}

		if(!t.is('a[class^=voted_member_]')) return;

		var srl = parseInt(t.attr('class').replace(/[^0-9]/g,''));
		if(!srl) return;

		if(t.hasClass('comment')){
			act = 'comment.getCommentVotedMemberList';
			params = {'comment_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}else{
			act = 'document.getDocumentVotedMemberList';
			params = {'document_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}

		$.exec_json(act, params, function(data){
				var l = data.voted_member_list;
				var ul = [];

				if(!l || l.length==0) return;

				$.each(l,function(){
					ul.push(this.nick_name);
				});

				t.after($('
')
					.addClass('layer_voted_member')
					.css({'position':'absolute','top':e.pageY+5,'left':e.pageX})
					.append('
'+ul.join('

')+'
'));
			});
	});
});

<|endoftext|>


<commit_before>var path = require('path');
var sinon = require('sinon');
var shuffleArray = require('shuffle-array');

var InMemoryCompiler = require('webpack-toolkit/lib/InMemoryCompiler');
var MemoryFS = require('memory-fs');

var Docpack = require('../lib/docpack');
var HOOKS = require('../lib/hooks');
var DocpackPlugin = require('../lib/utils/DocpackPlugin');
var createPlugin = DocpackPlugin.create;
var Source = require('../lib/data/Source');

function noop() {}

function plugInHook(hook, handler) {
  return function(compiler) {
    compiler.plugin('compilation', function (compilation) {
      compilation.plugin(hook, handler);
    });
  }
}

function createSpiedPluginBody() {
  return sinon.spy((sources, done) => done(null, sources));
}

describe('Docpack', () => {
  describe('static props', () => {
    Docpack.should.have.property('API_VERSION').and.be.a('string');
    Docpack.should.have.property('HOOKS').and.be.eql(HOOKS);
    Docpack.should.have.property('defaultConfig').and.be.an('object');
  });

  describe('static methods', () => {
    describe('createPlugin()', () => {
      it('should exist', () => {
        Docpack.createPlugin.should.exist.and.be.a('function').and.be.equal(createPlugin);
      });
    });
  });

  describe('constructor()', () => {
    it('should allow to create instance via function call', () => {
      Docpack().should.be.instanceof(Docpack);
    });

    it('should properly set initial values', () => {
      var docpack = Docpack();
      docpack.should.have.property('config').and.be.eql(Docpack.defaultConfig);
      docpack.should.have.property('plugins').and.be.empty;
      docpack.should.have.property('sources').and.be.empty;
    });

    it('should assign passed config', () => {
      var cfg = {test: /\.jsx$/, exclude: false, foo: 'bar'};
      Docpack(cfg).should.have.property('config').and.be.eql(cfg);
    });
  });

  describe('use()', () => {
    it('should throws when wrong plugin type', () => {
      var docpack = Docpack();
      (function() { docpack.use( noop ) }).should.throws(TypeError);
      (function() { docpack.use( noop() ) }).should.throws(TypeError);
      (function() { docpack.use( function(){ return function() {} }() ) }).should.throws(TypeError);
      (function() { docpack.use( createPlugin()() ) }).should.not.throws();
    });

    it('should allow to inject in any hook (actually simple plugin creation) (hook:String, handler:Function)', () => {
      var docpack = Docpack();
      (function() { docpack.use(1, function(){}) }).should.throws(TypeError);
      (function() { docpack.use(function(){}, function(){}) }).should.throws(TypeError);
      (function() { docpack.use('qwe', function(){}) }).should.not.throws();
      docpack.plugins[0].should.be.instanceOf(DocpackPlugin);
    });

    it('should return docpack instance', () => {
      var Plugin = createPlugin();
      Docpack().use(Plugin()).should.be.instanceOf(Docpack);
    });

    it('should save plugins in `plugins` prop', () => {
      var docpack = Docpack();
      var Plugin1 = createPlugin();
      var Plugin2 = createPlugin();

      docpack.use(Plugin1()).use(Plugin2());
      docpack.plugins.should.be.lengthOf(2);
      docpack.plugins[0].should.be.instanceOf(Plugin1);
      docpack.plugins[1].should.be.instanceOf(Plugin2);
    });
  });

  describe('save()', function () {
    it('should save source', function () {
      var source = new Source({path: '/qwe', absolutePath: '/qwe', content: 'qwe'});
      var docpack = Docpack();

      docpack.save(source);
      docpack.sources.should.include(source).and.to.have.lengthOf(1);

      docpack.save(source);
      docpack.sources.should.include(source).and.to.have.lengthOf(1);
    })
  });

  describe('apply()', () => {
    it('should apply all plugins registered via `use()`', (done) => {
      var pluginBody = sinon.spy();
      var plugin = createPlugin(pluginBody)();

      InMemoryCompiler({plugins: [Docpack().use(plugin)]})
        .run()
        .then(compilation => {
          pluginBody.should.have.been.calledOne;
          done();
        })
        .catch(done);
    });

    describe('Hooks', () => {
      var fs;
      var compiler;

      beforeEach(() => {
        fs = new MemoryFS({
          'entry.js': new Buffer('')
        });

        compiler = InMemoryCompiler({
          context: '/',
          entry: './entry',
          plugins: []
        }, {inputFS: fs});
      });

      afterEach(() => {
        fs = compiler = null;
      });

      it('should invoke all handlers in proper order', (done) => {
        var docpack = Docpack();

        var expectedOrder = [
          HOOKS.BEFORE_EXTRACT,
          HOOKS.EXTRACT,
          HOOKS.AFTER_EXTRACT,
          HOOKS.BEFORE_GENERATE,
          HOOKS.GENERATE,
          HOOKS.AFTER_GENERATE
        ];
        var actualOrder = [];

        shuffleArray(expectedOrder, {copy: true})
          .map((hookName) => {
            //var Plugin = createPlugin(`plugin${hookName}`, plugInHook(hookName, (sources, done) => {
            //  actualOrder.push(hookName);
            //  done(null, sources);
            //}));

            var Plugin = createPlugin(plugInHook(hookName, (sources, done) => {
              actualOrder.push(hookName);
              done(null, sources);
            }));

            docpack.use(Plugin());
          });

        compiler.apply(docpack).run().then(c => {
          actualOrder.should.be.eql(expectedOrder);
          done();
        })
        .catch(done)
      });

      it('should invoke handlers properly', (done) => {
        var extractPlugin = createSpiedPluginBody();
        var generatePlugin = createSpiedPluginBody();

        var docpack = Docpack(/\.txt$/)
          .use(HOOKS.BEFORE_EXTRACT, extractPlugin)
          .use(HOOKS.BEFORE_GENERATE, generatePlugin);

        compiler.apply(docpack).run().then(c => {
          // Handlers attached to extract stage are not invoked if there is no files to process
          extractPlugin.should.have.not.been.called;

          // Handlers attached to generate stage invoked ALWAYS, even if there is no files to process
          generatePlugin.should.have.been.calledOnce;

          // When there is no files to process handlers in generate stage receives [] as first param
          generatePlugin.should.have.been.calledWith([]);
          done();
        })
        .catch(done);
      });

      it('should throw if invalid type returned from plugin', () => {
        var docpack = Docpack()
          .use(HOOKS.BEFORE_EXTRACT, (sources, done) => done(null, 'qwe'));

        compiler.apply(docpack);

        return compiler.run().should.be.rejectedWith('Plugins should return array');
      });

      it('should properly handle errors from plugins', () => {
        var docpack = Docpack()
          .use(HOOKS.EXTRACT, (sources, done) => done('Bad content'));

        return compiler.apply(docpack).run().should.be.rejectedWith('Bad content');
      });

      it('should save results after AFTER_EXTRACT', (done) => {
        var s;
        var docpack = Docpack();
        docpack.sources.should.be.lengthOf(0);

        docpack.use(HOOKS.AFTER_EXTRACT, (sources, done) => {
          s = sources;
          done(null, sources);
        });

        compiler.apply(docpack).run().then(c => {
          docpack.sources.should.be.lengthOf(1).and.be.eql(s);
          done();
        }).catch(done);

      });
    });
  });
});<commit_msg>Cleanup<commit_after>var path = require('path');
var sinon = require('sinon');
var shuffleArray = require('shuffle-array');

var InMemoryCompiler = require('webpack-toolkit/lib/InMemoryCompiler');
var MemoryFS = require('memory-fs');

var Docpack = require('../lib/docpack');
var HOOKS = require('../lib/hooks');
var DocpackPlugin = require('../lib/utils/DocpackPlugin');
var createPlugin = DocpackPlugin.create;
var Source = require('../lib/data/Source');

function noop() {}

function plugInHook(hook, handler) {
  return function(compiler) {
    compiler.plugin('compilation', function (compilation) {
      compilation.plugin(hook, handler);
    });
  }
}

function createSpiedPluginBody() {
  return sinon.spy((sources, done) => done(null, sources));
}

describe('Docpack', () => {
  describe('static props', () => {
    Docpack.should.have.property('API_VERSION').and.be.a('string');
    Docpack.should.have.property('HOOKS').and.be.eql(HOOKS);
    Docpack.should.have.property('defaultConfig').and.be.an('object');
  });

  describe('static methods', () => {
    describe('createPlugin()', () => {
      it('should exist', () => {
        Docpack.createPlugin.should.exist.and.be.a('function').and.be.equal(createPlugin);
      });
    });
  });

  describe('constructor()', () => {
    it('should allow to create instance via function call', () => {
      Docpack().should.be.instanceof(Docpack);
    });

    it('should properly set initial values', () => {
      var docpack = Docpack();
      docpack.should.have.property('config').and.be.eql(Docpack.defaultConfig);
      docpack.should.have.property('plugins').and.be.empty;
      docpack.should.have.property('sources').and.be.empty;
    });

    it('should assign passed config', () => {
      var cfg = {test: /\.jsx$/, exclude: false, foo: 'bar'};
      Docpack(cfg).should.have.property('config').and.be.eql(cfg);
    });
  });

  describe('use()', () => {
    it('should throws when wrong plugin type', () => {
      var docpack = Docpack();
      (function() { docpack.use( noop ) }).should.throws(TypeError);
      (function() { docpack.use( noop() ) }).should.throws(TypeError);
      (function() { docpack.use( function(){ return function() {} }() ) }).should.throws(TypeError);
      (function() { docpack.use( createPlugin()() ) }).should.not.throws();
    });

    it('should allow to inject in any hook (actually simple plugin creation) (hook:String, handler:Function)', () => {
      var docpack = Docpack();
      (function() { docpack.use(1, function(){}) }).should.throws(TypeError);
      (function() { docpack.use(function(){}, function(){}) }).should.throws(TypeError);
      (function() { docpack.use('qwe', function(){}) }).should.not.throws();
      docpack.plugins[0].should.be.instanceOf(DocpackPlugin);
    });

    it('should return docpack instance', () => {
      var Plugin = createPlugin();
      Docpack().use(Plugin()).should.be.instanceOf(Docpack);
    });

    it('should save plugins in `plugins` prop', () => {
      var docpack = Docpack();
      var Plugin1 = createPlugin();
      var Plugin2 = createPlugin();

      docpack.use(Plugin1()).use(Plugin2());
      docpack.plugins.should.be.lengthOf(2);
      docpack.plugins[0].should.be.instanceOf(Plugin1);
      docpack.plugins[1].should.be.instanceOf(Plugin2);
    });
  });

  describe('save()', function () {
    it('should save source', function () {
      var source = new Source({path: '/qwe', absolutePath: '/qwe', content: 'qwe'});
      var docpack = Docpack();

      docpack.save(source);
      docpack.sources.should.include(source).and.to.have.lengthOf(1);

      docpack.save(source);
      docpack.sources.should.include(source).and.to.have.lengthOf(1);
    })
  });

  describe('apply()', () => {
    it('should apply all plugins registered via `use()`', (done) => {
      var pluginBody = sinon.spy();
      var plugin = createPlugin(pluginBody)();

      InMemoryCompiler({plugins: [Docpack().use(plugin)]})
        .run()
        .then(compilation => {
          pluginBody.should.have.been.calledOne;
          done();
        })
        .catch(done);
    });

    describe('Hooks', () => {
      var fs;
      var compiler;

      beforeEach(() => {
        fs = new MemoryFS({
          'entry.js': new Buffer('')
        });

        compiler = InMemoryCompiler({
          context: '/',
          entry: './entry',
          plugins: []
        }, {inputFS: fs});
      });

      afterEach(() => {
        fs = compiler = null;
      });

      it('should invoke all handlers in proper order', (done) => {
        var docpack = Docpack();

        var expectedOrder = [
          HOOKS.BEFORE_EXTRACT,
          HOOKS.EXTRACT,
          HOOKS.AFTER_EXTRACT,
          HOOKS.BEFORE_GENERATE,
          HOOKS.GENERATE,
          HOOKS.AFTER_GENERATE
        ];
        var actualOrder = [];

        shuffleArray(expectedOrder, {copy: true})
          .map((hookName) => {
            var Plugin = createPlugin(plugInHook(hookName, (sources, done) => {
              actualOrder.push(hookName);
              done(null, sources);
            }));

            docpack.use(Plugin());
          });

        compiler.apply(docpack).run().then(c => {
          actualOrder.should.be.eql(expectedOrder);
          done();
        })
        .catch(done)
      });

      it('should invoke handlers properly', (done) => {
        var extractPlugin = createSpiedPluginBody();
        var generatePlugin = createSpiedPluginBody();

        var docpack = Docpack(/\.txt$/)
          .use(HOOKS.BEFORE_EXTRACT, extractPlugin)
          .use(HOOKS.BEFORE_GENERATE, generatePlugin);

        compiler.apply(docpack).run().then(c => {
          // Handlers attached to extract stage are not invoked if there is no files to process
          extractPlugin.should.have.not.been.called;

          // Handlers attached to generate stage invoked ALWAYS, even if there is no files to process
          generatePlugin.should.have.been.calledOnce;

          // When there is no files to process handlers in generate stage receives [] as first param
          generatePlugin.should.have.been.calledWith([]);
          done();
        })
        .catch(done);
      });

      it('should throw if invalid type returned from plugin', () => {
        var docpack = Docpack()
          .use(HOOKS.BEFORE_EXTRACT, (sources, done) => done(null, 'qwe'));

        compiler.apply(docpack);

        return compiler.run().should.be.rejectedWith('Plugins should return array');
      });

      it('should properly handle errors from plugins', () => {
        var docpack = Docpack()
          .use(HOOKS.EXTRACT, (sources, done) => done('Bad content'));

        return compiler.apply(docpack).run().should.be.rejectedWith('Bad content');
      });

      it('should save results after AFTER_EXTRACT', (done) => {
        var s;
        var docpack = Docpack();
        docpack.sources.should.be.lengthOf(0);

        docpack.use(HOOKS.AFTER_EXTRACT, (sources, done) => {
          s = sources;
          done(null, sources);
        });

        compiler.apply(docpack).run().then(c => {
          docpack.sources.should.be.lengthOf(1).and.be.eql(s);
          done();
        }).catch(done);

      });
    });
  });
});<|endoftext|>


<commit_before>/// <reference path="../typings/mocha/mocha.d.ts"/>
var oauth = require('../index');
var assert = require("assert");

String.prototype.contains = function(other){
    return this.indexOf(other) > -1;
};

describe('OAuth 2.0', function(){

    describe('Access header', function(){

        var header = oauth.access_header('token');

        it('should contain authorization', function(){
            assert.ok(header.Authorization);
        });

        it('should be bearer', function(){
            assert.ok(header.Authorization.contains('Bearer'));
        });

         it('should contain the token', function(){
            assert.ok(header.Authorization.contains('token'));
        });

        it('should be Bearer token', function(){
            assert.equal(header.Authorization, 'Bearer token');
        });

    });

    describe('Generate oauth authorize uri', function(){

        var uri = oauth.authorize_uri('client_id', 'redirect_uri', 'install_id');

        it('should contain all parameters', function(){
            assert.ok(uri.contains('=client_id'));
            assert.ok(uri.contains('=redirect_uri'));
            assert.ok(uri.contains('=install_id'));
        });
    });

    describe('Grant options', function(){

        var options = oauth.grant_request_options('client_id', 'client_secret', 'authorization_code', 'redirect_uri');

        describe('headers', function(){

            var headers = options.headers;

            it('should contain authorization', function(){
                assert.ok(headers.Authorization);
            });

            it('should be basic', function(){
                assert.ok(headers.Authorization.contains('Basic'));
            });

        });

        describe('url', function(){

            var url = options.url;

            it('should not be null', function(){
                assert.ok(url);
            });

            it('should be oauth', function(){
                assert.ok(url.contains('oauth'));
            });

        });

        describe('body', function(){

            var json = options.json;
            console.log(json);

            it('should not be json', function(){
                assert.ok(json);
            });

            it('should be have the proper values', function(){
                assert.equal(json.grant_type, 'authorization_code');
                assert.equal(json.code, 'authorization_code');
                assert.equal(json.redirect_uri, 'redirect_uri');
            });

        });
    });

});<commit_msg>adding a few more tests<commit_after>/// <reference path="../typings/mocha/mocha.d.ts"/>
var oauth = require('../index');
var assert = require("assert");

String.prototype.contains = function(other){
    return this.indexOf(other) > -1;
};

describe('OAuth 2.0', function(){

    describe('Access header', function(){

        var header = oauth.access_header('token');

        it('should contain authorization', function(){
            assert.ok(header.Authorization);
        });

        it('should be bearer', function(){
            assert.ok(header.Authorization.contains('Bearer'));
        });

         it('should contain the token', function(){
            assert.ok(header.Authorization.contains('token'));
        });

        it('should be Bearer token', function(){
            assert.equal(header.Authorization, 'Bearer token');
        });

    });

    describe('Generate oauth authorize uri', function(){

        var uri = oauth.authorize_uri('client_id', 'redirect_uri', 'install_id');

        it('should contain all parameters', function(){
            assert.ok(uri.contains('=client_id'));
            assert.ok(uri.contains('=redirect_uri'));
            assert.ok(uri.contains('=install_id'));
        });
    });

    describe('Grant options', function(){

        var options = oauth.grant_request_options('client_id', 'client_secret', 'authorization_code', 'redirect_uri');

        describe('headers', function(){

            var headers = options.headers;

            it('should contain authorization', function(){
                assert.ok(headers.Authorization);
            });

            it('should be basic', function(){
                assert.ok(headers.Authorization.contains('Basic'));
            });

        });

        describe('url', function(){

            var url = options.url;

            it('should not be null', function(){
                assert.ok(url);
            });

            it('should be oauth', function(){
                assert.ok(url.contains('oauth'));
            });

        });

        describe('body', function(){

            var json = options.json;
            console.log(json);

            it('should be json', function(){
                assert.ok(json);
            });

            it('should be have the proper values', function(){
                assert.equal(json.grant_type, 'authorization_code');
                assert.equal(json.code, 'authorization_code');
                assert.equal(json.redirect_uri, 'redirect_uri');
            });

        });
    });

    describe('Refresh options', function(){

        var options = oauth.refresh_request_options('client_id', 'client_secret', 'refresh_token', 'redirect_uri');

        describe('headers', function(){

            var headers = options.headers;

            it('should contain authorization', function(){
                assert.ok(headers.Authorization);
            });

            it('should be basic', function(){
                assert.ok(headers.Authorization.contains('Basic'));
            });

        });

        describe('url', function(){

            var url = options.url;

            it('should not be null', function(){
                assert.ok(url);
            });

            it('should be oauth', function(){
                assert.ok(url.contains('oauth'));
            });

        });

        describe('body', function(){

            var json = options.json;
            console.log(json);

            it('should be json', function(){
                assert.ok(json);
            });

            it('should be have the proper values', function(){
                assert.equal(json.grant_type, 'refresh_token');
                assert.equal(json.refresh_token, 'refresh_token');
                assert.equal(json.scope, 'full');
                assert.equal(json.redirect_uri, 'redirect_uri');
            });

        });
    });

});<|endoftext|>


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

describe("export declarations", () => {
  it("should allow * exports", () => {
    import def, {
      a, b, c as d,
    } from "./export-all.js";

    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(d, "c");
    assert.strictEqual(def, "default");
  });

  it("should allow re-exporting import * alongside export *", () => {
    import {
      Abc, d, e, f,
    } from "./export-all-multiple.js";

    assert.strictEqual(Abc.a, "a");
    assert.strictEqual(Abc.b, "b");
    assert.strictEqual(Abc.c, "c");
    assert.strictEqual(d, "d");
    assert.strictEqual(e, "e");
    assert.strictEqual(f, "f");
  });

  it("should tolerate mutual * exports", () => {
    import { a as aa, b as ab } from "./export/all-mutual-a.js";
    import { a as ba, b as bb } from "./export/all-mutual-b.js";
    assert.strictEqual(aa, "a");
    assert.strictEqual(ab, "b");
    assert.strictEqual(ba, "a");
    assert.strictEqual(bb, "b");
  });

  it("should allow named re-exports", () => {
    import { a, c, v, si } from "./export-some.js";
    assert.strictEqual(a, "a");
    assert.strictEqual(c(), "c");
    assert.strictEqual(v, "b");
    assert.strictEqual(si, "cee");
  });

  it("should be able to contain import declarations", () => {
    import { outer } from "./nested";
    assert.deepEqual(outer(), ["a", "b", "c"]);
  });

  it("should support default declarations", () => {
    import g, { check } from "./default-function";
    check(g);
  });

  it("should support default expressions", () => {
    import count from "./default-expression";
    assert.strictEqual(count, 1);
  });

  it("should be able to invoke setters later", (done) => {
    import def, {
      val,
      exportAgain,
      exportYetAgain,
      oneLastExport
    } from "./export/later";

    assert.strictEqual(def, "default-1");
    assert.strictEqual(val, "value-1");

    exportAgain();
    assert.strictEqual(def, "default-2");
    assert.strictEqual(val, "value-2");

    exportYetAgain();
    assert.strictEqual(def, "default-3");
    assert.strictEqual(val, "value-2");

    setTimeout(() => {
      oneLastExport();
      assert.strictEqual(def, "default-3");
      assert.strictEqual(val, "value-3");
      done();
    }, 0);
  });

  import { Script } from "vm";

  let canUseClasses = false;
  let canUseLetConst = false;
  let canUseDestructuring = false;

  try {
    // Test if Node supports class syntax.
    new Script("class A {}");
    canUseClasses = true;
  } catch (e) {}

  try {
    // Test if Node supports block declaration syntax.
    new Script("let x; const y = 1234");
    canUseLetConst = true;
  } catch (e) {}

  try {
    // Test if Node supports destructuring declarations.
    new Script("const { x, y } = {}");
    canUseDestructuring = true;
  } catch (e) {}

  it("should support all default syntax", () => {
    import number from "./export/default/number";
    assert.strictEqual(number, 42);

    import object from "./export/default/object";
    assert.deepEqual(object, {
      foo: 42
    });

    import array from "./export/default/array";
    assert.deepEqual(array, [1, 2, 3]);

    import func from "./export/default/function";
    assert.strictEqual(func(), func);

    import anonFunc from "./export/default/anon-function";
    assert.strictEqual(anonFunc(3), 4);

    import ident from "./export/default/identifier";
    assert.strictEqual(ident, 42);

    if (canUseClasses) {
      import Anon from "./export/default/anon-class";
      assert.strictEqual(new Anon(1234).value, 1234);

      import Named from "./export/default/named-class";
      assert.strictEqual(new Named(56, 78).sum, 56 + 78);
    }
  });

  it("should support basic declaration syntax", () => {
    import { a, b, c, d } from "./export/declarations/basic";

    assert.strictEqual(a, 1);
    assert.strictEqual(b(), d);
    assert.strictEqual(c, "c");
    assert.strictEqual(d(), b);
  });

  (canUseLetConst ? it : xit)(
    "should support block declaration syntax", () => {
    import { a, b, c } from "./export/declarations/block";

    assert.strictEqual(a, 1);
    assert.strictEqual(b, 2);
    assert.strictEqual(c, 3);
  });

  it("should support all named export syntax", () => {
    const exp = require("./export/names");

    assert.strictEqual(exp.foo, "foo");
    assert.strictEqual(exp.bar, "bar");
    assert.strictEqual(exp.baz, "baz");
    assert.strictEqual(exp.foo2, "foo");
    assert.strictEqual(exp.foo3, "foo");
    assert.strictEqual(exp.baz2, "baz");
    assert.strictEqual(exp.default, "foo");

    import foo from "./export/names";
    assert.strictEqual(foo, "foo");
  });

  it("should tolerate one-to-many renamed exports", () => {
    import { x, y, append } from "./export/renamed";

    assert.strictEqual(x, y);
    assert.strictEqual(x, "a");

    assert.strictEqual(append("b"), "ab");

    assert.strictEqual(x, y);
    assert.strictEqual(x, "ab");

    assert.strictEqual(append("c"), "abc");

    assert.strictEqual(x, y);
    assert.strictEqual(x, "abc");
  });

  it("should support all export-from syntax", () => {
    import def, { a, b, c, ay, bee, foo } from "./export/from";

    assert.strictEqual(def, "a");
    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(c, "c");
    assert.strictEqual(ay, "a");
    assert.strictEqual(bee, "b");
    assert.deepEqual(foo, {
      a: "a",
      b: "b",
      c: "c"
    });
  });

  it("should support export-from extensions", () => {
    import {
      def1, def2, def3,
      ns1, ns2, ns3,
      a, b, c, d
    } from "./export/from-extensions";

    import def, {
      a as _a,
      b as _b,
      b as _c,
      c as _d,
    } from "./abc";

    assert.strictEqual(def, def1);
    assert.strictEqual(def, def2);
    assert.strictEqual(def, def3);

    function checkNS(ns) {
      assert.deepEqual(ns, def);
      assert.notStrictEqual(ns, def);
    }

    checkNS(ns1);
    checkNS(ns2);
    checkNS(ns3);

    assert.strictEqual(a, _a);
    assert.strictEqual(b, _b);
    assert.strictEqual(c, _c);
    assert.strictEqual(d, _d);
  });

  it("should support export { default } from ... syntax", () => {
    import object from "./export/default/from";
    assert.deepEqual(object, {
      foo: 42
    });
  });

  it("should support switch-case nested imports", () => {
    assert.strictEqual(typeof x, "undefined");

    for (let i = 0; i < 2; ++i) {
      switch (i) {
      case 0:
        import { a as x } from "./abc";
        break;
      case 1:
        import { b as x } from "./abc";
        break;
      }

      assert.strictEqual(x, i ? "b": "a");
    }

    assert.strictEqual(x, "b");
  });

  (canUseDestructuring ? it : xit)(
    "should support destructuring declarations", () => {
    import { a, c as b, d, x, y, rest } from "./export/destructuring.js";

    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(d, 1234);
    assert.strictEqual(x, 1);
    assert.strictEqual(y, 2);
    assert.deepEqual(rest, [a, b, d]);
  });

  (canUseDestructuring ? it : xit)(
  "should invoke destructuring setters later", () => {
    import { x, y, swap } from "./export/swap-later.js";
    assert.strictEqual(x, 1);
    assert.strictEqual(y, 2);
    swap();
    assert.strictEqual(x, 2);
    assert.strictEqual(y, 1);
  });

  it("should not crash on array patterns with holes", () => {
    import { a, b, update } from "./export/array-pattern-holes.js";
    assert.strictEqual(a, 1);
    assert.strictEqual(b, 2);
    assert.strictEqual(update(3, 4, 5), 8);
    assert.strictEqual(a, 3);
    assert.strictEqual(b, 5);
  });
});
<commit_msg>Make array patterns with holes test pass in Node 4.<commit_after>const assert = require("assert");

describe("export declarations", () => {
  it("should allow * exports", () => {
    import def, {
      a, b, c as d,
    } from "./export-all.js";

    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(d, "c");
    assert.strictEqual(def, "default");
  });

  it("should allow re-exporting import * alongside export *", () => {
    import {
      Abc, d, e, f,
    } from "./export-all-multiple.js";

    assert.strictEqual(Abc.a, "a");
    assert.strictEqual(Abc.b, "b");
    assert.strictEqual(Abc.c, "c");
    assert.strictEqual(d, "d");
    assert.strictEqual(e, "e");
    assert.strictEqual(f, "f");
  });

  it("should tolerate mutual * exports", () => {
    import { a as aa, b as ab } from "./export/all-mutual-a.js";
    import { a as ba, b as bb } from "./export/all-mutual-b.js";
    assert.strictEqual(aa, "a");
    assert.strictEqual(ab, "b");
    assert.strictEqual(ba, "a");
    assert.strictEqual(bb, "b");
  });

  it("should allow named re-exports", () => {
    import { a, c, v, si } from "./export-some.js";
    assert.strictEqual(a, "a");
    assert.strictEqual(c(), "c");
    assert.strictEqual(v, "b");
    assert.strictEqual(si, "cee");
  });

  it("should be able to contain import declarations", () => {
    import { outer } from "./nested";
    assert.deepEqual(outer(), ["a", "b", "c"]);
  });

  it("should support default declarations", () => {
    import g, { check } from "./default-function";
    check(g);
  });

  it("should support default expressions", () => {
    import count from "./default-expression";
    assert.strictEqual(count, 1);
  });

  it("should be able to invoke setters later", (done) => {
    import def, {
      val,
      exportAgain,
      exportYetAgain,
      oneLastExport
    } from "./export/later";

    assert.strictEqual(def, "default-1");
    assert.strictEqual(val, "value-1");

    exportAgain();
    assert.strictEqual(def, "default-2");
    assert.strictEqual(val, "value-2");

    exportYetAgain();
    assert.strictEqual(def, "default-3");
    assert.strictEqual(val, "value-2");

    setTimeout(() => {
      oneLastExport();
      assert.strictEqual(def, "default-3");
      assert.strictEqual(val, "value-3");
      done();
    }, 0);
  });

  import { Script } from "vm";

  let canUseClasses = false;
  let canUseLetConst = false;
  let canUseDestructuring = false;

  try {
    // Test if Node supports class syntax.
    new Script("class A {}");
    canUseClasses = true;
  } catch (e) {}

  try {
    // Test if Node supports block declaration syntax.
    new Script("let x; const y = 1234");
    canUseLetConst = true;
  } catch (e) {}

  try {
    // Test if Node supports destructuring declarations.
    new Script("const { x, y } = {}");
    canUseDestructuring = true;
  } catch (e) {}

  it("should support all default syntax", () => {
    import number from "./export/default/number";
    assert.strictEqual(number, 42);

    import object from "./export/default/object";
    assert.deepEqual(object, {
      foo: 42
    });

    import array from "./export/default/array";
    assert.deepEqual(array, [1, 2, 3]);

    import func from "./export/default/function";
    assert.strictEqual(func(), func);

    import anonFunc from "./export/default/anon-function";
    assert.strictEqual(anonFunc(3), 4);

    import ident from "./export/default/identifier";
    assert.strictEqual(ident, 42);

    if (canUseClasses) {
      import Anon from "./export/default/anon-class";
      assert.strictEqual(new Anon(1234).value, 1234);

      import Named from "./export/default/named-class";
      assert.strictEqual(new Named(56, 78).sum, 56 + 78);
    }
  });

  it("should support basic declaration syntax", () => {
    import { a, b, c, d } from "./export/declarations/basic";

    assert.strictEqual(a, 1);
    assert.strictEqual(b(), d);
    assert.strictEqual(c, "c");
    assert.strictEqual(d(), b);
  });

  (canUseLetConst ? it : xit)(
    "should support block declaration syntax", () => {
    import { a, b, c } from "./export/declarations/block";

    assert.strictEqual(a, 1);
    assert.strictEqual(b, 2);
    assert.strictEqual(c, 3);
  });

  it("should support all named export syntax", () => {
    const exp = require("./export/names");

    assert.strictEqual(exp.foo, "foo");
    assert.strictEqual(exp.bar, "bar");
    assert.strictEqual(exp.baz, "baz");
    assert.strictEqual(exp.foo2, "foo");
    assert.strictEqual(exp.foo3, "foo");
    assert.strictEqual(exp.baz2, "baz");
    assert.strictEqual(exp.default, "foo");

    import foo from "./export/names";
    assert.strictEqual(foo, "foo");
  });

  it("should tolerate one-to-many renamed exports", () => {
    import { x, y, append } from "./export/renamed";

    assert.strictEqual(x, y);
    assert.strictEqual(x, "a");

    assert.strictEqual(append("b"), "ab");

    assert.strictEqual(x, y);
    assert.strictEqual(x, "ab");

    assert.strictEqual(append("c"), "abc");

    assert.strictEqual(x, y);
    assert.strictEqual(x, "abc");
  });

  it("should support all export-from syntax", () => {
    import def, { a, b, c, ay, bee, foo } from "./export/from";

    assert.strictEqual(def, "a");
    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(c, "c");
    assert.strictEqual(ay, "a");
    assert.strictEqual(bee, "b");
    assert.deepEqual(foo, {
      a: "a",
      b: "b",
      c: "c"
    });
  });

  it("should support export-from extensions", () => {
    import {
      def1, def2, def3,
      ns1, ns2, ns3,
      a, b, c, d
    } from "./export/from-extensions";

    import def, {
      a as _a,
      b as _b,
      b as _c,
      c as _d,
    } from "./abc";

    assert.strictEqual(def, def1);
    assert.strictEqual(def, def2);
    assert.strictEqual(def, def3);

    function checkNS(ns) {
      assert.deepEqual(ns, def);
      assert.notStrictEqual(ns, def);
    }

    checkNS(ns1);
    checkNS(ns2);
    checkNS(ns3);

    assert.strictEqual(a, _a);
    assert.strictEqual(b, _b);
    assert.strictEqual(c, _c);
    assert.strictEqual(d, _d);
  });

  it("should support export { default } from ... syntax", () => {
    import object from "./export/default/from";
    assert.deepEqual(object, {
      foo: 42
    });
  });

  it("should support switch-case nested imports", () => {
    assert.strictEqual(typeof x, "undefined");

    for (let i = 0; i < 2; ++i) {
      switch (i) {
      case 0:
        import { a as x } from "./abc";
        break;
      case 1:
        import { b as x } from "./abc";
        break;
      }

      assert.strictEqual(x, i ? "b": "a");
    }

    assert.strictEqual(x, "b");
  });

  (canUseDestructuring ? it : xit)(
    "should support destructuring declarations", () => {
    import { a, c as b, d, x, y, rest } from "./export/destructuring.js";

    assert.strictEqual(a, "a");
    assert.strictEqual(b, "b");
    assert.strictEqual(d, 1234);
    assert.strictEqual(x, 1);
    assert.strictEqual(y, 2);
    assert.deepEqual(rest, [a, b, d]);
  });

  (canUseDestructuring ? it : xit)(
  "should invoke destructuring setters later", () => {
    import { x, y, swap } from "./export/swap-later.js";
    assert.strictEqual(x, 1);
    assert.strictEqual(y, 2);
    swap();
    assert.strictEqual(x, 2);
    assert.strictEqual(y, 1);
  });

  (canUseDestructuring ? it : xit)(
  "should not crash on array patterns with holes", () => {
    import { a, b, update } from "./export/array-pattern-holes.js";
    assert.strictEqual(a, 1);
    assert.strictEqual(b, 2);
    assert.strictEqual(update(3, 4, 5), 8);
    assert.strictEqual(a, 3);
    assert.strictEqual(b, 5);
  });
});
<|endoftext|>


<commit_before>// Load in dependencies
var childProcess = require('child_process');
var path = require('path');
var expect = require('chai').expect;
var sinon = require('sinon');
var wrench = require('wrench');
var Foundry = require('../bin/foundry');

// Stop exec calls from happening
var shell = require('shelljs');
var originalExec = shell.exec;
shell.exec = shell.complaintExec = function () {
  throw new Error('`shell.exec` was being called with ' + JSON.stringify(arguments));
};

// Stop childProcess exec and spawn calls too unless people opt in to our methods
var iKnowWhatIAmDoingSpawn = childProcess.spawn;
childProcess.spawn = childProcess.complaintSpawn = function () {
  throw new Error('`childProcess.spawn` was being called with ' + JSON.stringify(arguments));
};
var iKnowWhatIAmDoingExec = childProcess.exec;
childProcess.exec = childProcess.complaintExec = function () {
  throw new Error('`childProcess.exec` was being called with ' + JSON.stringify(arguments));
};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS

var tmp = shell.tempdir();
var fixtureDir = path.join(tmp, 'foundry_test');
before(function deleteFixtureDir (done) {
  wrench.rmdirRecursive(fixtureDir, false, function (err) {
    done();
  });
});
before(function createFixtureDir () {
  // DEV: There is no asynchronous flavor. We could use mkdirp but this is fine.
  wrench.mkdirSyncRecursive(fixtureDir);
});
before(function goToFixtureDir () {
  process.chdir(fixtureDir);
});

// TODO: Use this... similar to that of sexy-bash-prompt
function fixtureDir(name) {
  before(function copyFixtures (done) {

  });
  // TODO: Perform this
  // before(function moveDotgitToGit (done) {

  // });
}

function stubShellExec() {
  before(function () {
    this.execStub = sinon.stub(shell, 'exec', function () {
      return {};
    });
  });
  after(function () {
    this.execStub.restore();
  });
}

function allowShellExec(fn, cb) {
  shell.exec = originalExec;
  fn(function (err) {
    shell.exec = shell.complaintExec;
    cb(err);
  });
}
function allowChildExec(fn, cb) {
  childProcess.exec = iKnowWhatIAmDoingExec;
  fn(function (err) {
    childProcess.exec = childProcess.complaintExec;
    cb(err);
  });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder () {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirSyncRecursive(this.gitDir);
    });

    // TODO: Use premade git directory a la sexy-bash-prompt
    before(function initializeGitFolder (done) {
      process.chdir(this.gitDir);
      iKnowWhatIAmDoingExec('git init', function (err, stdout, stderr) {
        if (err) { return done(err); }
        iKnowWhatIAmDoingExec('touch a', function (err, stdout, stderr) {
          if (err) { return done(err); }
          iKnowWhatIAmDoingExec('git add -A', function (err, stdout, stderr) {
            if (err) { return done(err); }
            iKnowWhatIAmDoingExec('git commit -m "Initial commit =D"', function (err, stdout, stderr) {
              done(err);
            });
          });
        });
      });
    });

    before(function release (done) {
      // TODO: Consider `allow` function
      allowShellExec(function (cb1) {
        allowChildExec(function (cb2) {
          var program = new Foundry();
          program.parse(['node', '/usr/bin/foundry', 'release', '0.1.0']);
          // TODO: Figure out how to hook in better (program.parse does not provide a callback hook)
          // TODO: Maybe an EventEmitter? (error, end)
          setTimeout(cb2, 100);
        }, cb1);
      }, done);
    });

    it('adds a git tag', function (done) {
      iKnowWhatIAmDoingExec('git tag', function (err, stdout, stderr) {
        if (err) {
          return done(err);
        }
        expect(stdout).to.equal('0.1.0\n');
        done();
      });
    });
  });
});
<commit_msg>Updated allow TODO note<commit_after>// Load in dependencies
var childProcess = require('child_process');
var path = require('path');
var expect = require('chai').expect;
var sinon = require('sinon');
var wrench = require('wrench');
var Foundry = require('../bin/foundry');

// Stop exec calls from happening
var shell = require('shelljs');
var originalExec = shell.exec;
shell.exec = shell.complaintExec = function () {
  throw new Error('`shell.exec` was being called with ' + JSON.stringify(arguments));
};

// Stop childProcess exec and spawn calls too unless people opt in to our methods
var iKnowWhatIAmDoingSpawn = childProcess.spawn;
childProcess.spawn = childProcess.complaintSpawn = function () {
  throw new Error('`childProcess.spawn` was being called with ' + JSON.stringify(arguments));
};
var iKnowWhatIAmDoingExec = childProcess.exec;
childProcess.exec = childProcess.complaintExec = function () {
  throw new Error('`childProcess.exec` was being called with ' + JSON.stringify(arguments));
};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS

var tmp = shell.tempdir();
var fixtureDir = path.join(tmp, 'foundry_test');
before(function deleteFixtureDir (done) {
  wrench.rmdirRecursive(fixtureDir, false, function (err) {
    done();
  });
});
before(function createFixtureDir () {
  // DEV: There is no asynchronous flavor. We could use mkdirp but this is fine.
  wrench.mkdirSyncRecursive(fixtureDir);
});
before(function goToFixtureDir () {
  process.chdir(fixtureDir);
});

// TODO: Use this... similar to that of sexy-bash-prompt
function fixtureDir(name) {
  before(function copyFixtures (done) {

  });
  // TODO: Perform this
  // before(function moveDotgitToGit (done) {

  // });
}

function stubShellExec() {
  before(function () {
    this.execStub = sinon.stub(shell, 'exec', function () {
      return {};
    });
  });
  after(function () {
    this.execStub.restore();
  });
}

function allowShellExec(fn, cb) {
  shell.exec = originalExec;
  fn(function (err) {
    shell.exec = shell.complaintExec;
    cb(err);
  });
}
function allowChildExec(fn, cb) {
  childProcess.exec = iKnowWhatIAmDoingExec;
  fn(function (err) {
    childProcess.exec = childProcess.complaintExec;
    cb(err);
  });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder () {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirSyncRecursive(this.gitDir);
    });

    // TODO: Use premade git directory a la sexy-bash-prompt
    before(function initializeGitFolder (done) {
      process.chdir(this.gitDir);
      iKnowWhatIAmDoingExec('git init', function (err, stdout, stderr) {
        if (err) { return done(err); }
        iKnowWhatIAmDoingExec('touch a', function (err, stdout, stderr) {
          if (err) { return done(err); }
          iKnowWhatIAmDoingExec('git add -A', function (err, stdout, stderr) {
            if (err) { return done(err); }
            iKnowWhatIAmDoingExec('git commit -m "Initial commit =D"', function (err, stdout, stderr) {
              done(err);
            });
          });
        });
      });
    });

    before(function release (done) {
      // TODO: Consider `allow` function which can enable both of these
      allowShellExec(function (cb1) {
        allowChildExec(function (cb2) {
          var program = new Foundry();
          program.parse(['node', '/usr/bin/foundry', 'release', '0.1.0']);
          // TODO: Figure out how to hook in better (program.parse does not provide a callback hook)
          // TODO: Maybe an EventEmitter? (error, end)
          setTimeout(cb2, 100);
        }, cb1);
      }, done);
    });

    it('adds a git tag', function (done) {
      iKnowWhatIAmDoingExec('git tag', function (err, stdout, stderr) {
        if (err) {
          return done(err);
        }
        expect(stdout).to.equal('0.1.0\n');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var Code = require('code');
var Lab = require('lab');
var University = require('../lib');
var Path = require('path');
var Config = require('../lib/config');
var Good = require('good');
var GoodMonitor = require('../lib/good-monitor');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var expect = Code.expect;
var it = lab.test;

describe('good-monitor', function () {

    it('monitor registration failed', { parallel: false }, function (done) {

        var orig = Good.register;

        Good.register = function (plugin, options, next) {

            Good.register = orig;
            return next(new Error('fail'));
        };

        Good.register.attributes = {
            name: 'fake good'
        };

        University.init(internals.manifest, internals.composeOptions, function (err, server) {

            expect(err).to.exist();
            expect(err.message).to.equal('fail');
            done();
        });
    });
});

internals.manifest = {
    connections: [
        {
            host: 'localhost',
            port: 0,
            labels: ['web']
        },
        {
            host: 'localhost',
            port: 0,
            labels: ['web-tls', 'api'],
            tls: Config.tls
        }
    ],
    plugins: {
        './good-monitor': {}
    }
};

internals.composeOptions = {
    relativeTo: Path.resolve(__dirname, '../lib')
};
<commit_msg>Good tests cleanup<commit_after>var Code = require('code');
var Lab = require('lab');
var University = require('../lib');
var Path = require('path');
var Config = require('../lib/config');
var Good = require('good');
var GoodMonitor = require('../lib/good-monitor');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var expect = Code.expect;
var it = lab.test;

describe('good', function () {

    it('monitor registration failed', { parallel: false }, function (done) {

        var orig = Good.register;

        Good.register = function (plugin, options, next) {

            Good.register = orig;
            return next(new Error('fail'));
        };

        Good.register.attributes = {
            name: 'fake good'
        };

        University.init(internals.manifest, internals.composeOptions, function (err, server) {

            expect(err).to.exist();
            expect(err.message).to.equal('fail');
            done();
        });
    });
});

internals.manifest = {
    connections: [
        {
            host: 'localhost',
            port: 0,
            labels: ['web']
        },
        {
            host: 'localhost',
            port: 0,
            labels: ['web-tls', 'api'],
            tls: Config.tls
        }
    ],
    plugins: {
        './good-monitor': {}
    }
};

internals.composeOptions = {
    relativeTo: Path.resolve(__dirname, '../lib')
};
<|endoftext|>


<commit_before>// Helper functions used to test endpoints that are protected by authentication.

exports.APIKEY_ADMIN = process.env.ADMIN_APIKEY || '12345';

exports.AUTH_ADMIN = 'deconst apikey="' + exports.APIKEY_ADMIN + '"';

exports.APIKEY_USER = '54321';

exports.AUTH_USER = 'deconst apikey="' + exports.APIKEY_USER + '"';

/**
 * @description Test helper to ensure that a route fails if no API key is given.
 */
exports.ensureAuthIsRequired = function (action, done) {
  action
    .expect(401)
    .expect('Content-Type', 'application/json')
    .expect({
      code: 'UnauthorizedError',
      message: 'An API key is required for this endpoint.'
    }, done);
};

/**
 * @description Test helper to ensure that a route fails if a non-admin API key is given.
 */
exports.ensureAdminIsRequired = function (action, done) {
  action
    .set('Authorization', exports.AUTH_USER)
    .expect(401)
    .expect('Content-Type', 'application/json')
    .expect({
      code: 'UnauthorizedError',
      message: 'Only admins may access this endpoint.'
    }, done);
};
<commit_msg>Remove the apikey="" stuff from the unit tests.<commit_after>// Helper functions used to test endpoints that are protected by authentication.

exports.APIKEY_ADMIN = process.env.ADMIN_APIKEY || '12345';

exports.AUTH_ADMIN = 'deconst ' + exports.APIKEY_ADMIN;

exports.APIKEY_USER = '54321';

exports.AUTH_USER = 'deconst ' + exports.APIKEY_USER;

/**
 * @description Test helper to ensure that a route fails if no API key is given.
 */
exports.ensureAuthIsRequired = function (action, done) {
  action
    .expect(401)
    .expect('Content-Type', 'application/json')
    .expect({
      code: 'UnauthorizedError',
      message: 'An API key is required for this endpoint.'
    }, done);
};

/**
 * @description Test helper to ensure that a route fails if a non-admin API key is given.
 */
exports.ensureAdminIsRequired = function (action, done) {
  action
    .set('Authorization', exports.AUTH_USER)
    .expect(401)
    .expect('Content-Type', 'application/json')
    .expect({
      code: 'UnauthorizedError',
      message: 'Only admins may access this endpoint.'
    }, done);
};
<|endoftext|>


<commit_before>describe('$httpoll service', function () {
    var $httpoll, $httpBackend, $http, $timeout, pollingIterations;
    var route = '/';

    beforeEach(module('ngHTTPPoll'));

    beforeEach(inject(function($injector){
        $httpBackend = $injector.get('$httpBackend');
        $httpoll = $injector.get('$httpoll');
        $http = $injector.get('$http');
        $timeout = $injector.get('$timeout');
    }));

    beforeEach(function(){
        pollingIterations = 0;
        $httpSpy();
    });

    describe('main method', function () {

        var retries;

        beforeEach(function(){
            retries = 5;
            mockPollResponse('get', route, retries, "response");
        })

        it ('should only poll once if retries is zero', function () {
            var result = $httpoll({method: 'get', url: route, retries: 0});
            expectCatch(result, function(err){
                expect(err).toEqual("Polling reached max number of retries")
            });
            expectHTTPCount(1)
        })

        it ('should limit polling by the number of retries', function () {
            var result = $httpoll({method: 'get', url: route, retries: 3})
            expectCatch(result, function(err){
                expect(err).toEqual("Polling reached max number of retries")
            });
            expectHTTPCount(4)
        })

        it ('should retry if it receives a status code in the error range',
            function() {
                $httpoll({method: 'get', url: route, retryOnError: true })
                flush();
                expectHTTPCount(5)
            }
        )

        it ('should not retry if it receives a status code in the error range',
            function() {
                var result = $httpoll({method: 'get', url: route, retryOnError: false});
                expectCatch(result, function(err){
                    expect(err).toEqual('HTTP error: 404')
                })
                expectHTTPCount(1)
            }
        )

        it ('should respect a custom error range', function() {
            mockPollResponse('get', route, retries, "response");
            $httpoll({
                method: 'get',
                url: route,
                errorRange: [500, 599],
                retryOnError: false
            })

            flush();
            expectHTTPCount(5)
        })

        it ('should respect a custom success range', function() {
            $httpoll({
                method: 'get',
                url: route,
                retries: 9,
                successRange: [201, 299]
            })
            flush();
            expectHTTPCount(10)
        })

        it ('should timeout', function() {
            var result = $httpoll({
                method: 'get',
                url: route,
                timeout: 1000,
                delay: 1200,
                retries: 9
            })
            expectCatch(result, function(err){
                expect(err).toEqual("Polling timed out")
            });
            expectHTTPCount(1);
        })
    });

    /* GET, DELETE, JSONP */
    ['get','delete','jsonp'].forEach(function(method){

        describe (method+' method', function () {
            var response = "response message";
            var retries = 5;
            beforeEach(function(){
                mockPollResponse(method, route, retries, response)
            });

            it ('should successfully poll a '+method.toUpperCase() +' route',
                function () {
                    var promise = $httpoll[method](route);
                    promise.then(function(r){
                        expect(r).toBe(response);
                    })
                    flush();
                    expectHTTPCount(5)
                }
            );
        });
    });

    /* PUT, POST, PATCH */
    ['put','post','patch'].forEach(function(method){

        describe (method+' method', function () {
            var retries = 5;
            beforeEach(function(){
                mockPollResponse(method, route, retries, "", true)
            });

            it ('should successfully poll a '+method.toUpperCase() +' route\
                and pass data',
                function () {
                    var payload = {foo: 'bar'};
                    var promise = $httpoll[method](route, payload);
                    promise.then(function(r){
                        expect(r).toEqual(payload);
                    })
                    flush();
                    expectHTTPCount(5)
                }
            )

            it ('should not mutate the original config object', function() {
                var config = {retries: 20};
                var promise = $httpoll[method](route, {}, config);
                expect(config).toEqual({retries: 20});
            });
        })
    });

    /* HELPERS */

    function mockPollResponse(method, route, retries, response, passThrough) {
        $httpBackend.when(method.toUpperCase(),route)
            .respond(function (method, url, data) {
                pollingIterations ++;
                if (pollingIterations < retries) {
                    return [404, "Not found"]
                } else {
                    return [200, passThrough ? data : response]
                }
            });
    }

    function flush(){
        try {
            while (true) {
                $httpBackend.flush();
                $timeout.flush();
            }
        }
        catch (err) {
            if (err.message != 'No pending request to flush !') {
                throw err;
            }
        }
    }

    function $httpSpy () {
        $httpoll.provider = $http;
        spyOn($httpoll,'provider').and.callThrough();
    }

    function expectCatch(promise, catchExpectation) {
        var catchCalled;
        promise.catch(function(err){
            catchCalled = true;
            catchExpectation(err);
        });
        flush();
        expect(catchCalled).toBe(true);
    }

    function expectHTTPCount(count){
        expect($httpoll.provider.calls.count()).toBe(count)
    }
})
<commit_msg>removes unnecessary variable store<commit_after>describe('$httpoll service', function () {
    var $httpoll, $httpBackend, $http, $timeout, pollingIterations;
    var route = '/';

    beforeEach(module('ngHTTPPoll'));

    beforeEach(inject(function($injector){
        $httpBackend = $injector.get('$httpBackend');
        $httpoll = $injector.get('$httpoll');
        $http = $injector.get('$http');
        $timeout = $injector.get('$timeout');
    }));

    beforeEach(function(){
        pollingIterations = 0;
        $httpSpy();
    });

    describe('main method', function () {

        var retries;

        beforeEach(function(){
            retries = 5;
            mockPollResponse('get', route, retries, "response");
        })

        it ('should only poll once if retries is zero', function () {
            var result = $httpoll({method: 'get', url: route, retries: 0});
            expectCatch(result, function(err){
                expect(err).toEqual("Polling reached max number of retries")
            });
            expectHTTPCount(1)
        })

        it ('should limit polling by the number of retries', function () {
            var result = $httpoll({method: 'get', url: route, retries: 3})
            expectCatch(result, function(err){
                expect(err).toEqual("Polling reached max number of retries")
            });
            expectHTTPCount(4)
        })

        it ('should retry if it receives a status code in the error range',
            function() {
                $httpoll({method: 'get', url: route, retryOnError: true })
                flush();
                expectHTTPCount(5)
            }
        )

        it ('should not retry if it receives a status code in the error range',
            function() {
                var result = $httpoll({method: 'get', url: route, retryOnError: false});
                expectCatch(result, function(err){
                    expect(err).toEqual('HTTP error: 404')
                })
                expectHTTPCount(1)
            }
        )

        it ('should respect a custom error range', function() {
            mockPollResponse('get', route, retries, "response");
            $httpoll({
                method: 'get',
                url: route,
                errorRange: [500, 599],
                retryOnError: false
            })

            flush();
            expectHTTPCount(5)
        })

        it ('should respect a custom success range', function() {
            $httpoll({
                method: 'get',
                url: route,
                retries: 9,
                successRange: [201, 299]
            })
            flush();
            expectHTTPCount(10)
        })

        it ('should timeout', function() {
            var result = $httpoll({
                method: 'get',
                url: route,
                timeout: 1000,
                delay: 1200,
                retries: 9
            })
            expectCatch(result, function(err){
                expect(err).toEqual("Polling timed out")
            });
            expectHTTPCount(1);
        })
    });

    /* GET, DELETE, JSONP */
    ['get','delete','jsonp'].forEach(function(method){

        describe (method+' method', function () {
            var response = "response message";
            var retries = 5;
            beforeEach(function(){
                mockPollResponse(method, route, retries, response)
            });

            it ('should successfully poll a '+method.toUpperCase() +' route',
                function () {
                    var promise = $httpoll[method](route);
                    promise.then(function(r){
                        expect(r).toBe(response);
                    })
                    flush();
                    expectHTTPCount(5)
                }
            );
        });
    });

    /* PUT, POST, PATCH */
    ['put','post','patch'].forEach(function(method){

        describe (method+' method', function () {
            var retries = 5;
            beforeEach(function(){
                mockPollResponse(method, route, retries, "", true)
            });

            it ('should successfully poll a '+method.toUpperCase() +' route\
                and pass data',
                function () {
                    var payload = {foo: 'bar'};
                    var promise = $httpoll[method](route, payload);
                    promise.then(function(r){
                        expect(r).toEqual(payload);
                    })
                    flush();
                    expectHTTPCount(5)
                }
            )

            it ('should not mutate the original config object', function() {
                var config = {retries: 20};
                $httpoll[method](route, {}, config);
                expect(config).toEqual({retries: 20});
            });
        })
    });

    /* HELPERS */

    function mockPollResponse(method, route, retries, response, passThrough) {
        $httpBackend.when(method.toUpperCase(),route)
            .respond(function (method, url, data) {
                pollingIterations ++;
                if (pollingIterations < retries) {
                    return [404, "Not found"]
                } else {
                    return [200, passThrough ? data : response]
                }
            });
    }

    function flush(){
        try {
            while (true) {
                $httpBackend.flush();
                $timeout.flush();
            }
        }
        catch (err) {
            if (err.message != 'No pending request to flush !') {
                throw err;
            }
        }
    }

    function $httpSpy () {
        $httpoll.provider = $http;
        spyOn($httpoll,'provider').and.callThrough();
    }

    function expectCatch(promise, catchExpectation) {
        var catchCalled;
        promise.catch(function(err){
            catchCalled = true;
            catchExpectation(err);
        });
        flush();
        expect(catchCalled).toBe(true);
    }

    function expectHTTPCount(count){
        expect($httpoll.provider.calls.count()).toBe(count)
    }
})
<|endoftext|>


<commit_before>// idmaker-test.js
//
// Test the idmaker module
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require('assert'),
    vows = require('vows');

vows.describe('idmaker module interface').addBatch({
    'When we require the idmaker module': {
        topic: function() {
            return require('../lib/idmaker');
        },
        'it works': function(idmaker) {
            assert.isObject(idmaker);
        },
        'and we get its IDMaker export': {
            topic: function(idmaker) {
                return idmaker.IDMaker;
            },
            'it exists': function(IDMaker) {
                assert.isObject(IDMaker);
            },
            'it has a makeID() method': function(IDMaker) {
                assert.isFunction(IDMaker.makeID);
            },
            'and we make an ID': {
                topic: function(IDMaker) {
                    return IDMaker.makeID();
                },
                'it works': function(id) {
                    assert.isString(id);
                },
                'it is URL-safe': function(id) {
                    assert.equal(id, encodeURIComponent(id));
                },
                'it looks big enough for 128 bits of data': function(id) {
                    assert.isTrue(id.length >= (128/8));
                }
            }
        }
    }
}).export(module);
<commit_msg>Take out the calculation<commit_after>// idmaker-test.js
//
// Test the idmaker module
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require('assert'),
    vows = require('vows');

vows.describe('idmaker module interface').addBatch({
    'When we require the idmaker module': {
        topic: function() {
            return require('../lib/idmaker');
        },
        'it works': function(idmaker) {
            assert.isObject(idmaker);
        },
        'and we get its IDMaker export': {
            topic: function(idmaker) {
                return idmaker.IDMaker;
            },
            'it exists': function(IDMaker) {
                assert.isObject(IDMaker);
            },
            'it has a makeID() method': function(IDMaker) {
                assert.isFunction(IDMaker.makeID);
            },
            'and we make an ID': {
                topic: function(IDMaker) {
                    return IDMaker.makeID();
                },
                'it works': function(id) {
                    assert.isString(id);
                },
                'it is URL-safe': function(id) {
                    assert.equal(id, encodeURIComponent(id));
                },
                'it looks big enough for 128 bits of data': function(id) {
                    assert.isTrue(id.length >= 16);
                }
            }
        }
    }
}).export(module);
<|endoftext|>


<commit_before>var assert = require("assert");

var hamjest = require("hamjest");
var assertThat = hamjest.assertThat;
var contains = hamjest.contains;
var equalTo = hamjest.equalTo;
var hasProperties = hamjest.hasProperties;

var mammoth = require("../");
var documents = require("../lib/documents");
var promises = require("../lib/promises");

var test = require("./test")(module);

test('mammoth.images.inline() should be an alias of mammoth.images.imgElement()', function() {
    assert.ok(mammoth.images.inline === mammoth.images.imgElement);
});

test('mammoth.images.dataUri() encodes images in base64', function() {
    var imageBuffer = new Buffer("abc");
    var image = new documents.Image({
        readImage: function(encoding) {
            return promises.when(imageBuffer.toString(encoding));
        },
        contentType: "image/jpeg"
    });

    return mammoth.images.dataUri(image).then(function(result) {
        assertThat(result, contains(
            hasProperties({tag: hasProperties({attributes: {"src": "data:image/jpeg;base64,YWJj"}})})
        ));
    });
});

test('mammoth.images.imgElement()', {
    'when element does not have alt text then alt attribute is not set': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({src: "<src>"})
                    })
                })
            ));
        });
    },

    'when element has alt text then alt attribute is set': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg",
            altText: "<alt>"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({alt: "<alt>", src: "<src>"})
                    })
                })
            ));
        });
    },

    'image alt text can be overriden by alt attribute returned from function': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg",
            altText: "<alt>"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {alt: "<alt override>", src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({alt: "<alt override>", src: "<src>"})
                    })
                })
            ));
        });
    }
});
<commit_msg>Fix typo in test name<commit_after>var assert = require("assert");

var hamjest = require("hamjest");
var assertThat = hamjest.assertThat;
var contains = hamjest.contains;
var equalTo = hamjest.equalTo;
var hasProperties = hamjest.hasProperties;

var mammoth = require("../");
var documents = require("../lib/documents");
var promises = require("../lib/promises");

var test = require("./test")(module);

test('mammoth.images.inline() should be an alias of mammoth.images.imgElement()', function() {
    assert.ok(mammoth.images.inline === mammoth.images.imgElement);
});

test('mammoth.images.dataUri() encodes images in base64', function() {
    var imageBuffer = new Buffer("abc");
    var image = new documents.Image({
        readImage: function(encoding) {
            return promises.when(imageBuffer.toString(encoding));
        },
        contentType: "image/jpeg"
    });

    return mammoth.images.dataUri(image).then(function(result) {
        assertThat(result, contains(
            hasProperties({tag: hasProperties({attributes: {"src": "data:image/jpeg;base64,YWJj"}})})
        ));
    });
});

test('mammoth.images.imgElement()', {
    'when element does not have alt text then alt attribute is not set': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({src: "<src>"})
                    })
                })
            ));
        });
    },

    'when element has alt text then alt attribute is set': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg",
            altText: "<alt>"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({alt: "<alt>", src: "<src>"})
                    })
                })
            ));
        });
    },

    'image alt text can be overridden by alt attribute returned from function': function() {
        var imageBuffer = new Buffer("abc");
        var image = new documents.Image({
            readImage: function(encoding) {
                return promises.when(imageBuffer.toString(encoding));
            },
            contentType: "image/jpeg",
            altText: "<alt>"
        });

        var result = mammoth.images.imgElement(function(image) {
            return {alt: "<alt override>", src: "<src>"};
        })(image);

        return result.then(function(result) {
            assertThat(result, contains(
                hasProperties({
                    tag: hasProperties({
                        attributes: equalTo({alt: "<alt override>", src: "<src>"})
                    })
                })
            ));
        });
    }
});
<|endoftext|>


<commit_before><commit_msg>Filled include-test test script.<commit_after>exports.includeTest = function(test){
	test.doesNotThrow(
	  function() {
	    var cares = require('../lib/cares.js');
	  },
	  Error,
	  'Failed to import cares.'
	);
	test.done();
};
<|endoftext|>