<commit_before>'use babel'

import Update from '../src/update'
import remote from 'remote'

fdescribe('Update', () => {
  describe('::initialize', () => {
    it('subscribes to appropriate applicationDelegate events', () => {
      const update = new Update()
      update.initialize()

      const downloadingSpy = jasmine.createSpy('downloadingSpy')
      const checkingSpy = jasmine.createSpy('checkingSpy')
      const noUpdateSpy = jasmine.createSpy('noUpdateSpy')

      update.onDidBeginCheckingForUpdate(checkingSpy)
      update.onDidBeginDownload(downloadingSpy)
      update.onUpdateNotAvailable(noUpdateSpy)

      // This doesn't work
      const webContents = remote.getCurrentWebContents()
      webContents.send('message', 'update-available', {releaseVersion: '1.2.3'})
      webContents.send('message', 'did-begin-downloading-update')
      webContents.send('message', 'checking-for-update')
      webContents.send('message', 'update-not-available')

      waitsFor(() => {
        noUpdateSpy.callCount > 0
      })
      runs(() => {
        expect(downloadingSpy.callCount).toBe(1)
        expect(checkingSpy.callCount).toBe(1)
        expect(noUpdateSpy.callCount).toBe(1)
      })
    })
  })
})
<commit_msg>Add specs for Update methods (::check left TODO)<commit_after>'use babel'

import Update from '../src/update'
import remote from 'remote'
import ipc from 'ipc'

fdescribe('Update', () => {
  let update

  afterEach(() => {
    update.dispose()
  })

  describe('::initialize', () => {
    it('subscribes to appropriate applicationDelegate events', () => {
      update = new Update()

      const downloadingSpy = jasmine.createSpy('downloadingSpy')
      const checkingSpy = jasmine.createSpy('checkingSpy')
      const noUpdateSpy = jasmine.createSpy('noUpdateSpy')
      const completedDownloadSpy = jasmine.createSpy('completedDownloadSpy')

      update.emitter.on('did-begin-checking-for-update', checkingSpy)
      update.emitter.on('did-begin-downloading-update', downloadingSpy)
      update.emitter.on('did-complete-downloading-update', completedDownloadSpy)
      update.emitter.on('update-not-available', noUpdateSpy)

      update.initialize()

      const webContents = remote.getCurrentWebContents()
      webContents.send('message', 'checking-for-update')
      webContents.send('message', 'did-begin-downloading-update')
      webContents.send('message', 'update-available', {releaseVersion: '1.2.3'})
      webContents.send('message', 'update-not-available')

      waitsFor(() => {
        return noUpdateSpy.callCount > 0
      })

      runs(() => {
        expect(downloadingSpy.callCount).toBe(1)
        expect(checkingSpy.callCount).toBe(1)
        expect(noUpdateSpy.callCount).toBe(1)
        expect(completedDownloadSpy.callCount).toBe(1)
      })
    })
  })

  beforeEach(() => {
    update = new Update()
    update.initialize()
  })

  describe('::onDidBeginCheckingForUpdate', () => {
    it('subscribes to "did-begin-checking-for-update" event', () => {
      const spy = jasmine.createSpy('spy')
      update.onDidBeginCheckingForUpdate(spy)
      update.emitter.emit('did-begin-checking-for-update')
      expect(spy.callCount).toBe(1)
    })
  })

  describe('::onDidBeginDownload', () => {
    it('subscribes to "did-begin-downloading-update" event', () => {
      const spy = jasmine.createSpy('spy')
      update.onDidBeginDownload(spy)
      update.emitter.emit('did-begin-downloading-update')
      expect(spy.callCount).toBe(1)
    })
  })

  describe('::onDidCompleteDownload', () => {
    it('subscribes to "did-complete-downloading-update" event', () => {
      const spy = jasmine.createSpy('spy')
      update.onDidCompleteDownload(spy)
      update.emitter.emit('did-complete-downloading-update')
      expect(spy.callCount).toBe(1)
    })
  })

  describe('::onUpdateNotAvailable', () => {
    it('subscribes to "update-not-available" event', () => {
      const spy = jasmine.createSpy('spy')
      update.onUpdateNotAvailable(spy)
      update.emitter.emit('update-not-available')
      expect(spy.callCount).toBe(1)
    })
  })

  describe('::onUpdateAvailable', () => {
    it('subscribes to "update-available" event', () => {
      const spy = jasmine.createSpy('spy')
      update.onUpdateAvailable(spy)
      update.emitter.emit('update-available')
      expect(spy.callCount).toBe(1)
    })
  })

  // TODO: spec is timing out. spy is not called
  // describe('::check', () => {
  //   it('sends "check-for-update" event', () => {
  //     const spy = jasmine.createSpy('spy')
  //     ipc.on('check-for-update', () => {
  //       spy()
  //     })
  //     update.check()
  //     waitsFor(() => {
  //       return spy.callCount > 0
  //     })
  //   })
  // })

  describe('::dispose', () => {
    it('disposes of subscriptions', () => {
      expect(update.subscriptions.disposables).not.toBeNull()
      update.dispose()
      expect(update.subscriptions.disposables).toBeNull()
    })
  })

})
<|endoftext|>


<commit_before>
var request = require('supertest')
var views = require('../')
var should = require('should')
var koa = require('koa')

describe('koa-views', function () {
  it('have a render method', function (done) {
    var app = koa()
    .use(views())
    .use(function *() {
      this.render.should.ok
      this.render.should.Function
    })

    request(app.listen()).get('/')
      .expect(404, done)
  })

  it('default to html', function (done) {
    var app = koa()
    .use(views())
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:html/)
      .expect(200, done)
  })

  it('default to [ext] if a default engine is set', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('set and render locals', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      this.locals.engine = 'jade'
      yield this.render('./fixtures/global-locals')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('`map` given `engine` to given file `ext`', function (done) {
    var app = koa()
    .use(views({ map: {html: 'underscore'} }))
    .use(function *() {
      this.locals.engine = 'underscore'
      yield this.render('./fixtures/underscore')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:underscore/)
      .expect(200, done)
  })

  it('merge global and local locals ', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      this.locals.engine = 'jade'

      yield this.render('./fixtures/locals', {
        type: 'basic'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  // TODO: #23
})<commit_msg>add test for #25<commit_after>
var request = require('supertest')
var views = require('../')
var should = require('should')
var koa = require('koa')

describe('koa-views', function () {
  it('have a render method', function (done) {
    var app = koa()
    .use(views())
    .use(function *() {
      this.render.should.ok
      this.render.should.Function
    })

    request(app.listen()).get('/')
      .expect(404, done)
  })

  it('default to html', function (done) {
    var app = koa()
    .use(views())
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:html/)
      .expect(200, done)
  })

  it('default to [ext] if a default engine is set', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('set and render locals', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      this.locals.engine = 'jade'
      yield this.render('./fixtures/global-locals')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  // #25
  it('works with circular references in locals', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      this.locals = {
        a: {},
        app: app
      }

      this.locals.a.a = this.locals.a

      yield this.render('./fixtures/global-locals', {
        app: app,
        b: this.locals,
        engine: 'jade'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('`map` given `engine` to given file `ext`', function (done) {
    var app = koa()
    .use(views({ map: {html: 'underscore'} }))
    .use(function *() {
      this.locals.engine = 'underscore'
      yield this.render('./fixtures/underscore')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:underscore/)
      .expect(200, done)
  })

  it('merge global and local locals ', function (done) {
    var app = koa()
    .use(views({ default: 'jade' }))
    .use(function *() {
      this.locals.engine = 'jade'

      yield this.render('./fixtures/locals', {
        type: 'basic'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  // TODO: #23
})<|endoftext|>


<commit_before>var assert = require('assert')
var Blockchain = require('../src/index')

var url = 'http://localhost:8080'

describe('Blockchain', function() {
  describe('Constructor', function() {
    it('defaults to the bitcoin network', function() {
      var blockchain = new Blockchain(url)

      assert.equal(blockchain.getNetwork(), 'bitcoin')
    })
  })

  describe('getNetwork', function() {
    it('returns the underlying network name', function() {
      var blockchain = new Blockchain(url, 'testnet')

      assert.equal(blockchain.getNetwork(), 'testnet')
    })
  })
})

describe('cb-tests', function() {
	var options = {}

	beforeEach(function() {
		options.blockchain = new Blockchain(url, 'testnet')
	})

	require('cb-tester')(options)
})
<commit_msg>tests: use the example heroku app for testing<commit_after>var assert = require('assert')
var Blockchain = require('../src/index')

var url = 'https://common-blockchain.herokuapp.com/'

describe('Blockchain', function() {
  describe('Constructor', function() {
    it('defaults to the bitcoin network', function() {
      var blockchain = new Blockchain(url)

      assert.equal(blockchain.getNetwork(), 'bitcoin')
    })
  })

  describe('getNetwork', function() {
    it('returns the underlying network name', function() {
      var blockchain = new Blockchain(url, 'testnet')

      assert.equal(blockchain.getNetwork(), 'testnet')
    })
  })
})

describe('cb-tests', function() {
	var options = {}

	beforeEach(function() {
		options.blockchain = new Blockchain(url, 'testnet')
	})

	require('cb-tester')(options)
})
<|endoftext|>


<commit_before>'use strict';

const lab = exports.lab = require('lab').script();
const code = require('code');
const PROJECT_NAME = 'bump-regex';
const project = require('..');

lab.experiment(PROJECT_NAME, function() {
  const options = {
    str: JSON.stringify({version: '0.1.0'})
  };

  lab.test('no options', function(done) {
    project(options, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1"}');
      done();
    });
  });

  lab.test('patch', function(done) {
    let opts = options;
    opts.type = 'patch';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1"}');
      done();
    });
  });

  lab.test('minor', function(done) {
    let opts = options;
    opts.type = 'minor';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.2.0"}');
      done();
    });
  });

  lab.test('major', function(done) {
    let opts = options;
    opts.type = 'major';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"1.0.0"}');
      done();
    });
  });

  lab.test('set version', function(done) {
    var opts = options;
    opts.version = '3.2.1';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"3.2.1"}');
      done();
    });
  });

  lab.test('set key', function(done) {
    var opts = {
      str: JSON.stringify({appversion: '0.1.0'}),
      key: 'appversion'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"appversion":"0.1.1"}');
      done();
    });
  });

  lab.test('set key with dash', function(done) {
    var opts = {
      str: JSON.stringify({'latest-release': '0.1.1'}),
      key: 'latest-release'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"latest-release":"0.1.2"}');
      done();
    });
  });

  lab.test('bump version in xml files with dash', function(done) {
    var opts = {
      str: '<latest-version>1.0.0</latest-version>'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<latest-version>1.0.1</latest-version>');
      done();
    });
  });

  lab.test('set preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0'}),
      type: 'prerelease',
      preid: 'thing'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1-thing.0"}');
      done();
    });
  });

  lab.test('set preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-thing.0'}),
      type: 'prerelease',
      preid: 'thing'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0-thing.1"}');
      done();
    });

  });

  lab.test('update existing prerelease without preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-rc.0'}),
      type: 'prerelease'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0-rc.1"}');
      done();
    });

  });

  lab.test('remove prerelease with patch', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-rc.0'}),
      type: 'patch'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0"}');
      done();
    });

  });
  lab.test('remove prerelease with patch when alpha tag has no version', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-noversion'}),
      type: 'patch'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0"}');
      done();
    });

  });

  lab.test('set global', function(done) {
    var opts = {
      str: JSON.stringify({
        version: '0.1.0',
        test: {
          version: '0.1.2'
        }
      }),
      global: true
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1","test":{"version":"0.1.3"}}');
      done();
    });

  });

  lab.test('set on text file', function(done) {
    var opts = {
      str: 'swift \n Version: "0.1.2"'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('swift \n Version: "0.1.3"');
      done();
    });
  });

  lab.test('error with invalid semver', function(done) {
    var opts = {
      str: 'swift \n Version: "0.A.2"'
    };
    project(opts, function(err) {
      code.expect(err).to.equal('Invalid semver: version key "version" is not found in file');
      done();
    });
  });

  lab.test('return new version', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.2.1');
      done();
    });
  });

  lab.test('return update type', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.type).to.equal('patch');
      done();
    });
  });

  lab.test('return prev version', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.prev).to.equal('1.2.0');
      done();
    });
  });

  lab.test('bump xml version param', function(done) {
    var opts = {
      str: '<version="1.0.0">'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<version="1.0.1">');
      done();
    });
  });

  lab.test('bump version in xml files', function(done) {
    var opts = {
      str: '<version>1.0.0</version>'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<version>1.0.1</version>');
      done();
    });
  });

  lab.test('bump version in specific xml tag with `case: true`', function(done) {
    var opts = {
      str: '<projectVersion>1.2.3</projectVersion><version>1.0.0</version>',
      case: true
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<projectVersion>1.2.3</projectVersion><version>1.0.1</version>');
      done();
    });
  });

  lab.test('bump version with a prefix', function(done) {
    var opts = {
      str: 'version=v1.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('version=v1.0.1');
      done();
    });
  });

  lab.test('set a 4 char version without adding a character', function(done) {
    var opts = {
      str: 'version=11.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('11.0.1');
      code.expect(out.str).to.equal('version=11.0.1');
      done();
    });
  });

  lab.test('set a 4 char version with a version prefix character', function(done) {
    var opts = {
      str: 'version=r11.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('11.0.1');
      code.expect(out.str).to.equal('version=r11.0.1');
      done();
    });
  });

  lab.test('set a 4 char version with a prefix', function(done) {
    var opts = {
      str: 'version: v101.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('101.0.1');
      code.expect(out.str).to.equal('version: v101.0.1');
      done();
    });
  });
});
<commit_msg>add test for gulp-bump/issues/66<commit_after>'use strict';

const lab = exports.lab = require('lab').script();
const code = require('code');
const PROJECT_NAME = 'bump-regex';
const project = require('..');

lab.experiment(PROJECT_NAME, function() {
  const options = {
    str: JSON.stringify({version: '0.1.0'})
  };

  lab.test('no options', function(done) {
    project(options, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1"}');
      done();
    });
  });

  lab.test('patch', function(done) {
    let opts = options;
    opts.type = 'patch';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1"}');
      done();
    });
  });

  lab.test('minor', function(done) {
    let opts = options;
    opts.type = 'minor';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.2.0"}');
      done();
    });
  });

  lab.test('major', function(done) {
    let opts = options;
    opts.type = 'major';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"1.0.0"}');
      done();
    });
  });

  lab.test('set version', function(done) {
    var opts = options;
    opts.version = '3.2.1';
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"3.2.1"}');
      done();
    });
  });

  lab.test('set key', function(done) {
    var opts = {
      str: JSON.stringify({appversion: '0.1.0'}),
      key: 'appversion'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"appversion":"0.1.1"}');
      done();
    });
  });

  lab.test('set key with dash', function(done) {
    var opts = {
      str: JSON.stringify({'latest-release': '0.1.1'}),
      key: 'latest-release'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"latest-release":"0.1.2"}');
      done();
    });
  });

  lab.test('bump version in xml files with dash', function(done) {
    var opts = {
      str: '<latest-version>1.0.0</latest-version>'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<latest-version>1.0.1</latest-version>');
      done();
    });
  });

  lab.test('set preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0'}),
      type: 'prerelease',
      preid: 'thing'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1-thing.0"}');
      done();
    });
  });

  lab.test('set preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-thing.0'}),
      type: 'prerelease',
      preid: 'thing'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0-thing.1"}');
      done();
    });

  });

  lab.test('update existing prerelease without preid', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-rc.0'}),
      type: 'prerelease'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0-rc.1"}');
      done();
    });

  });

  lab.test('remove prerelease with patch', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-rc.0'}),
      type: 'patch'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0"}');
      done();
    });

  });
  lab.test('remove prerelease with patch when alpha tag has no version', function(done) {
    var opts = {
      str: JSON.stringify({version: '0.1.0-noversion'}),
      type: 'patch'
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.0"}');
      done();
    });

  });

  lab.test('set global', function(done) {
    var opts = {
      str: JSON.stringify({
        version: '0.1.0',
        test: {
          version: '0.1.2'
        }
      }),
      global: true
    };

    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('{"version":"0.1.1","test":{"version":"0.1.3"}}');
      done();
    });

  });

  lab.test('set on text file', function(done) {
    var opts = {
      str: 'swift \n Version: "0.1.2"'
    };
    project(opts, function(err, out) {
      code.expect(err).to.equal(null);
      code.expect(out.str).to.equal('swift \n Version: "0.1.3"');
      done();
    });
  });

  lab.test('error with invalid semver', function(done) {
    var opts = {
      str: 'swift \n Version: "0.A.2"'
    };
    project(opts, function(err) {
      code.expect(err).to.equal('Invalid semver: version key "version" is not found in file');
      done();
    });
  });

  lab.test('return new version', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.2.1');
      done();
    });
  });

  lab.test('return update type', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.type).to.equal('patch');
      done();
    });
  });

  lab.test('return prev version', function(done) {
    var opts = {
      str: JSON.stringify({version: '1.2.0'})
    };
    project(opts, function(err, out) {
      code.expect(out.prev).to.equal('1.2.0');
      done();
    });
  });

  lab.test('bump xml version param', function(done) {
    var opts = {
      str: '<version="1.0.0">'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<version="1.0.1">');
      done();
    });
  });

  lab.test('bump version in xml files', function(done) {
    var opts = {
      str: '<version>1.0.0</version>'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<version>1.0.1</version>');
      done();
    });
  });

  lab.test('bump version in specific xml tag with `case: true`', function(done) {
    var opts = {
      str: '<projectVersion>1.2.3</projectVersion><version>1.0.0</version>',
      case: true
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('<projectVersion>1.2.3</projectVersion><version>1.0.1</version>');
      done();
    });
  });

  lab.test('bump version with a prefix', function(done) {
    var opts = {
      str: 'version=v1.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('1.0.1');
      code.expect(out.str).to.equal('version=v1.0.1');
      done();
    });
  });

  lab.test('set a 4 char version without adding a character', function(done) {
    var opts = {
      str: 'version=11.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('11.0.1');
      code.expect(out.str).to.equal('version=11.0.1');
      done();
    });
  });

  lab.test('set a 4 char version with a version prefix character', function(done) {
    var opts = {
      str: 'version=r11.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('11.0.1');
      code.expect(out.str).to.equal('version=r11.0.1');
      done();
    });
  });

  lab.test('set a 4 char version with a prefix', function(done) {
    var opts = {
      str: 'version: v101.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('101.0.1');
      code.expect(out.str).to.equal('version: v101.0.1');
      done();
    });
  });

  lab.test('bump php/text/whatever version', function(done) {
    var opts = {
      str: '\n * Version: 3.0.0'
    };
    project(opts, function(err, out) {
      code.expect(out.new).to.equal('3.0.1');
      code.expect(out.str).to.equal('\n * Version: 3.0.1');
      done();
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Mentor help request view page
 */

(function($) {
    'use strict';

    // Setup DataTable
    var table = $('table#help-requests');
    var COLS = {
        'Name': { data: 'attendee.name' },
        'Request': { data: 'request' },
        'Status': { data: function (row, type) {
            var assignedMentor = row.assigned_mentor;
            if (type === 'display') {
                if (assignedMentor) {
                    if (assignedMentor.is_me) {
                        return 'Claimed by you';
                    }
                    return 'Claimed by ' + assignedMentor.name;
                }
                return 'Waiting for mentor!';
            }

            // Sort by claimed/unclaimed
            return assignedMentor? 1 : 0;
        }},
        'Submitted At': { data: function (row, type) {
            var created = hackUtil.deserializeDateTime(row.created);
            if (type === 'display') {
                // Minimal display
                return created.format('ddd hh:mm a');
            }

            // Exact time for sorting
            return created.valueOf();
        }}

    };

    /**
     * Formats the table html
     */
    function createTable(table, colData) {
        var tableHead = $('

');
        var tableHeadRow = tableHead.find('tr');

        Object.keys(colData).forEach(function(columnName) {
            tableHeadRow.append(''+columnName+'	');
        });

        table.append(tableHead);
        table.append('

');
    }

    /**
     * Retrieves data
     */
    function getData() {
        var dfd = $.Deferred();

        $.ajaxGet({
            url: '/api/mentor/request/get'
        })
            .done(function(res) {
                dfd.resolve(res['help_requests']);
            })
            .fail(function(err) {
                dfd.reject(err);
            });

        return dfd.promise();
    }

    /**
     * Populates the DataTable with help requests
     */
    function populateTable(table, colData, data) {
        var colNames = Object.keys(colData);

        var dt = table.DataTable({
            dom:
                "<'row flex-align-center flex-wrap'<'col-sm-4'l><'col-sm-4'<'flex-center'B>><'col-sm-4'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
            // scrollX: true,
            responsive: true,
            data: data,
            columns: $.map(colData, function(data) {
                return data;
            }),
            order: [
                [colNames.indexOf('Status'), 'asc'],
                [colNames.indexOf('Submitted At'), 'desc']
            ],
            select: {
                style: 'single'
            },
            buttons: [
                {
                    extend: 'selected',
                    text: 'View Full Request',
                    className: 'btn-form btn-form-sm',
                    action: function (e, dt) {
                        var row = dt.rows({selected: true}).data()[0];
                        window.location.href = '/mentor/request/' + row.id;
                    }
                }
            ]
        });

        return dt;
    }

    // Create page
    createTable(table, COLS);
    getData().done(function(requests) {
        console.log(requests);
        populateTable(table, COLS, requests);
    });

    // Reload after a minute
    setTimeout(function() {
       window.location.reload(1);
    }, 60*1000);

})(jQuery);
<commit_msg>datatables page length menu sizes increased<commit_after>/**
 * Mentor help request view page
 */

(function($) {
    'use strict';

    // Setup DataTable
    var table = $('table#help-requests');
    var COLS = {
        'Name': { data: 'attendee.name' },
        'Request': { data: 'request' },
        'Status': { data: function (row, type) {
            var assignedMentor = row.assigned_mentor;
            if (type === 'display') {
                if (assignedMentor) {
                    if (assignedMentor.is_me) {
                        return 'Claimed by you';
                    }
                    return 'Claimed by ' + assignedMentor.name;
                }
                return 'Waiting for mentor!';
            }

            // Sort by claimed/unclaimed
            return assignedMentor? 1 : 0;
        }},
        'Submitted At': { data: function (row, type) {
            var created = hackUtil.deserializeDateTime(row.created);
            if (type === 'display') {
                // Minimal display
                return created.format('ddd hh:mm a');
            }

            // Exact time for sorting
            return created.valueOf();
        }}

    };

    /**
     * Formats the table html
     */
    function createTable(table, colData) {
        var tableHead = $('

');
        var tableHeadRow = tableHead.find('tr');

        Object.keys(colData).forEach(function(columnName) {
            tableHeadRow.append(''+columnName+'	');
        });

        table.append(tableHead);
        table.append('

');
    }

    /**
     * Retrieves data
     */
    function getData() {
        var dfd = $.Deferred();

        $.ajaxGet({
            url: '/api/mentor/request/get'
        })
            .done(function(res) {
                dfd.resolve(res['help_requests']);
            })
            .fail(function(err) {
                dfd.reject(err);
            });

        return dfd.promise();
    }

    /**
     * Populates the DataTable with help requests
     */
    function populateTable(table, colData, data) {
        var colNames = Object.keys(colData);

        var dt = table.DataTable({
            dom:
                "<'row flex-align-center flex-wrap'<'col-sm-4'l><'col-sm-4'<'flex-center'B>><'col-sm-4'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
            // scrollX: true,
            responsive: true,
            lengthMenu: [[25, 50, 100, -1], [25, 50, 100, 'All']],
            data: data,
            columns: $.map(colData, function(data) {
                return data;
            }),
            order: [
                [colNames.indexOf('Status'), 'asc'],
                [colNames.indexOf('Submitted At'), 'desc']
            ],
            select: {
                style: 'single'
            },
            buttons: [
                {
                    extend: 'selected',
                    text: 'View Full Request',
                    className: 'btn-form btn-form-sm',
                    action: function (e, dt) {
                        var row = dt.rows({selected: true}).data()[0];
                        window.location.href = '/mentor/request/' + row.id;
                    }
                }
            ]
        });

        return dt;
    }

    // Create page
    createTable(table, COLS);
    getData().done(function(requests) {
        console.log(requests);
        populateTable(table, COLS, requests);
    });

    // Reload after a minute
    setTimeout(function() {
       window.location.reload(1);
    }, 60*1000);

})(jQuery);
<|endoftext|>


<commit_before>// @flow
import defineFunction from "../defineFunction";
import buildCommon from "../buildCommon";
import mathMLTree from "../mathMLTree";
import stretchy from "../stretchy";

import * as html from "../buildHTML";
import * as mml from "../buildMathML";

import type {ParseNode} from "../parseNode";

// Stretchy arrows with an optional argument
defineFunction({
    type: "xArrow",
    names: [
        "\\xleftarrow", "\\xrightarrow", "\\xLeftarrow", "\\xRightarrow",
        "\\xleftrightarrow", "\\xLeftrightarrow", "\\xhookleftarrow",
        "\\xhookrightarrow", "\\xmapsto", "\\xrightharpoondown",
        "\\xrightharpoonup", "\\xleftharpoondown", "\\xleftharpoonup",
        "\\xrightleftharpoons", "\\xleftrightharpoons", "\\xlongequal",
        "\\xtwoheadrightarrow", "\\xtwoheadleftarrow", "\\xtofrom",
        // The next 3 functions are here to support the mhchem extension.
        // Direct use of these functions is discouraged and may break someday.
        "\\xrightleftarrows", "\\xrightequilibrium", "\\xleftequilibrium",
    ],
    props: {
        numArgs: 1,
        numOptionalArgs: 1,
    },
    handler({parser, funcName}, args, optArgs) {
        return {
            type: "xArrow",
            mode: parser.mode,
            label: funcName,
            body: args[0],
            below: optArgs[0],
        };
    },
    // Flow is unable to correctly infer the type of `group`, even though it's
    // unamibiguously determined from the passed-in `type` above.
    htmlBuilder(group: ParseNode<"xArrow">, options) {
        const style = options.style;

        // Build the argument groups in the appropriate style.
        // Ref: amsmath.dtx:   \hbox{$\scriptstyle\mkern#3mu{#6}\mkern#4mu$}%

        // Some groups can return document fragments.  Handle those by wrapping
        // them in a span.
        let newOptions = options.havingStyle(style.sup());
        const upperGroup = buildCommon.wrapFragment(
            html.buildGroup(group.body, newOptions, options), options);
        upperGroup.classes.push("x-arrow-pad");

        let lowerGroup;
        if (group.below) {
            // Build the lower group
            newOptions = options.havingStyle(style.sub());
            lowerGroup = buildCommon.wrapFragment(
                html.buildGroup(group.below, newOptions, options), options);
            lowerGroup.classes.push("x-arrow-pad");
        }

        const arrowBody = stretchy.svgSpan(group, options);

        // Re shift: Note that stretchy.svgSpan returned arrowBody.depth = 0.
        // The point we want on the math axis is at 0.5 * arrowBody.height.
        const arrowShift = -options.fontMetrics().axisHeight +
            0.5 * arrowBody.height;
        // 2 mu kern. Ref: amsmath.dtx: #7\if0#2\else\mkern#2mu\fi
        let upperShift = -options.fontMetrics().axisHeight
            - 0.5 * arrowBody.height - 0.111; // 0.111 em = 2 mu
        if (upperGroup.depth > 0.25 || group.label === "\\xleftequilibrium") {
            upperShift -= upperGroup.depth;  // shift up if depth encroaches
        }

        // Generate the vlist
        let vlist;
        if (lowerGroup) {
            const lowerShift = -options.fontMetrics().axisHeight
                + lowerGroup.height + 0.5 * arrowBody.height
                + 0.111;
            vlist = buildCommon.makeVList({
                positionType: "individualShift",
                children: [
                    {type: "elem", elem: upperGroup, shift: upperShift},
                    {type: "elem", elem: arrowBody,  shift: arrowShift},
                    {type: "elem", elem: lowerGroup, shift: lowerShift},
                ],
            }, options);
        } else {
            vlist = buildCommon.makeVList({
                positionType: "individualShift",
                children: [
                    {type: "elem", elem: upperGroup, shift: upperShift},
                    {type: "elem", elem: arrowBody,  shift: arrowShift},
                ],
            }, options);
        }

        // $FlowFixMe: Replace this with passing "svg-align" into makeVList.
        vlist.children[0].children[0].children[1].classes.push("svg-align");

        return buildCommon.makeSpan(["mrel", "x-arrow"], [vlist], options);
    },
    mathmlBuilder(group, options) {
        const arrowNode = stretchy.mathMLnode(group.label);
        let node;
        let lowerNode;

        if (group.body) {
            const upperNode = mml.buildGroup(group.body, options);
            if (group.below) {
                lowerNode = mml.buildGroup(group.below, options);
                node = new mathMLTree.MathNode(
                    "munderover", [arrowNode, lowerNode, upperNode]
                );
            } else {
                node = new mathMLTree.MathNode("mover", [arrowNode, upperNode]);
            }
        } else if (group.below) {
            lowerNode = mml.buildGroup(group.below, options);
            node = new mathMLTree.MathNode("munder", [arrowNode, lowerNode]);
        } else {
            node = new mathMLTree.MathNode("mover", [arrowNode]);
        }
        return node;
    },
});
<commit_msg>Improve MathML for extensible arrows (#1901)<commit_after>// @flow
import defineFunction from "../defineFunction";
import buildCommon from "../buildCommon";
import mathMLTree from "../mathMLTree";
import stretchy from "../stretchy";

import * as html from "../buildHTML";
import * as mml from "../buildMathML";

import type {ParseNode} from "../parseNode";

// Helper function
const paddedNode = group => {
    const node = new mathMLTree.MathNode("mpadded", group ? [group] : []);
    node.setAttribute("width", "+0.6em");
    node.setAttribute("lspace", "0.3em");
    return node;
};

// Stretchy arrows with an optional argument
defineFunction({
    type: "xArrow",
    names: [
        "\\xleftarrow", "\\xrightarrow", "\\xLeftarrow", "\\xRightarrow",
        "\\xleftrightarrow", "\\xLeftrightarrow", "\\xhookleftarrow",
        "\\xhookrightarrow", "\\xmapsto", "\\xrightharpoondown",
        "\\xrightharpoonup", "\\xleftharpoondown", "\\xleftharpoonup",
        "\\xrightleftharpoons", "\\xleftrightharpoons", "\\xlongequal",
        "\\xtwoheadrightarrow", "\\xtwoheadleftarrow", "\\xtofrom",
        // The next 3 functions are here to support the mhchem extension.
        // Direct use of these functions is discouraged and may break someday.
        "\\xrightleftarrows", "\\xrightequilibrium", "\\xleftequilibrium",
    ],
    props: {
        numArgs: 1,
        numOptionalArgs: 1,
    },
    handler({parser, funcName}, args, optArgs) {
        return {
            type: "xArrow",
            mode: parser.mode,
            label: funcName,
            body: args[0],
            below: optArgs[0],
        };
    },
    // Flow is unable to correctly infer the type of `group`, even though it's
    // unamibiguously determined from the passed-in `type` above.
    htmlBuilder(group: ParseNode<"xArrow">, options) {
        const style = options.style;

        // Build the argument groups in the appropriate style.
        // Ref: amsmath.dtx:   \hbox{$\scriptstyle\mkern#3mu{#6}\mkern#4mu$}%

        // Some groups can return document fragments.  Handle those by wrapping
        // them in a span.
        let newOptions = options.havingStyle(style.sup());
        const upperGroup = buildCommon.wrapFragment(
            html.buildGroup(group.body, newOptions, options), options);
        upperGroup.classes.push("x-arrow-pad");

        let lowerGroup;
        if (group.below) {
            // Build the lower group
            newOptions = options.havingStyle(style.sub());
            lowerGroup = buildCommon.wrapFragment(
                html.buildGroup(group.below, newOptions, options), options);
            lowerGroup.classes.push("x-arrow-pad");
        }

        const arrowBody = stretchy.svgSpan(group, options);

        // Re shift: Note that stretchy.svgSpan returned arrowBody.depth = 0.
        // The point we want on the math axis is at 0.5 * arrowBody.height.
        const arrowShift = -options.fontMetrics().axisHeight +
            0.5 * arrowBody.height;
        // 2 mu kern. Ref: amsmath.dtx: #7\if0#2\else\mkern#2mu\fi
        let upperShift = -options.fontMetrics().axisHeight
            - 0.5 * arrowBody.height - 0.111; // 0.111 em = 2 mu
        if (upperGroup.depth > 0.25 || group.label === "\\xleftequilibrium") {
            upperShift -= upperGroup.depth;  // shift up if depth encroaches
        }

        // Generate the vlist
        let vlist;
        if (lowerGroup) {
            const lowerShift = -options.fontMetrics().axisHeight
                + lowerGroup.height + 0.5 * arrowBody.height
                + 0.111;
            vlist = buildCommon.makeVList({
                positionType: "individualShift",
                children: [
                    {type: "elem", elem: upperGroup, shift: upperShift},
                    {type: "elem", elem: arrowBody,  shift: arrowShift},
                    {type: "elem", elem: lowerGroup, shift: lowerShift},
                ],
            }, options);
        } else {
            vlist = buildCommon.makeVList({
                positionType: "individualShift",
                children: [
                    {type: "elem", elem: upperGroup, shift: upperShift},
                    {type: "elem", elem: arrowBody,  shift: arrowShift},
                ],
            }, options);
        }

        // $FlowFixMe: Replace this with passing "svg-align" into makeVList.
        vlist.children[0].children[0].children[1].classes.push("svg-align");

        return buildCommon.makeSpan(["mrel", "x-arrow"], [vlist], options);
    },
    mathmlBuilder(group, options) {
        const arrowNode = stretchy.mathMLnode(group.label);
        let node;

        if (group.body) {
            const upperNode = paddedNode(mml.buildGroup(group.body, options));
            if (group.below) {
                const lowerNode = paddedNode(mml.buildGroup(group.below, options));
                node = new mathMLTree.MathNode(
                    "munderover", [arrowNode, lowerNode, upperNode]
                );
            } else {
                node = new mathMLTree.MathNode("mover", [arrowNode, upperNode]);
            }
        } else if (group.below) {
            const lowerNode = paddedNode(mml.buildGroup(group.below, options));
            node = new mathMLTree.MathNode("munder", [arrowNode, lowerNode]);
        } else {
            // This should never happen.
            // Parser.js throws an error if there is no argument.
            node = paddedNode();
            node = new mathMLTree.MathNode("mover", [arrowNode, node]);
        }
        return node;
    },
});
<|endoftext|>


<commit_before>/*
 * map managment
 *
 * Manages the loading and creation of maps
 *
 */

var logger = new Logger('[goto]');

if (!Memory.world) Memory.world = {};
if (!Memory.world.avoidRooms) Memory.world.avoidRooms = {};

var gotoModule = {};

gotoModule.resumeTravel: function(creep) {
    let dest = getPos(creep.memory._goto.dest);
    return this.travel(creep, dest, {});
};

gotoModule.travel: function(creep, target, args = {}) {
    if (!target) return ERR_INVALID_ARGS;
    if (!(target instanceof RoomPosition)) target = target.pos;

    if (creep.room.controller) {
        if (creep.room.controller.owner && !creep.room.controller.my) {
            this.memory.avoidRooms[creep.room.name] = creep.room.controller.level;
        } else {
            this.memory.avoidRooms[creep.room.name] = undefined;
        }
    }
    if (!creep.memory._goto)
        creep.memory._goto = {
            tick: Game.time,
            stuck: 0,
            cpu: 0,
        };

    let gotoData = creep.memory._goto;
    let isStuck = false;
    if (gotoData.last) {
        gotoData.last = getPos(gotoData.last);
        if (!creep.pos.inRangeTo(gotoData.last, 0)) {
            gotoData.stuck = 0;
        } else {
            isStuck = true;
            gotoData.stuck++;
            visualCircle(creep.pos, 'magenta', (gotoData.stuck * 0.1));
        }
    }

    if (gotoData.stuck >= C.GOTO_STUCK_COUNT) {
        delete gotoData.path;
        args.ignoreCreeps = false;
    }
    if (!isStuck && (Game.time - gotoData.tick) > 1)
        delete gotoData.path;
    if (!gotoData.dest || gotoData.dest.roomName !== target.roomName ||
        gotoData.dest.x !== target.x || gotoData.dest.y !== target.y
    ) delete gotoData.path;
    gotoData.tick = Game.time;
    if (creep.fatigue > 0) {
        visualCircle(creep.pos, 'aqua', 0.25);
        return ERR_TIRED;
    }

    if (!gotoData.path) {
        gotoData.dest = target;
        gotoData.last = undefined;
        let cpuStart = Game.cpu.getUsed();
        let route = this.findRoute(creep.pos, target, args);
        gotoData.cpu = (Game.cpu.getUsed() - cpuStart);
        if (gotoData.cpu > C.GOTO_CPU_ALERT)
            logger.alert('high cpu: ' + (gotoData.cpu).toFixed(2) +
                ', creep: ' + creep.name +
                ', from: ' + creep.pos + ', to: ' + target
            );
        if (route.incomplete)
            logger.debug('failed to find route, cpu: ' + (gotoData.cpu).toFixed(2) +
                ', creep: ' + creep.name +
                ', from: ' + creep.pos + ', to: ' + target
            );
        gotoData.path = serializePath(creep.pos, route.path);
        gotoData.stuck = 0;
    }

    if (!gotoData.path || gotoData.path.length === 0) {
        delete creep.memory._goto;
        return ERR_NO_PATH;
    }
    if (gotoData.last && gotoData.stuck === 0)
        gotoData.path = gotoData.path.substr(1);
    gotoData.last = creep.pos;
    let moveDir = parseInt(gotoData.path[0], 10);
    return creep.move(moveDir);
};

gotoModule.findRoute: function(start, target, args) {
    _.defaults(args, {
        ignoreCreeps: true,
        range: 1,
        maxOps: C.GOTO_MAXOPS,
        maxRooms: 16,
    });

    let validRooms;
    if ((args.useFindRoute && start.roomName !== target.roomName) ||
        Game.map.getRoomLinearDistance(start.roomName, target.roomName) > 2
    ) validRooms = this.findValidRooms(start.roomName, target.roomName, args);

    let callback = (roomName) => {
        if (validRooms && !validRooms[roomName]) return false;
        if (this.memory.avoidRooms[roomName] && !args.allowAvoid)
            return false;
        let room = Game.rooms[roomName];
        if (!room) return;

        let costs = this.getMap(room);

        if (!args.ignoreCreeps)
            costs = this.addCreepsToCosts(room, costs.clone());
        return costs;
    };

    return PathFinder.search(start, {pos: target, range: args.range}, {
        roomCallback: callback,
        maxOps: args.maxOps,
        maxRooms: args.maxRooms,
    });
};

gotoModule.findValidRooms: function(start, target, args = {}) {
    _.defaults(args, {
        restrictDistance: 16,
        preferHighway: true,
    });

    let validRooms = {
        [start]: true,
        [target]: true,
    };
    let callback = (roomName) => {
        let parsedRoom = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName);
        let xMod = parsedRoom[1] % 10;
        let yMod = parsedRoom[2] % 10;
        if (args.preferHighway) {
            if (xMod === 0 || yMod === 0) return 1;
        }
        if (!args.allowSK) {
            if ((xMod >= 4 && xMod <= 6) &&
                (yMod >= 4 && yMod <= 6)
            ) return 10;
        }
        if (!args.allowAvoid && this.memory.avoidRooms[roomName] &&
            roomName !== start && roomName !== target
        ) return Number.POSITIVE_INFINITY;
        return 2.5;
    };

    let route = Game.map.findRoute(start, target, {
        routeCallback: callback,
    });
    if (!_.isArray(route)) return;
    for (const record of route) {
        validRooms[record.room] = true;
    }
    return validRooms;
};

gotoModule.getMap: function(room) {
    var cached = mod.cache.getData(C.CACHE.COST_MATRIX);
    if (!cached.costs) cached.costs = {};
    if (!cached.age) cached.age = {};
    if (!cached.costs[room.name] || (cached.age[room.name] &&
        (cached.age[room.name] + C.GOTO_MAP_CACHE) < Game.time)
    ) {
        let startCPU = Game.cpu.getUsed();
        let costs = new PathFinder.CostMatrix;
        costs = this.addTerrainToCosts(room, costs);
        cached.costs[room.name] = this.addStructuresToCosts(room, costs);
        cached.age[room.name] = Game.time;
        logger.debug('rebuilt cost matrix cache for room: ' + room.name +
            ', cpu used: ' + (Game.cpu.getUsed() - startCPU).toFixed(2)
        );
    }
    return cached.costs[room.name];
};

gotoModule.addTerrainToCosts: function(room, costs) {
    for (var x = 0; x < 50; ++x) {
        for (var y = 0; y < 50; ++y) {
            let cost = 2;
            if (x == 0 || x == 49 || y == 0 || y == 49) cost = 25;
            var terrain = Game.map.getTerrainAt(x, y, room.name);
            if (terrain == 'wall') {
                cost = 0xff;
            } else if (terrain == 'swamp') {
                cost = 10;
            }
            costs.set(x,y, cost);
        }
    }
    return costs;
};

gotoModule.addStructuresToCosts: function(room, costs) {
    for (const structure of room.getStructures()) {
        if (structure instanceof StructureRampart) {
            if (!structure.my && !structure.isPublic)
                costs.set(structure.pos.x, structure.pos.y, 0xff);
        } else if (structure instanceof StructureRoad) {
            costs.set(structure.pos.x, structure.pos.y, 1);
        } else if (structure.structureType !== STRUCTURE_CONTAINER) {
            costs.set(structure.pos.x, structure.pos.y, 0xff);
        }
    }
    for (const construction of room.getConstructionSites()) {
        if (construction.structureType === STRUCTURE_CONTAINER ||
            construction.structureType === STRUCTURE_ROAD ||
            construction.structureType === STRUCTURE_RAMPART
        ) continue;
        costs.set(construction.pos.x, construction.pos.y, 0xff);
    }
    return costs;
};

gotoModule.addCreepsToCosts: function(room, costs) {
    let creeps = room.find(FIND_CREEPS);
    creeps.forEach(creep => costs.set(creep.pos.x, creep.pos.y, 0xff));
    return costs;
};

gotoModule.showMap: function(roomName) {
    if (this.memory.avoidRooms[roomName] && !args.allowAvoid)
        return false;
    let room = Game.rooms[roomName];
    if (!room) return;
    let costs = this.getMap(room);
    costs = this.addCreepsToCosts(room, costs.clone());
    for (var x = 0; x < 50; ++x) {
        for (var y = 0; y < 50; ++y) {
            let cost = costs.get(x,y);
            new RoomVisual(roomName).text(cost, x, (y + 0.4), {
                color: '#51d181',
                font: 0.3,
            });
        }
    }
};

Object.defineProperty(gotoModule, 'memory', {
    get: function() {
        return Memory.world;
    },
    set: function(value) {
        Memory.world = value;
    },
});

var getPos = function(pos) {
    return new RoomPosition(pos.x, pos.y, pos.roomName);
};

var serializePath = function(startPos, path) {
    let serialPath = '';
    let lastPos = startPos;
    for (const pos of path) {
        //new RoomVisual(pos.roomName).line(pos, lastPos, { color: 'red', lineStyle: "dashed" });
        if (pos.roomName === lastPos.roomName)
            serialPath += lastPos.getDirectionTo(pos);
        lastPos = pos;
    }
    return serialPath;
};

var visualCircle = function(pos, color, opacity) {
    new RoomVisual(pos.roomName).circle(pos, {
        radius: 0.5,
        fill: 'transparent',
        stroke: color,
        strokeWidth: 0.2,
        opacity: opacity,
    });
};

module.exports = gotoModule;
<commit_msg>fix goto<commit_after>/*
 * map managment
 *
 * Manages the loading and creation of maps
 *
 */

var logger = new Logger('[goto]');

if (!Memory.world) Memory.world = {};
if (!Memory.world.avoidRooms) Memory.world.avoidRooms = {};

var gotoModule = {};

gotoModule.resumeTravel = function(creep) {
    let dest = getPos(creep.memory._goto.dest);
    return this.travel(creep, dest, {});
};

gotoModule.travel = function(creep, target, args = {}) {
    if (!target) return ERR_INVALID_ARGS;
    if (!(target instanceof RoomPosition)) target = target.pos;

    if (creep.room.controller) {
        if (creep.room.controller.owner && !creep.room.controller.my) {
            this.memory.avoidRooms[creep.room.name] = creep.room.controller.level;
        } else {
            this.memory.avoidRooms[creep.room.name] = undefined;
        }
    }
    if (!creep.memory._goto)
        creep.memory._goto = {
            tick: Game.time,
            stuck: 0,
            cpu: 0,
        };

    let gotoData = creep.memory._goto;
    let isStuck = false;
    if (gotoData.last) {
        gotoData.last = getPos(gotoData.last);
        if (!creep.pos.inRangeTo(gotoData.last, 0)) {
            gotoData.stuck = 0;
        } else {
            isStuck = true;
            gotoData.stuck++;
            visualCircle(creep.pos, 'magenta', (gotoData.stuck * 0.1));
        }
    }

    if (gotoData.stuck >= C.GOTO_STUCK_COUNT) {
        delete gotoData.path;
        args.ignoreCreeps = false;
    }
    if (!isStuck && (Game.time - gotoData.tick) > 1)
        delete gotoData.path;
    if (!gotoData.dest || gotoData.dest.roomName !== target.roomName ||
        gotoData.dest.x !== target.x || gotoData.dest.y !== target.y
    ) delete gotoData.path;
    gotoData.tick = Game.time;
    if (creep.fatigue > 0) {
        visualCircle(creep.pos, 'aqua', 0.25);
        return ERR_TIRED;
    }

    if (!gotoData.path) {
        gotoData.dest = target;
        gotoData.last = undefined;
        let cpuStart = Game.cpu.getUsed();
        let route = this.findRoute(creep.pos, target, args);
        gotoData.cpu = (Game.cpu.getUsed() - cpuStart);
        if (gotoData.cpu > C.GOTO_CPU_ALERT)
            logger.alert('high cpu: ' + (gotoData.cpu).toFixed(2) +
                ', creep: ' + creep.name +
                ', from: ' + creep.pos + ', to: ' + target
            );
        if (route.incomplete)
            logger.debug('failed to find route, cpu: ' + (gotoData.cpu).toFixed(2) +
                ', creep: ' + creep.name +
                ', from: ' + creep.pos + ', to: ' + target
            );
        gotoData.path = serializePath(creep.pos, route.path);
        gotoData.stuck = 0;
    }

    if (!gotoData.path || gotoData.path.length === 0) {
        delete creep.memory._goto;
        return ERR_NO_PATH;
    }
    if (gotoData.last && gotoData.stuck === 0)
        gotoData.path = gotoData.path.substr(1);
    gotoData.last = creep.pos;
    let moveDir = parseInt(gotoData.path[0], 10);
    return creep.move(moveDir);
};

gotoModule.findRoute = function(start, target, args) {
    _.defaults(args, {
        ignoreCreeps: true,
        range: 1,
        maxOps: C.GOTO_MAXOPS,
        maxRooms: 16,
    });

    let validRooms;
    if ((args.useFindRoute && start.roomName !== target.roomName) ||
        Game.map.getRoomLinearDistance(start.roomName, target.roomName) > 2
    ) validRooms = this.findValidRooms(start.roomName, target.roomName, args);

    let callback = (roomName) => {
        if (validRooms && !validRooms[roomName]) return false;
        if (this.memory.avoidRooms[roomName] && !args.allowAvoid)
            return false;
        let room = Game.rooms[roomName];
        if (!room) return;

        let costs = this.getMap(room);

        if (!args.ignoreCreeps)
            costs = this.addCreepsToCosts(room, costs.clone());
        return costs;
    };

    return PathFinder.search(start, {pos: target, range: args.range}, {
        roomCallback: callback,
        maxOps: args.maxOps,
        maxRooms: args.maxRooms,
    });
};

gotoModule.findValidRooms = function(start, target, args = {}) {
    _.defaults(args, {
        restrictDistance: 16,
        preferHighway: true,
    });

    let validRooms = {
        [start]: true,
        [target]: true,
    };
    let callback = (roomName) => {
        let parsedRoom = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName);
        let xMod = parsedRoom[1] % 10;
        let yMod = parsedRoom[2] % 10;
        if (args.preferHighway) {
            if (xMod === 0 || yMod === 0) return 1;
        }
        if (!args.allowSK) {
            if ((xMod >= 4 && xMod <= 6) &&
                (yMod >= 4 && yMod <= 6)
            ) return 10;
        }
        if (!args.allowAvoid && this.memory.avoidRooms[roomName] &&
            roomName !== start && roomName !== target
        ) return Number.POSITIVE_INFINITY;
        return 2.5;
    };

    let route = Game.map.findRoute(start, target, {
        routeCallback: callback,
    });
    if (!_.isArray(route)) return;
    for (const record of route) {
        validRooms[record.room] = true;
    }
    return validRooms;
};

gotoModule.getMap = function(room) {
    var cached = mod.cache.getData(C.CACHE.COST_MATRIX);
    if (!cached.costs) cached.costs = {};
    if (!cached.age) cached.age = {};
    if (!cached.costs[room.name] || (cached.age[room.name] &&
        (cached.age[room.name] + C.GOTO_MAP_CACHE) < Game.time)
    ) {
        let startCPU = Game.cpu.getUsed();
        let costs = new PathFinder.CostMatrix;
        costs = this.addTerrainToCosts(room, costs);
        cached.costs[room.name] = this.addStructuresToCosts(room, costs);
        cached.age[room.name] = Game.time;
        logger.debug('rebuilt cost matrix cache for room: ' + room.name +
            ', cpu used: ' + (Game.cpu.getUsed() - startCPU).toFixed(2)
        );
    }
    return cached.costs[room.name];
};

gotoModule.addTerrainToCosts = function(room, costs) {
    for (var x = 0; x < 50; ++x) {
        for (var y = 0; y < 50; ++y) {
            let cost = 2;
            if (x == 0 || x == 49 || y == 0 || y == 49) cost = 25;
            var terrain = Game.map.getTerrainAt(x, y, room.name);
            if (terrain == 'wall') {
                cost = 0xff;
            } else if (terrain == 'swamp') {
                cost = 10;
            }
            costs.set(x,y, cost);
        }
    }
    return costs;
};

gotoModule.addStructuresToCosts = function(room, costs) {
    for (const structure of room.getStructures()) {
        if (structure instanceof StructureRampart) {
            if (!structure.my && !structure.isPublic)
                costs.set(structure.pos.x, structure.pos.y, 0xff);
        } else if (structure instanceof StructureRoad) {
            costs.set(structure.pos.x, structure.pos.y, 1);
        } else if (structure.structureType !== STRUCTURE_CONTAINER) {
            costs.set(structure.pos.x, structure.pos.y, 0xff);
        }
    }
    for (const construction of room.getConstructionSites()) {
        if (construction.structureType === STRUCTURE_CONTAINER ||
            construction.structureType === STRUCTURE_ROAD ||
            construction.structureType === STRUCTURE_RAMPART
        ) continue;
        costs.set(construction.pos.x, construction.pos.y, 0xff);
    }
    return costs;
};

gotoModule.addCreepsToCosts = function(room, costs) {
    let creeps = room.find(FIND_CREEPS);
    creeps.forEach(creep => costs.set(creep.pos.x, creep.pos.y, 0xff));
    return costs;
};

gotoModule.showMap = function(roomName) {
    if (this.memory.avoidRooms[roomName] && !args.allowAvoid)
        return false;
    let room = Game.rooms[roomName];
    if (!room) return;
    let costs = this.getMap(room);
    costs = this.addCreepsToCosts(room, costs.clone());
    for (var x = 0; x < 50; ++x) {
        for (var y = 0; y < 50; ++y) {
            let cost = costs.get(x,y);
            new RoomVisual(roomName).text(cost, x, (y + 0.4), {
                color: '#51d181',
                font: 0.3,
            });
        }
    }
};

Object.defineProperty(gotoModule, 'memory', {
    get: function() {
        return Memory.world;
    },
    set: function(value) {
        Memory.world = value;
    },
});

var getPos = function(pos) {
    return new RoomPosition(pos.x, pos.y, pos.roomName);
};

var serializePath = function(startPos, path) {
    let serialPath = '';
    let lastPos = startPos;
    for (const pos of path) {
        //new RoomVisual(pos.roomName).line(pos, lastPos, { color: 'red', lineStyle: "dashed" });
        if (pos.roomName === lastPos.roomName)
            serialPath += lastPos.getDirectionTo(pos);
        lastPos = pos;
    }
    return serialPath;
};

var visualCircle = function(pos, color, opacity) {
    new RoomVisual(pos.roomName).circle(pos, {
        radius: 0.5,
        fill: 'transparent',
        stroke: color,
        strokeWidth: 0.2,
        opacity: opacity,
    });
};

module.exports = gotoModule;
<|endoftext|>


<commit_before>var expect = require('chai').expect
  , os = require('os')
  , fs = require('fs')
  , path = require('path')
  , crypto = require('crypto')
  , exec = require('child_process').exec
  , scripts = require('../');

describe('git-scripts', function() {
  beforeEach(function(done) {
    var path = os.tmpdir() + '/' + crypto.randomBytes(20).toString('hex')
      , self = this;

    fs.mkdir(path, 0700, function() {
      self.proj = scripts(path);
      done();
    });
  });

  afterEach(function(done) {
    exec('rm -rf ' + this.proj.path, done);
  });

  describe('when the path is not a git repo', function() {
    describe('isGitRepo()', function() {
      it('should be false', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path is a git repo', function() {
    beforeEach(function(done) {
      exec('git init', {cwd: this.proj.path}, done);
    });

    describe('isGitRepo()', function() {
      it('should be true', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should move the old hooks directory and create the new symlink', function(done) {
        var self = this;
        this.proj.install(function(err) {
          var gitPath = self.proj.path + '/.git'
            , binHooksPath = path.resolve(gitPath, fs.readlinkSync(gitPath + '/hooks'));

          expect(binHooksPath).to.equal(path.normalize(__dirname + '/../bin/hooks'));
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.true;
          done(err);
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when installed', function() {
    beforeEach(function(done) {
      var self = this;
      exec('git init', {cwd: this.proj.path}, function() {
        self.proj.install(done);
      });
    });

    describe('installed()', function() {
      it('should be true', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should succeed', function(done) {
        var self = this;
        this.proj.uninstall(function(err) {
          expect(fs.existsSync(self.proj.path + '/.git/hooks')).to.be.true;
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.false;
          done(err);
        });
      });
    });
  });

  describe('when the path has no package.json', function() {
    describe('script()', function() {
      it('should be an error', function(done) {
        this.proj.script('foo', function(err, cmd) {
          expect(err).to.be.an.instanceof(Error);
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be an error', function(done) {
        this.proj.run('foo', function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path has package.json', function() {
    beforeEach(function(done) {
      var pkg = {git: {scripts: {
        foo: 'echo "hello, $0"',
        bar: 'exit 1'
      }}};
      fs.writeFile(this.proj.path + '/package.json', JSON.stringify(pkg), done);
    });

    describe('script()', function() {
      it('should parse command', function(done) {
        this.proj.script('foo', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.equal('echo "hello, $0"');
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be able to supply arguments', function(done) {
        this.proj.run('foo', ['world'], done);
      });

      it('should be an error when the command failed', function(done) {
        this.proj.run('bar', function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });

      it('should not be an error when the command does not exist', function(done) {
        this.proj.run('any', function(err) {
          expect(err).to.not.exist;
          done();
        });
      });
    });
  });
});
<commit_msg>add an assert<commit_after>var expect = require('chai').expect
  , os = require('os')
  , fs = require('fs')
  , path = require('path')
  , crypto = require('crypto')
  , exec = require('child_process').exec
  , scripts = require('../');

describe('git-scripts', function() {
  beforeEach(function(done) {
    var path = os.tmpdir() + '/' + crypto.randomBytes(20).toString('hex')
      , self = this;

    fs.mkdir(path, 0700, function() {
      self.proj = scripts(path);
      done();
    });
  });

  afterEach(function(done) {
    exec('rm -rf ' + this.proj.path, done);
  });

  describe('when the path is not a git repo', function() {
    describe('isGitRepo()', function() {
      it('should be false', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path is a git repo', function() {
    beforeEach(function(done) {
      exec('git init', {cwd: this.proj.path}, done);
    });

    describe('isGitRepo()', function() {
      it('should be true', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should move the old hooks directory and create the new symlink', function(done) {
        var self = this;
        this.proj.install(function(err) {
          var gitPath = self.proj.path + '/.git'
            , binHooksPath = path.resolve(gitPath, fs.readlinkSync(gitPath + '/hooks'));

          expect(binHooksPath).to.equal(path.normalize(__dirname + '/../bin/hooks'));
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.true;
          done(err);
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when installed', function() {
    beforeEach(function(done) {
      var self = this;
      exec('git init', {cwd: this.proj.path}, function() {
        self.proj.install(done);
      });
    });

    describe('installed()', function() {
      it('should be true', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should succeed', function(done) {
        var self = this;
        this.proj.uninstall(function(err) {
          expect(fs.existsSync(self.proj.path + '/.git/hooks')).to.be.true;
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.false;
          done(err);
        });
      });
    });
  });

  describe('when the path has no package.json', function() {
    describe('script()', function() {
      it('should be an error', function(done) {
        this.proj.script('foo', function(err, cmd) {
          expect(err).to.be.an.instanceof(Error);
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be an error', function(done) {
        this.proj.run('foo', function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path has package.json', function() {
    beforeEach(function(done) {
      var pkg = {git: {scripts: {
        foo: 'echo "hello, $0"',
        bar: 'exit 1'
      }}};
      fs.writeFile(this.proj.path + '/package.json', JSON.stringify(pkg), done);
    });

    describe('script()', function() {
      it('should parse command', function(done) {
        this.proj.script('foo', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.equal('echo "hello, $0"');
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be able to supply arguments', function(done) {
        this.proj.run('foo', ['world'], done);
      });

      it('should be an error when the command failed', function(done) {
        this.proj.run('bar', function(err) {
          expect(err).to.be.an.instanceof(Error);
          expect(err).to.have.property('code', 1);
          done();
        });
      });

      it('should not be an error when the command does not exist', function(done) {
        this.proj.run('any', function(err) {
          expect(err).to.not.exist;
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>import test from 'ava';
import { readFileSync, writeFileSync } from 'fs';
import { rollup } from 'rollup';
import sass from '..';

const sassOptions = {
    outputStyle: 'compressed'
};

test('should import *.scss and *.sass files', t => {
    return rollup({
        entry: 'fixtures/basic/index.js',
        plugins: [
            sass({
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/basic/style1.scss').toString();
        const style2 = readFileSync('fixtures/basic/style2.sass').toString();

        t.true(code.indexOf(style1) > -1);
        t.true(code.indexOf(style2) > -1);
    });
});

test('should process code with output function', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-function/index.js',
        plugins: [
            sass({
                output(code) {
                    return outputCode = code;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-function/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode, `${style}\n`);
    })
});

test('should process code with output path', t => {
    writeFileSync('fixtures/output-string/output.css', '');

    return rollup({
        entry: 'fixtures/output-string/index.js',
        plugins: [
            sass({
                output: 'fixtures/output-string/output.css',
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-string/style.scss').toString();
        const output = readFileSync('fixtures/output-string/output.css').toString();

        t.is(output, `${style}\n`);
    })
});

test('should process support promise', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-promise/index.js',
        plugins: [
            sass({
                output(code) {
                    return new Promise((resolve) => {
                        setTimeout(() => {
                            resolve(outputCode = code)
                        }, 100);
                    });
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-promise/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode, `${style}\n`);
    });
});

test('should insert CSS into head tag', t => {
    return rollup({
        entry: 'fixtures/insert-css/index.js',
        plugins: [
            sass({
                insert: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/insert-css/style.scss').toString();

        global.window = {};
        global.document = {
            innerHTML: '',
            head: {
                appendChild(mockNode) {
                    t.true(mockNode.hasOwnProperty('setAttribute'));
                    t.is(mockNode.innerHTML, `${style}\n`);
                }
            },
            createElement() {
                return {
                    setAttribute(key, value) {
                        if (key === 'type') {
                            t.is(value, 'text/css');
                        }
                    }
                };
            }
        };

        new Function(code)();
    });
});<commit_msg>Trim output code<commit_after>import test from 'ava';
import { readFileSync, writeFileSync } from 'fs';
import { rollup } from 'rollup';
import sass from '..';

const sassOptions = {
    outputStyle: 'compressed'
};

test('should import *.scss and *.sass files', t => {
    return rollup({
        entry: 'fixtures/basic/index.js',
        plugins: [
            sass({
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/basic/style1.scss').toString();
        const style2 = readFileSync('fixtures/basic/style2.sass').toString();

        t.true(code.indexOf(style1) > -1);
        t.true(code.indexOf(style2) > -1);
    });
});

test('should process code with output function', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-function/index.js',
        plugins: [
            sass({
                output(code) {
                    return outputCode = code;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-function/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style}`);
    })
});

test('should process code with output path', t => {
    writeFileSync('fixtures/output-string/output.css', '');

    return rollup({
        entry: 'fixtures/output-string/index.js',
        plugins: [
            sass({
                output: 'fixtures/output-string/output.css',
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-string/style.scss').toString();
        const output = readFileSync('fixtures/output-string/output.css').toString();

        t.is(output.trim(), `${style}`);
    })
});

test('should process support promise', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-promise/index.js',
        plugins: [
            sass({
                output(code) {
                    return new Promise((resolve) => {
                        setTimeout(() => {
                            resolve(outputCode = code)
                        }, 100);
                    });
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/output-promise/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style}`);
    });
});

test('should insert CSS into head tag', t => {
    return rollup({
        entry: 'fixtures/insert-css/index.js',
        plugins: [
            sass({
                insert: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/insert-css/style.scss').toString();

        global.window = {};
        global.document = {
            innerHTML: '',
            head: {
                appendChild(mockNode) {
                    t.true(mockNode.hasOwnProperty('setAttribute'));
                    t.is(mockNode.innerHTML.trim(), `${style}`);
                }
            },
            createElement() {
                return {
                    setAttribute(key, value) {
                        if (key === 'type') {
                            t.is(value, 'text/css');
                        }
                    }
                };
            }
        };

        new Function(code)();
    });
});<|endoftext|>


<commit_before>import _ from 'underscore';
import test from 'blue-tape';

import createAdapter from '../src';
import {ADAPTABLE_METHODS} from '../src';

const DEFAULTS = {
  storage: [
    {key: 'x', value: 1},
    {key: 'x', value: 2},
    {key: 'x', value: 3},
    {key: 'y', value: 4},
    {key: 'z', value: 5},
    {key: 'w', value: -1},
  ],
};

test('adapter factory rejects invalid storages', (assert) => {
  const sut = createAdapter;
  const adaptable = ADAPTABLE_METHODS.reduce((curr, prev) => {
    prev[curr] = {};
    return prev;
  }, {});
  const noStorage = sut.bind(sut, {});
  const arrayStorage = sut.bind(sut, {storage: DEFAULTS});
  const invalidStorage = sut.bind(sut, {storage: 'foo'});
  const adaptableStorage = sut.bind(sut, {storage: adaptable});

  assert.doesNotThrow(arrayStorage, 'should support array storage');
  assert.doesNotThrow(adaptableStorage, 'should support adaptable storage');

  assert.throws(noStorage, /`options.storage` is missing/i,
    'should have a storage');
  assert.throws(invalidStorage,
    /`options.storage` should be a queryable or an array/i,
    'should have a valid storage');
  assert.end();
});

test('adapter#find', (sub) => {
  sub.test('exists', (assert) => {
    const sut = createAdapter(DEFAULTS);

    assert.ok(sut.find, 'should exist');
    assert.end();
  });

  sub.test('returns an array', (assert) => {
    const sut = createAdapter(DEFAULTS);
    const result = sut.find();

    assert.ok(_.isArray(result), 'should return an array');
    assert.end();
  });
});

test('adapter find supports querying', (assert) => {
  const sut = createAdapter(DEFAULTS);
  const query = {
    key: 'x',
  };
  const result = sut.find(query);

  assert.ok(_.every(result, (r) => r.key === 'x'), 'result should match query');
  assert.end();
});

test('adapter find supports projection', (assert) => {
  const sut = createAdapter(DEFAULTS);
  const projection = {
    key: false,
    value: true,
  };
  const result = sut.find({}, projection);

  assert.ok(_.every(result, (r) => 'value' in r && !('key' in r)),
  'should contain selected keys only');
  assert.end();
});
<commit_msg>Fix more typos in test.<commit_after>import _ from 'underscore';
import test from 'blue-tape';

import createAdapter from '../src';
import {ADAPTABLE_METHODS} from '../src';

const DEFAULTS = {
  storage: [
    {key: 'x', value: 1},
    {key: 'x', value: 2},
    {key: 'x', value: 3},
    {key: 'y', value: 4},
    {key: 'z', value: 5},
    {key: 'w', value: -1},
  ],
};

test('adapter factory rejects invalid storages', (assert) => {
  const sut = createAdapter;
  const adaptable = ADAPTABLE_METHODS.reduce((curr, prev) => {
    prev[curr] = {};
    return prev;
  }, {});
  const noStorage = sut.bind(sut, {});
  const arrayStorage = sut.bind(sut, {storage: DEFAULTS});
  const invalidStorage = sut.bind(sut, {storage: 'foo'});
  const adaptableStorage = sut.bind(sut, {storage: adaptable});

  assert.doesNotThrow(arrayStorage, 'should support array storage');
  assert.doesNotThrow(adaptableStorage, 'should support adaptable storage');

  assert.throws(noStorage, /`options.storage` is missing/i,
    'should have a storage');
  assert.throws(invalidStorage,
    /`options.storage` should be an adaptable or an array/i,
    'should have a valid storage');
  assert.end();
});

test('adapter#find', (sub) => {
  sub.test('exists', (assert) => {
    const sut = createAdapter(DEFAULTS);

    assert.ok(sut.find, 'should exist');
    assert.end();
  });

  sub.test('returns an array', (assert) => {
    const sut = createAdapter(DEFAULTS);
    const result = sut.find();

    assert.ok(_.isArray(result), 'should return an array');
    assert.end();
  });
});

test('adapter find supports querying', (assert) => {
  const sut = createAdapter(DEFAULTS);
  const query = {
    key: 'x',
  };
  const result = sut.find(query);

  assert.ok(_.every(result, (r) => r.key === 'x'), 'result should match query');
  assert.end();
});

test('adapter find supports projection', (assert) => {
  const sut = createAdapter(DEFAULTS);
  const projection = {
    key: false,
    value: true,
  };
  const result = sut.find({}, projection);

  assert.ok(_.every(result, (r) => 'value' in r && !('key' in r)),
  'should contain selected keys only');
  assert.end();
});
<|endoftext|>