<commit_before>

function testAssignmentInCondition() {
    var other = 'prop';
    var name = 'value';
    console.assert((other = name) === 'value');
}

function testShortCurcuit() {
    var lhs = false;
    // LHS is false, RHS is not evaluated, result is false
    var isFalse = lhs && console.error('&& Not shortCurcuited');
    console.assert(!isFalse);
    lhs = true;
    // LHS is true, RHS is not evaluated, result is true
    var isTrue = lhs || console.error('|| Not shortCurcuited');
    console.assert(isTrue);
}

function testTypeof() {
    var isAnUndefined = typeof anUndefined !== "undefined";
    console.assert(!isAnUndefined);
}

function testConditionalExpression() {
  var isNull = null;
  var isTrue = isNull ? isNull.name() : true;
  console.assert(isTrue);
}

function testForIn() {
  var prop;
  var loaded = {foo: false};
  for (prop in loaded) {
      if (!loaded[prop])
              break;
  }
}

function testConst() {
  const isConst = 5;
  console.assert(isConst);
}

function testDoWhile() {
  var index = 0;
  do {
      if (index === 1)
          break;
      index++;
  } while (index <= 2);
  console.assert(index == 1);
}

function testSwitch() {
  var obj = { foo: 5};
  switch(obj.foo){
    case 5:
       obj.ok = true;
     break;
    default:
     obj.ok = false;
  }
  console.assert(obj.ok);
}

function testEval() {
  'use strict';

  // LHS for the compile context of the devtools script preprocessor,
  // RHS for the runtime context of the devtools script preprocessor...
  var global = ('global', eval)('this') || window;

  global.Querypoint = {};
  console.assert(typeof global.Querypoint === 'object');
}

function testTypeofInSwitch(GeneratorReturn) {
  switch (typeof GeneratorReturn) {
    case 'function':
      return;
    case 'undefined':
      return;
    default:
      throw new Error('FAIL testTypeofInSwitch');
  }
}

function testPropertyAccessInCase() {
  var v = 1;
  var obj = {prop: 1};
  switch(v) {
    case obj.prop: return;
    default: throw new Error('FAIL testPropertyAccessInCase');
  }
}

function onLoad() {
  testPropertyAccessInCase();
  testTypeofInSwitch();
  testAssignmentInCondition();
  testShortCurcuit();
  testTypeof();
  testConditionalExpression();
  testForIn();
  testConst();
  testDoWhile();
  testEval();
  console.warn("Tests complete");
}

window.addEventListener('load',onLoad);
<commit_msg>Log progress on running tests<commit_after>

function testAssignmentInCondition() {
    var other = 'prop';
    var name = 'value';
    console.assert((other = name) === 'value');
}

function testShortCurcuit() {
    var lhs = false;
    // LHS is false, RHS is not evaluated, result is false
    var isFalse = lhs && console.error('&& Not shortCurcuited');
    console.assert(!isFalse);
    lhs = true;
    // LHS is true, RHS is not evaluated, result is true
    var isTrue = lhs || console.error('|| Not shortCurcuited');
    console.assert(isTrue);
}

function testTypeof() {
    var isAnUndefined = typeof anUndefined !== "undefined";
    console.assert(!isAnUndefined);
}

function testConditionalExpression() {
  var isNull = null;
  var isTrue = isNull ? isNull.name() : true;
  console.assert(isTrue);
}

function testForIn() {
  var prop;
  var loaded = {foo: false};
  for (prop in loaded) {
      if (!loaded[prop])
              break;
  }
}

function testConst() {
  const isConst = 5;
  console.assert(isConst);
}

function testDoWhile() {
  var index = 0;
  do {
      if (index === 1)
          break;
      index++;
  } while (index <= 2);
  console.assert(index == 1);
}

function testSwitch() {
  var obj = { foo: 5};
  switch(obj.foo){
    case 5:
       obj.ok = true;
     break;
    default:
     obj.ok = false;
  }
  console.assert(obj.ok);
}

function testEval() {
  'use strict';

  // LHS for the compile context of the devtools script preprocessor,
  // RHS for the runtime context of the devtools script preprocessor...
  var global = ('global', eval)('this') || window;

  global.Querypoint = {};
  console.assert(typeof global.Querypoint === 'object');
}

function testTypeofInSwitch(GeneratorReturn) {
  switch (typeof GeneratorReturn) {
    case 'function':
      return;
    case 'undefined':
      return;
    default:
      throw new Error('FAIL testTypeofInSwitch');
  }
}

function testPropertyAccessInCase() {
  var v = 1;
  var obj = {prop: 1};
  switch(v) {
    case obj.prop: return;
    default: throw new Error('FAIL testPropertyAccessInCase');
  }
}

function test(aTestCase) {
  console.log('start ' + aTestCase);
  window[aTestCase]();
  console.log('end ' + aTestCase);
}

function onLoad() {
  test('testTypeofInSwitch');
  test('testPropertyAccessInCase');
  test('testAssignmentInCondition');
  test('testShortCurcuit');
  test('testTypeof');
  test('testConditionalExpression');
  test('testForIn');
  test('testConst');
  test('testDoWhile');
  test('testEval');
  console.warn("Tests complete");
}

window.addEventListener('load',onLoad);
<|endoftext|>


<commit_before>'use strict'

import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import chaiSubset from 'chai-subset'
import nock from 'nock'
import path from 'path'

import cep from '../../src/cep-promise.js'
import CepPromiseError from '../../src/errors/cep-promise.js'

chai.use(chaiAsPromised)
chai.use(chaiSubset)

let expect = chai.expect

describe('cep-promise (unit)', () => {
  describe('when imported', () => {
    it('should return a Function', () => {
      expect(cep).to.be.a('function')
    })
  })

  describe('when invoked', () => {
    it('should return a Promise', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      const cepPromise = cep('05010000')
      expect(cepPromise.then).to.be.a('function')
      expect(cepPromise.catch).to.be.a('function')
    })
  })

  describe('when invoked without arguments', () => {
    it('should reject with "validation_error"', () => {
      return cep()
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Array', () => {
    it('should reject with "validation_error"', () => {
      return cep([1, 2, 3])
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Object', () => {
    it('should reject with "validation_error"', () => {
      return cep({ nintendo: true, ps: false, xbox: false })
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Function', () => {
    it('should reject with "validation_error"', () => {
      return cep(function zelda () { return 'link' })
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with a valid "05010000" String', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('05010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when invoked with a valid 5010000 Number', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep(5010000)).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when request returns with error but with an unkown XML schema and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(500, path.join(__dirname, '/fixtures/response-unknown-format.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when its not possible to parse the returning XML and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when http request to Correios fails and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when invoked with an inexistend "99999999" CEP', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(500, path.join(__dirname, '/fixtures/response-cep-not-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/99999999/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json'))

      return cep('99999999')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'CEP NAO ENCONTRADO',
                service: 'correios'
              }, {
                message: 'CEP não encontrado na base do ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when invoked with an invalid "123456789" CEP', () => {
    it('should reject with "validation_error"', () => {
      return cep('123456789')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'CEP deve conter exatamente 8 caracteres.',
              type: 'validation_error',
              errors: [{
                service: 'cep_validation',
                message: 'CEP informado possui mais do que 8 caracteres.'
              }]
            })
        })
    })
  })

  describe('when http request fails both for primary and secondary service with bad response', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .reply(400, '
Bad Request (400)
')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Erro ao se conectar com o serviço dos Correios.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when http request has unformated xml and secondary service fails', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .reply(400, '
Bad Request (400)
')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Não foi possível interpretar o XML de resposta.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when http request fails both for primary and secondary service with error', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Erro ao se conectar com o serviço dos Correios.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  afterEach(() => {
    nock.cleanAll()
  })
})
<commit_msg>chore(tests): fix some typos<commit_after>'use strict'

import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import chaiSubset from 'chai-subset'
import nock from 'nock'
import path from 'path'

import cep from '../../src/cep-promise.js'
import CepPromiseError from '../../src/errors/cep-promise.js'

chai.use(chaiAsPromised)
chai.use(chaiSubset)

let expect = chai.expect

describe('cep-promise (unit)', () => {
  describe('when imported', () => {
    it('should return a Function', () => {
      expect(cep).to.be.a('function')
    })
  })

  describe('when invoked', () => {
    it('should return a Promise', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      const cepPromise = cep('05010000')
      expect(cepPromise.then).to.be.a('function')
      expect(cepPromise.catch).to.be.a('function')
    })
  })

  describe('when invoked without arguments', () => {
    it('should reject with "validation_error"', () => {
      return cep()
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Array', () => {
    it('should reject with "validation_error"', () => {
      return cep([1, 2, 3])
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Object', () => {
    it('should reject with "validation_error"', () => {
      return cep({ nintendo: true, ps: false, xbox: false })
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with an Function', () => {
    it('should reject with "validation_error"', () => {
      return cep(function zelda () { return 'link' })
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Erro ao inicializar a instância do CepPromise.',
              type: 'validation_error',
              errors: [{
                message: 'Você deve chamar o construtor utilizando uma String ou Number.',
                service: 'cep_validation'
              }]
            })
        })
    })
  })

  describe('when invoked with a valid "05010000" String', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('05010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when invoked with a valid 5010000 Number', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep(5010000)).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when request returns with error but with an unknown XML schema and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(500, path.join(__dirname, '/fixtures/response-unknown-format.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when its not possible to parse the returned XML and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when http request to Correios fails and then succeed to the failover service', () => {
    it('should fulfill with correct address', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))

      return expect(cep('5010000')).to.eventually.deep.equal({
        cep: '05010000',
        state: 'SP',
        city: 'São Paulo',
        neighborhood: 'Perdizes',
        street: 'Rua Caiubi'
      })
    })
  })

  describe('when invoked with an inexistent "99999999" CEP', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(500, path.join(__dirname, '/fixtures/response-cep-not-found.xml'))
      nock('https://viacep.com.br')
        .get('/ws/99999999/json/')
        .replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json'))

      return cep('99999999')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'CEP NAO ENCONTRADO',
                service: 'correios'
              }, {
                message: 'CEP não encontrado na base do ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when invoked with an invalid "123456789" CEP', () => {
    it('should reject with "validation_error"', () => {
      return cep('123456789')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'CEP deve conter exatamente 8 caracteres.',
              type: 'validation_error',
              errors: [{
                service: 'cep_validation',
                message: 'CEP informado possui mais do que 8 caracteres.'
              }]
            })
        })
    })
  })

  describe('when http request fails both for primary and secondary service with bad response', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .reply(400, '
Bad Request (400)
')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Erro ao se conectar com o serviço dos Correios.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when http request has unformatted xml and secondary service fails', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .reply(400, '
Bad Request (400)
')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Não foi possível interpretar o XML de resposta.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  describe('when http request fails both for primary and secondary service with error', () => {
    it('should reject with "service_error"', () => {
      nock('https://apps.correios.com.br')
        .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
      nock('https://viacep.com.br')
        .get('/ws/05010000/json/')
        .replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')

      return cep('05010000')
        .catch((error) => {
          return expect(error)
            .to.be.an.instanceOf(CepPromiseError)
            .and.containSubset({
              message: 'Todos os serviços de CEP retornaram erro.',
              type: 'service_error',
              errors: [{
                message: 'Erro ao se conectar com o serviço dos Correios.',
                service: 'correios'
              }, {
                message: 'Erro ao se conectar com o serviço ViaCEP.',
                service: 'viacep'
              }]
            })
        })
    })
  })

  afterEach(() => {
    nock.cleanAll()
  })
})
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const gutil = require('gulp-util');
const express = require('express');
const {spawn} = require('child_process');
const webpackMiddleware = require('webpack-dev-middleware');
const runSequence = require('run-sequence');
const utils = require('../../utils');
const projectConfig = require('../../../config/project');
const {compiler} = require('../webpack');

module.exports = (gulp, plugins, options) => {
  let server;

  const port = projectConfig.servers.cdn.port();
  const clientFilesPath = projectConfig.clientFilesPath();
  const bundler = compiler({debug: true, hot: options.hot});

  const runServer = () => {
    const env = Object.create(process.env);
    if (server) {
      server.kill('SIGTERM');
    } else {
      console.log('');
      gutil.log('Application is now available at ', gutil.colors.magenta(`http://localhost:3000${env.MOUNT_POINT || '/'}`));
      gutil.log('Server log is written to ', gutil.colors.magenta('./target/server.log'));
      gulp.start('mocha');
    }

    env.NODE_ENV = 'development';
    env.DEBUG = 'wix:*,wnp:*';

    server = spawn('node', [path.resolve(options.entryPoint)], {env});
    [server.stdout, server.stderr].forEach(stream =>
      stream.on('data', writeToServerLog)
    );

    const displayErrors = _.debounce(() => {
      gutil.log(
        gutil.colors.red('There are errors! Please check'),
        gutil.colors.magenta('./target/server.log')
      );
    }, 500);

    server.stderr.on('data', buffer => {
      if (buffer.toString().includes('wix:error')) {
        displayErrors();
      }
    });

    return server;
  };

  // TODO: change gulp tasks to simple async functions
  options = Object.assign(options, {
    done: options.server ? runServer : function () {},
    watch: true
  });

  require('../node')(gulp, plugins, options);
  require('../babel')(gulp, plugins, options);
  require('../typescript')(gulp, plugins, options);
  require('../sass')(gulp, plugins, options);
  require('../mocha')(gulp, plugins, options);
  require('../copy-assets')(gulp, plugins, options);
  require('../clean')(gulp, plugins, options);

  runSequence('clean:all', () => {
    gulp.start(utils.isTypescriptProject() ? 'typescript' : 'babel');

    gulp.start('update-node-version');
    gulp.start('sass');
    gulp.start('copy-assets');

    if (!options.server) {
      gulp.start('mocha');
    }
  });

  const app = express()
    .use(getCorsMiddleware());

  if (bundler) {
    app.use(getWebpackDevMiddleware(bundler));
    if (options.hot) {
      app.use(require('webpack-hot-middleware')(bundler));
    }
  }

  app.use(express.static(clientFilesPath))
    .listen(port, 'localhost');
};

function getCorsMiddleware() {
  return (req, res, next) => {
    res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.setHeader('Access-Control-Allow-Origin', '*');

    next();
  };
}

function getWebpackDevMiddleware(bundler) {
  try {
    return webpackMiddleware(bundler, {
      noInfo: true,
      stats: {
        colors: true
      }
    });
  } catch (e) {
    return (req, res, next) => next();
  }
}

function writeToServerLog(data) {
  fs.appendFile('target/server.log', data);
}
<commit_msg>start refactor<commit_after>'use strict';

const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const gutil = require('gulp-util');
const {spawn} = require('child_process');
const runSequence = require('run-sequence');
const utils = require('../../utils');

function getCorsMiddleware() {
  return (req, res, next) => {
    res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.setHeader('Access-Control-Allow-Origin', '*');

    next();
  };
}

function getWebpackDevMiddleware(bundler) {
  const webpackMiddleware = require('webpack-dev-middleware');

  try {
    return webpackMiddleware(bundler, {
      noInfo: true,
      stats: {
        colors: true
      }
    });
  } catch (e) {
    return (req, res, next) => next();
  }
}

function startWebpack({hot}) {
  const express = require('express');
  const projectConfig = require('../../../config/project');
  const {compiler} = require('../webpack');

  const port = projectConfig.servers.cdn.port();
  const clientFilesPath = projectConfig.clientFilesPath();
  const bundler = compiler({debug: true, hot});
  const app = express().use(getCorsMiddleware());
  if (bundler) {
    app.use(getWebpackDevMiddleware(bundler));
    if (hot) {
      app.use(require('webpack-hot-middleware')(bundler));
    }
  }
  app.use(express.static(clientFilesPath)).listen(port, 'localhost');
}

module.exports = (gulp, plugins, options) => {
  let server;
  const runServer = () => {
    const env = Object.create(process.env);
    if (server) {
      server.kill('SIGTERM');
    } else {
      console.log('');
      gutil.log('Application is now available at ', gutil.colors.magenta(`http://localhost:3000${env.MOUNT_POINT || '/'}`));
      gutil.log('Server log is written to ', gutil.colors.magenta('./target/server.log'));
      gulp.start('mocha');
    }

    env.NODE_ENV = 'development';
    env.DEBUG = 'wix:*,wnp:*';

    server = spawn('node', [path.resolve(options.entryPoint)], {env});
    [server.stdout, server.stderr].forEach(stream =>
      stream.on('data', writeToServerLog)
    );

    const displayErrors = _.debounce(() => {
      gutil.log(
        gutil.colors.red('There are errors! Please check'),
        gutil.colors.magenta('./target/server.log')
      );
    }, 500);

    server.stderr.on('data', buffer => {
      if (buffer.toString().includes('wix:error')) {
        displayErrors();
      }
    });

    return server;
  };

  // TODO: change gulp tasks to simple async functions
  options = Object.assign(options, {
    done: options.server ? runServer : function () {},
    watch: true
  });

  require('../node')(gulp, plugins, options);
  require('../babel')(gulp, plugins, options);
  require('../typescript')(gulp, plugins, options);
  require('../sass')(gulp, plugins, options);
  require('../mocha')(gulp, plugins, options);
  require('../copy-assets')(gulp, plugins, options);
  require('../clean')(gulp, plugins, options);

  runSequence('clean:all', () => {
    gulp.start(utils.isTypescriptProject() ? 'typescript' : 'babel');

    gulp.start('update-node-version');
    gulp.start('sass');
    gulp.start('copy-assets');

    if (!options.server) {
      gulp.start('mocha');
    }
  });

  startWebpack(options);
};

function writeToServerLog(data) {
  fs.appendFile('target/server.log', data);
}
<|endoftext|>


<commit_before>import {getCacheKey} from '../../src';
import expect from 'unexpected';
import {connection} from '../helper';

describe('getCacheKey', function () {
  const User = connection.define('user')
    , Task = connection.define('task')
    , association = User.hasMany(Task);

  it('handles circular structures', function () {
    let foo = {}
      , bar = {}
      , options = {
        foo,
        bar
      };

    foo.bar = bar;
    bar.foo = foo;

    expect(getCacheKey({
      name: 'user'
    }, 'id', options), 'to equal',
      'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles nulls', function () {
    expect(getCacheKey(User, 'id', {
      order: null
    }), 'to equal', 'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:null|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('does not modify arrays', function () {
    let options = {
      order: ['foo', 'bar']
    };

    expect(getCacheKey(User, 'id', options), 'to equal',
      'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:foo,bar|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
    expect(options.order, 'to equal', ['foo', 'bar']);
  });

  it('handles associations', function () {
    expect(getCacheKey(User, 'id', {
      association,
      limit: 42
    }), 'to equal', 'user|id|association:HasMany,task,tasks|attributes:undefined|groupedLimit:undefined|limit:42|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles attributes', function () {
    expect(getCacheKey(User, 'id', {
      attributes: ['foo', 'bar', 'baz']
    }), 'to equal', 'user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles schemas', function () {
    expect(getCacheKey({
      name: 'user',
      options: {
        schema: 'app'
      }
    }, 'id', {
      attributes: ['foo', 'bar', 'baz']
    }), 'to equal', 'app|user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  describe('where statements', function () {
    it('POJO', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          completed: true
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:true');
    });

    it('symbols', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          [Symbol('or')]: {
            name: { [Symbol('iLike')]: '%test%' }
          },
          [Symbol('or')]: {
            name: { [Symbol('iLike')]: '%test%' }
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:Symbol(or):name:Symbol(iLike):%test%|Symbol(or):name:Symbol(iLike):%test%');
    });

    it('date', function () {
      const from = new Date(Date.UTC(2016, 1, 1));
      const to = new Date(Date.UTC(2016, 2, 1));

      expect(getCacheKey(User, 'id', {
        where: {
          completed: {
            $between: [
              from,
              to
            ]
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:$between:2016-02-01T00:00:00.000Z,2016-03-01T00:00:00.000Z');
    });

    it('literal', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          foo: connection.literal('SELECT foo FROM bar')
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:val:SELECT foo FROM bar');
    });

    it('fn + col', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          foo: {
            $gt: connection.fn('FOO', connection.col('bar'))
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:$gt:args:col:bar|fn:FOO');
    });
  });

  it('searchPath', function () {
    expect(getCacheKey(User, 'id', {
      searchPath: 'test'
    }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:test|through:undefined|where:undefined');
  });

});
<commit_msg>Add tests for paranoid cache key (#62)<commit_after>import {getCacheKey} from '../../src';
import expect from 'unexpected';
import {connection} from '../helper';

describe('getCacheKey', function () {
  const User = connection.define('user')
    , Task = connection.define('task')
    , association = User.hasMany(Task);

  it('handles circular structures', function () {
    let foo = {}
      , bar = {}
      , options = {
        foo,
        bar
      };

    foo.bar = bar;
    bar.foo = foo;

    expect(getCacheKey({
      name: 'user'
    }, 'id', options), 'to equal',
      'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles nulls', function () {
    expect(getCacheKey(User, 'id', {
      order: null
    }), 'to equal', 'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:null|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('does not modify arrays', function () {
    let options = {
      order: ['foo', 'bar']
    };

    expect(getCacheKey(User, 'id', options), 'to equal',
      'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:foo,bar|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
    expect(options.order, 'to equal', ['foo', 'bar']);
  });

  it('handles associations', function () {
    expect(getCacheKey(User, 'id', {
      association,
      limit: 42
    }), 'to equal', 'user|id|association:HasMany,task,tasks|attributes:undefined|groupedLimit:undefined|limit:42|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles attributes', function () {
    expect(getCacheKey(User, 'id', {
      attributes: ['foo', 'bar', 'baz']
    }), 'to equal', 'user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  it('handles schemas', function () {
    expect(getCacheKey({
      name: 'user',
      options: {
        schema: 'app'
      }
    }, 'id', {
      attributes: ['foo', 'bar', 'baz']
    }), 'to equal', 'app|user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
  });

  describe('where statements', function () {
    it('POJO', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          completed: true
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:true');
    });

    it('symbols', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          [Symbol('or')]: {
            name: { [Symbol('iLike')]: '%test%' }
          },
          [Symbol('or')]: {
            name: { [Symbol('iLike')]: '%test%' }
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:Symbol(or):name:Symbol(iLike):%test%|Symbol(or):name:Symbol(iLike):%test%');
    });

    it('date', function () {
      const from = new Date(Date.UTC(2016, 1, 1));
      const to = new Date(Date.UTC(2016, 2, 1));

      expect(getCacheKey(User, 'id', {
        where: {
          completed: {
            $between: [
              from,
              to
            ]
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:$between:2016-02-01T00:00:00.000Z,2016-03-01T00:00:00.000Z');
    });

    it('literal', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          foo: connection.literal('SELECT foo FROM bar')
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:val:SELECT foo FROM bar');
    });

    it('fn + col', function () {
      expect(getCacheKey(User, 'id', {
        where: {
          foo: {
            $gt: connection.fn('FOO', connection.col('bar'))
          }
        }
      }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:$gt:args:col:bar|fn:FOO');
    });
  });

  it('searchPath', function () {
    expect(getCacheKey(User, 'id', {
      searchPath: 'test'
    }), 'to equal',
        'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|paranoid:undefined|raw:undefined|searchPath:test|through:undefined|where:undefined');
  });

});
<|endoftext|>


<commit_before>"use strict"
const Candidate = require('../models/candidate')
const CandidateMetadata = require('../models/candidate_metadata')

const CANDIDATE_ID = 'Candidate_ID'

function getCandidatesForContests(contestIds) {
  return Candidate
    .query(function(qb) {
      qb.whereIn('Contest_ID', contestIds)
    })
    .fetchAll()
    .then(results => {
      let candidates = results.map(candidateModel => {
        return candidateModel.attributes
      })
      return candidates
    })
}

function getCandidate(candidateId) {
  return Candidate
    .where(CANDIDATE_ID, candidateId)
    .fetch()
    .then(candidate => {
      return candidate.attributes
    })
}

function getCandidateMetadata(candidateId) {
  return getCandidatesMetadata([candidateId]).then(candidatesMetadata => {
    if (candidatesMetadata && candidatesMetadata.length > 0) {
      return candidatesMetadata[0]
    }
    else {
      return {}
    }
  })
}

function getCandidatesMetadata(candidateIds) {
  return CandidateMetadata
    .query(function(qb) {
      qb.whereIn(CANDIDATE_ID, candidateIds)
    })
    .fetchAll()
    .then(results => {
      let candidatesMetadata = results.map(candidateMetadataModel => {
        return candidateMetadataModel.attributes
      })
      return candidatesMetadata
    })
}

function getFullCandidatePromise(candidateId) {
  const candidatePr = getCandidate(candidateId)
  const candidateMetadataPr = getCandidateMetadata(candidateId)
  return Promise.all([candidatePr, candidateMetadataPr])
    .then(results => {
      let fullCandidate = results[0] || {}
      fullCandidate.metadata = results[1] || {}
      return fullCandidate
    })
}

function setCandidateMetadata(candidateId, metadata) {
  return CandidateMetadata
    .forge({ [CANDIDATE_ID]: candidateId })
    .fetch()
    .then(foundMetadata => {
      let method = 'update'
      if (foundMetadata === null) {
        method = 'insert'
      }

      console.log('method ', method)

      return CandidateMetadata
        .forge({ [CANDIDATE_ID]: candidateId})
        .save(metadata, {method: method})
        .then(savedModel => {
          console.log('Saved metadata', savedModel)
          return savedModel
        })
    })
}

module.exports = {
  getCandidatesMetadata,
  getCandidatesForContests,
  getFullCandidatePromise,
  setCandidateMetadata,
}
<commit_msg>Sorted candidates by id<commit_after>"use strict"
const Candidate = require('../models/candidate')
const CandidateMetadata = require('../models/candidate_metadata')

const CANDIDATE_ID = 'Candidate_ID'

function getCandidatesForContests(contestIds) {
  return Candidate
    .query(function(qb) {
      qb.whereIn('Contest_ID', contestIds)
    })
    .orderBy(CANDIDATE_ID, 'ASC')
    .fetchAll()
    .then(results => {
      let candidates = results.map(candidateModel => {
        return candidateModel.attributes
      })
      return candidates
    })
}

function getCandidate(candidateId) {
  return Candidate
    .where(CANDIDATE_ID, candidateId)
    .fetch()
    .then(candidate => {
      return candidate.attributes
    })
}

function getCandidateMetadata(candidateId) {
  return getCandidatesMetadata([candidateId]).then(candidatesMetadata => {
    if (candidatesMetadata && candidatesMetadata.length > 0) {
      return candidatesMetadata[0]
    }
    else {
      return {}
    }
  })
}

function getCandidatesMetadata(candidateIds) {
  return CandidateMetadata
    .query(function(qb) {
      qb.whereIn(CANDIDATE_ID, candidateIds)
    })
    .orderBy(CANDIDATE_ID, 'ASC')
    .fetchAll()
    .then(results => {
      let candidatesMetadata = results.map(candidateMetadataModel => {
        return candidateMetadataModel.attributes
      })
      return candidatesMetadata
    })
}

function getFullCandidatePromise(candidateId) {
  const candidatePr = getCandidate(candidateId)
  const candidateMetadataPr = getCandidateMetadata(candidateId)
  return Promise.all([candidatePr, candidateMetadataPr])
    .then(results => {
      let fullCandidate = results[0] || {}
      fullCandidate.metadata = results[1] || {}
      return fullCandidate
    })
}

function setCandidateMetadata(candidateId, metadata) {
  return CandidateMetadata
    .forge({ [CANDIDATE_ID]: candidateId })
    .fetch()
    .then(foundMetadata => {
      let method = 'update'
      if (foundMetadata === null) {
        method = 'insert'
      }

      console.log('method ', method)

      return CandidateMetadata
        .forge({ [CANDIDATE_ID]: candidateId})
        .save(metadata, {method: method})
        .then(savedModel => {
          console.log('Saved metadata', savedModel)
          return savedModel
        })
    })
}

module.exports = {
  getCandidatesMetadata,
  getCandidatesForContests,
  getFullCandidatePromise,
  setCandidateMetadata,
}
<|endoftext|>


<commit_before>var system = require('system');
var args = system.args;

var page = require('webpage').create();

page.open(args[1] + args[2] + '#fight=' + args[3] + '&type=damage-done', function(status) {

		page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', function() {
			setTimeout(function () {
				console.log("Start_Response")
				console.log(page.evaluate(eva));
				console.log("End_Response");
				phantom.exit();
			}, 10000);
		});

});

var eva = function() {

	var msg = "";
	// eX̒l擾
	for (var i = 0, size = $(".table-icon").length; i < size; i++) {
		if($(".main-table-performance")[i]) {
			msg += $(".main-table-performance")[i].innerText.replace(/\t|(\r?\n)/g,"");
			msg += "% ";
		}

		if($(".main-table-name")[i]) {
			msg += $(".main-table-name")[i].innerText.replace(/\t|(\r?\n)/g,"");
		}
		if($(".table-icon")[i]) {
			msg += " (";
			msg += $(".table-icon")[i].src.match(/\/(\w+).png/)[1];
			msg += ") ";
		}

		if($(".main-table-number")[i]) {
			msg += $(".main-table-number")[i].innerText.replace(/\t|(\r?\n)/g,"");
		}

		msg += "\n";
	}

	// total̒l擾
	{
		if($(".main-table-performance")[$(".main-table-performance").length-1]) {
			msg += $(".main-table-performance")[$(".main-table-performance").length-1].innerText.replace(/\t|(\r?\n)/g,"");
			msg += "% "
		}

		msg += "Total ";

		if($(".main-table-number")[$(".main-table-number").length-1]) {
			msg += $(".main-table-number")[$(".main-table-number").length-1].innerText;
		}

		msg += "\n";
	}

	return msg;
}<commit_msg>Change: コメントをSJISからUTF-8に変更<commit_after>var system = require('system');
var args = system.args;

var page = require('webpage').create();

page.open(args[1] + args[2] + '#fight=' + args[3] + '&type=damage-done', function(status) {

		page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', function() {
			setTimeout(function () {
				console.log("Start_Response")
				console.log(page.evaluate(eva));
				console.log("End_Response");
				phantom.exit();
			}, 10000);
		});

});

var eva = function() {

	var msg = "";
	// 各々の値を取得
	for (var i = 0, size = $(".table-icon").length; i < size; i++) {
		if($(".main-table-performance")[i]) {
			msg += $(".main-table-performance")[i].innerText.replace(/\t|(\r?\n)/g,"");
			msg += "% ";
		}

		if($(".main-table-name")[i]) {
			msg += $(".main-table-name")[i].innerText.replace(/\t|(\r?\n)/g,"");
		}
		if($(".table-icon")[i]) {
			msg += " (";
			msg += $(".table-icon")[i].src.match(/\/(\w+).png/)[1];
			msg += ") ";
		}

		if($(".main-table-number")[i]) {
			msg += $(".main-table-number")[i].innerText.replace(/\t|(\r?\n)/g,"");
		}

		msg += "\n";
	}

	// totalの値を取得
	{
		if($(".main-table-performance")[$(".main-table-performance").length-1]) {
			msg += $(".main-table-performance")[$(".main-table-performance").length-1].innerText.replace(/\t|(\r?\n)/g,"");
			msg += "% "
		}

		msg += "Total ";

		if($(".main-table-number")[$(".main-table-number").length-1]) {
			msg += $(".main-table-number")[$(".main-table-number").length-1].innerText;
		}

		msg += "\n";
	}

	return msg;
}<|endoftext|>


<commit_before>describe('Overlay Header Height [00j]', function () {

  beforeEach(function () {
    cy.configureCluster({
      mesos: '1-task-healthy'
    })
    .visitUrl({url: '/', identify: true, fakeAnalytics: true});
  });

  context('Headers [00n]', function () {

    beforeEach(function () {
      cy.get('.sidebar-menu-item').contains('Services').click();
      cy.get('table tbody tr').as('tableRows');
    });

    it('should render all overlay headers at the same height [00p]',
      function () {
        var sidePanelHeaderHeight = null;
        var overlayHeaderHeight = null;

        // Open the Marathon task.
        cy.get('@tableRows').contains('marathon').click();
        // Get the task panel's header.
        cy.get('.side-panel-header-container').as('sidePanelHeader');

        cy.get('@sidePanelHeader').should(function ($sidePanelHeader) {
          sidePanelHeaderHeight = $sidePanelHeader.outerHeight();
        });

        // Open the Marathon UI.
        cy.get('.side-panel-content-header-actions')
          .contains('Open Service')
          .click();

        // Get the service overlay's header.
        cy.get('.overlay-header-container').as('overlayHeader');

        cy.get('@overlayHeader').should(function ($overlayHeader) {
          overlayHeaderHeight = $overlayHeader.outerHeight();
          expect(sidePanelHeaderHeight).to.eq(overlayHeaderHeight);
        });
      });
  });
});
<commit_msg>Remove unneeded test.<commit_after><|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import { exec, spawn } from 'child_process';
import tmp from 'tmp';
import walkSync from 'walk-sync';
import mkdirp from 'mkdirp';
import findup from 'findup-sync';
import dedent from 'dedent-js';
import eachDir from '../utils/each-dir';
import createDebug from 'debug';

const debug = createDebug('denali:test:command-acceptance');

export default class CommandAcceptanceTest {

  constructor(command, options = {}) {
    this.command = command;
    this.dir = options.dir || tmp.dirSync({ unsafeCleanup: true }).name;
    this.environment = options.environment || 'development';
    // This will likely break once avajs/ava#1074 lands in a release. Right now,
    // because ava sets process.cwd() to the test file's location, the
    // `findup()` starts searching inside a app/addons's compiled `dist/test/`
    // folder, since that's the file that's executing. That means that the
    // projectRoot will be `dist/`, so we add another dirname().
    //
    // Once that PR is released, process.cwd() will the actual project root. So
    // we will need to remove one of the double dirname()s.
    this.projectRoot = path.dirname(path.dirname(findup('package.json')));
    let projectName = require(path.join(this.projectRoot, 'package.json')).name;
    this.denaliPath = path.join(this.projectRoot, 'node_modules', '.bin', 'denali');

    // This is a special case for when we are running Denali's own test suite.
    // In _every_ other scenario (app or addon running tests), Denali would be
    // a dependency, and therefore node_modules/.bin/denali should exist. But
    // when running Denali's own test suite, that won't exist, since Denali
    // isn't a dependency of itself. So we special case this to find the actual
    // executable instead.
    if (!fs.existsSync(this.denaliPath)) {
      this.denaliPath = path.join(this.projectRoot, 'dist-test', 'node_modules', 'denali', 'bin', 'denali');
    }

    if (options.populateWithDummy !== false) {
      debug(`populating tmp directory for "${ command }" command with dummy app`);
      if (fs.existsSync(path.join(this.dir, 'node_modules'))) {
        // If node_modules already exists, the user must have passed in a tmp
        // directory of their own that they previous messed with.
        throw new Error('You tried to run a CommandAcceptanceTest against a directory that already has an app in it. Did you forget to specify { populateWithDummy: false }?');
      }
      // Create a tmp copy of our dummy app to test our blueprint against
      let dummyDir = path.join(this.projectRoot, 'test', 'dummy');
      walkSync(dummyDir).forEach((dummyFile) => {
        if (dummyFile.charAt(dummyFile.length - 1) === '/') {
          mkdirp.sync(path.join(this.dir, dummyFile));
        } else {
          fs.writeFileSync(path.join(this.dir, dummyFile), fs.readFileSync(path.join(dummyDir, dummyFile)));
        }
      });
      // Symlink dependencies for dummy app to the addon's dependencies
      mkdirp.sync(path.join(this.dir, 'node_modules'));
      eachDir(path.join(this.projectRoot, 'node_modules'), (dep) => {
        fs.symlinkSync(path.join(this.projectRoot, 'node_modules', dep), path.join(this.dir, 'node_modules', dep));
      });
      // Symlink the addon under test as a dependency of this dummy app
      fs.symlinkSync(path.join(this.projectRoot, 'dist'), path.join(this.dir, 'node_modules', projectName));
      debug('tmp directory populated');
    }
  }

  run(options = {}) {
    return new Promise((resolve, reject) => {
      exec(`${ this.denaliPath } ${ this.command }`, {
        env: Object.assign({}, process.env, {
          DENALI_ENV: this.environment,
          NODE_ENV: this.environment
        }, options.env || {}),
        cwd: this.dir
      }, (err, stdout, stderr) => {
        if (err || (options.failOnStderr && stderr.length > 0)) {
          err = err || new Error();
          err.message += dedent`
            ====> stdout:
            ${ stdout }
            ====> stderr:
            ${ stderr }
          `;
          return reject(err);
        }
        resolve({ stdout, stderr, dir: this.dir });
      });
    });
  }

  spawn(options = {}) {
    return new Promise((resolve, reject) => {

      this.spawnedCommand = spawn(this.denaliPath, this.command.split(' '), {
        env: Object.assign({}, process.env, {
          DENALI_ENV: this.environment,
          NODE_ENV: this.environment
        }, options.env || {}),
        cwd: this.dir,
        stdio: 'pipe'
      });

      // Cleanup spawned processes if our process is killed
      let cleanup = this.cleanup.bind(this);
      process.on('exit', cleanup.bind(this));

      // Buffer up the output so the polling timer can check it
      let stdoutBuffer = '';
      let stderrBuffer = '';
      this.spawnedCommand.stdout.on('data', (d) => {
        stdoutBuffer += d.toString();
      });
      this.spawnedCommand.stderr.on('data', (d) => {
        stderrBuffer += d.toString();
      });

      // Handle errors from the child process
      this.spawnedCommand.stdout.on('error', reject);
      this.spawnedCommand.stderr.on('error', reject);
      this.spawnedCommand.on('error', reject);

      // Poll periodically to check the results
      this.pollOutput = setInterval(() => {
        if (stderrBuffer.length > 0 && options.failOnStderr) {
          process.removeListener('exit', cleanup);
          this.cleanup();
          let error = new Error('Command printed to stderr, and failOnStderr enabled:\n');
          error.message += dedent`
            ====> stdout:
            ${ stdoutBuffer }
            ====> stderr:
            ${ stderrBuffer }
          `;
          reject(error);
        }
        let passed = options.checkOutput(stdoutBuffer, stderrBuffer, this.dir);
        if (passed) {
          process.removeListener('exit', cleanup);
          this.cleanup();
          resolve();
        }
      }, options.pollInterval || 50);

      // Ensure the test fails if we don't pass the test after a while
      let timeout = options.timeout || (process.env.CI ? 10 * 60 * 1000 : 3 * 60 * 1000);
      this.fallbackTimeout = setTimeout(() => {
        process.removeListener('exit', cleanup);
        this.cleanup();
        let message = `Timeout of ${ (timeout / 1000) / 60 } minutes exceeded for spawned command: ${ this.command }\n`;
        message += dedent`
          ====> stdout:
          ${ stdoutBuffer }
          ====> stderr:
          ${ stderrBuffer }
        `;
        reject(new Error(message));
      }, timeout);

    });
  }

  cleanup() {
    this.spawnedCommand.kill();
    clearInterval(this.pollOutput);
    clearTimeout(this.fallbackTimeout);
  }

}
<commit_msg>fix(test): ensure addon dependency can link properly, even when cyclical<commit_after>import fs from 'fs';
import path from 'path';
import { exec, spawn } from 'child_process';
import tmp from 'tmp';
import walkSync from 'walk-sync';
import mkdirp from 'mkdirp';
import findup from 'findup-sync';
import dedent from 'dedent-js';
import eachDir from '../utils/each-dir';
import createDebug from 'debug';

const debug = createDebug('denali:test:command-acceptance');

export default class CommandAcceptanceTest {

  constructor(command, options = {}) {
    this.command = command;
    this.dir = options.dir || tmp.dirSync({ unsafeCleanup: true }).name;
    this.environment = options.environment || 'development';
    // This will likely break once avajs/ava#1074 lands in a release. Right now,
    // because ava sets process.cwd() to the test file's location, the
    // `findup()` starts searching inside a app/addons's compiled `dist/test/`
    // folder, since that's the file that's executing. That means that the
    // projectRoot will be `dist/`, so we add another dirname().
    //
    // Once that PR is released, process.cwd() will the actual project root. So
    // we will need to remove one of the double dirname()s.
    this.projectRoot = path.dirname(path.dirname(findup('package.json')));
    let projectName = require(path.join(this.projectRoot, 'package.json')).name;
    this.denaliPath = path.join(this.projectRoot, 'node_modules', '.bin', 'denali');

    // This is a special case for when we are running Denali's own test suite.
    // In _every_ other scenario (app or addon running tests), Denali would be
    // a dependency, and therefore node_modules/.bin/denali should exist. But
    // when running Denali's own test suite, that won't exist, since Denali
    // isn't a dependency of itself. So we special case this to find the actual
    // executable instead.
    if (!fs.existsSync(this.denaliPath)) {
      this.denaliPath = path.join(this.projectRoot, 'dist-test', 'node_modules', 'denali', 'bin', 'denali');
    }

    if (options.populateWithDummy !== false) {
      debug(`populating tmp directory for "${ command }" command with dummy app`);
      if (fs.existsSync(path.join(this.dir, 'node_modules'))) {
        // If node_modules already exists, the user must have passed in a tmp
        // directory of their own that they previous messed with.
        throw new Error('You tried to run a CommandAcceptanceTest against a directory that already has an app in it. Did you forget to specify { populateWithDummy: false }?');
      }
      // Create a tmp copy of our dummy app to test our blueprint against
      let dummyDir = path.join(this.projectRoot, 'test', 'dummy');
      walkSync(dummyDir).forEach((dummyFile) => {
        if (dummyFile.charAt(dummyFile.length - 1) === '/') {
          mkdirp.sync(path.join(this.dir, dummyFile));
        } else {
          fs.writeFileSync(path.join(this.dir, dummyFile), fs.readFileSync(path.join(dummyDir, dummyFile)));
        }
      });
      // Symlink dependencies for dummy app to the addon's dependencies
      mkdirp.sync(path.join(this.dir, 'node_modules'));
      eachDir(path.join(this.projectRoot, 'node_modules'), (dep) => {
        fs.symlinkSync(path.join(this.projectRoot, 'node_modules', dep), path.join(this.dir, 'node_modules', dep));
      });
      // Symlink the addon under test as a dependency of this dummy app
      fs.unlinkSync(path.join(this.dir, 'node_modules', projectName));
      fs.symlinkSync(path.join(this.projectRoot, 'dist'), path.join(this.dir, 'node_modules', projectName));
      debug('tmp directory populated');
    }
  }

  run(options = {}) {
    return new Promise((resolve, reject) => {
      exec(`${ this.denaliPath } ${ this.command }`, {
        env: Object.assign({}, process.env, {
          DENALI_ENV: this.environment,
          NODE_ENV: this.environment
        }, options.env || {}),
        cwd: this.dir
      }, (err, stdout, stderr) => {
        if (err || (options.failOnStderr && stderr.length > 0)) {
          err = err || new Error();
          err.message += dedent`
            ====> stdout:
            ${ stdout }
            ====> stderr:
            ${ stderr }
          `;
          return reject(err);
        }
        resolve({ stdout, stderr, dir: this.dir });
      });
    });
  }

  spawn(options = {}) {
    return new Promise((resolve, reject) => {

      this.spawnedCommand = spawn(this.denaliPath, this.command.split(' '), {
        env: Object.assign({}, process.env, {
          DENALI_ENV: this.environment,
          NODE_ENV: this.environment
        }, options.env || {}),
        cwd: this.dir,
        stdio: 'pipe'
      });

      // Cleanup spawned processes if our process is killed
      let cleanup = this.cleanup.bind(this);
      process.on('exit', cleanup.bind(this));

      // Buffer up the output so the polling timer can check it
      let stdoutBuffer = '';
      let stderrBuffer = '';
      this.spawnedCommand.stdout.on('data', (d) => {
        stdoutBuffer += d.toString();
      });
      this.spawnedCommand.stderr.on('data', (d) => {
        stderrBuffer += d.toString();
      });

      // Handle errors from the child process
      this.spawnedCommand.stdout.on('error', reject);
      this.spawnedCommand.stderr.on('error', reject);
      this.spawnedCommand.on('error', reject);

      // Poll periodically to check the results
      this.pollOutput = setInterval(() => {
        if (stderrBuffer.length > 0 && options.failOnStderr) {
          process.removeListener('exit', cleanup);
          this.cleanup();
          let error = new Error('Command printed to stderr, and failOnStderr enabled:\n');
          error.message += dedent`
            ====> stdout:
            ${ stdoutBuffer }
            ====> stderr:
            ${ stderrBuffer }
          `;
          reject(error);
        }
        let passed = options.checkOutput(stdoutBuffer, stderrBuffer, this.dir);
        if (passed) {
          process.removeListener('exit', cleanup);
          this.cleanup();
          resolve();
        }
      }, options.pollInterval || 50);

      // Ensure the test fails if we don't pass the test after a while
      let timeout = options.timeout || (process.env.CI ? 10 * 60 * 1000 : 3 * 60 * 1000);
      this.fallbackTimeout = setTimeout(() => {
        process.removeListener('exit', cleanup);
        this.cleanup();
        let message = `Timeout of ${ (timeout / 1000) / 60 } minutes exceeded for spawned command: ${ this.command }\n`;
        message += dedent`
          ====> stdout:
          ${ stdoutBuffer }
          ====> stderr:
          ${ stderrBuffer }
        `;
        reject(new Error(message));
      }, timeout);

    });
  }

  cleanup() {
    this.spawnedCommand.kill();
    clearInterval(this.pollOutput);
    clearTimeout(this.fallbackTimeout);
  }

}
<|endoftext|>


<commit_before>
export const fields = [
  { code: '%H',
    name: 'commit hash',
    fullDescription: 'commit hash',
    description: '',
    identifier: 'commit_hash' },
  { code: '%h',
    name: 'abbreviated commit hash',
    fullDescription: 'abbreviated commit hash',
    description: '',
    identifier: 'abbreviated_commit_hash' },
  { code: '%T',
    name: 'tree hash',
    fullDescription: 'tree hash',
    description: '',
    identifier: 'tree_hash' },
  { code: '%t',
    name: 'abbreviated tree hash',
    fullDescription: 'abbreviated tree hash',
    description: '',
    identifier: 'abbreviated_tree_hash' },
  { code: '%P',
    name: 'parent hashes',
    fullDescription: 'parent hashes',
    description: '',
    identifier: 'parent_hashes' },
  { code: '%p',
    name: 'abbreviated parent hashes',
    fullDescription: 'abbreviated parent hashes',
    description: '',
    identifier: 'abbreviated_parent_hashes' },
  { code: '%an',
    name: 'author name',
    fullDescription: 'author name',
    description: '',
    identifier: 'author_name' },
  { code: '%aN',
    name: 'author name',
    fullDescription: 'author name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'author_name_mailmap' },
  { code: '%ae',
    name: 'author email',
    fullDescription: 'author email',
    description: '',
    identifier: 'author_email' },
  { code: '%aE',
    name: 'author email',
    fullDescription: 'author email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'author_email_mailmap' },
  // { code: '%ad',
  //   name: 'author date',
  //   fullDescription: 'author date (format respects --date= option)',
  //   description: ' (format respects --date= option)',
  //   identifier: 'author_date_(format_respects_--date=_option)' },
  // { code: '%aD',
  //   name: 'author date',
  //   fullDescription: 'author date, RFC2822 style',
  //   description: ', RFC2822 style',
  //   identifier: 'author_date_RFC2822_style' },
  { code: '%ar',
    name: 'author date',
    fullDescription: 'author date, relative',
    description: ', relative',
    identifier: 'author_date_relative' },
  // { code: '%at',
  //   name: 'author date',
  //   fullDescription: 'author date, UNIX timestamp',
  //   description: ', UNIX timestamp',
  //   identifier: 'author_date_UNIX_timestamp' },
  // { code: '%ai',
  //   name: 'author date',
  //   fullDescription: 'author date, ISO 8601-like format',
  //   description: ', ISO 8601-like format',
  //   identifier: 'author_date_ISO_8601-like_format' },
  { code: '%aI',
    name: 'author date',
    fullDescription: 'author date, strict ISO 8601 format',
    description: ', strict ISO 8601 format',
    identifier: 'author_date' },
  { code: '%cn',
    name: 'committer name',
    fullDescription: 'committer name',
    description: '',
    identifier: 'committer_name' },
  { code: '%cN',
    name: 'committer name',
    fullDescription: 'committer name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'committer_name_mailmap' },
  { code: '%ce',
    name: 'committer email',
    fullDescription: 'committer email',
    description: '',
    identifier: 'committer_email' },
  { code: '%cE',
    name: 'committer email',
    fullDescription: 'committer email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'committer_email_mailmap' },
  // { code: '%cd',
  //   name: 'committer date',
  //   fullDescription: 'committer date (format respects --date= option)',
  //   description: ' (format respects --date= option)',
  //   identifier: 'committer_date_(format_respects_--date=_option)' },
  // { code: '%cD',
  //   name: 'committer date',
  //   fullDescription: 'committer date, RFC2822 style',
  //   description: ', RFC2822 style',
  //   identifier: 'committer_date_RFC2822_style' },
  { code: '%cr',
    name: 'committer date',
    fullDescription: 'committer date, relative',
    description: ', relative',
    identifier: 'committer_date_relative' },
  // { code: '%ct',
  //   name: 'committer date',
  //   fullDescription: 'committer date, UNIX timestamp',
  //   description: ', UNIX timestamp',
  //   identifier: 'committer_date_UNIX_timestamp' },
  // { code: '%ci',
  //   name: 'committer date',
  //   fullDescription: 'committer date, ISO 8601-like format',
  //   description: ', ISO 8601-like format',
  //   identifier: 'committer_date_ISO_8601-like_format' },
  { code: '%cI',
    name: 'committer date',
    fullDescription: 'committer date, strict ISO 8601 format',
    description: ', strict ISO 8601 format',
    identifier: 'committer_date' },
  // { code: '%d',
  //   name: 'ref names',
  //   fullDescription: 'ref names, like the --decorate option of git-log[1]',
  //   description: ', like the --decorate option of git-log[1]',
  //   identifier: 'ref_names' },
  { code: '%D',
    name: 'ref names without the "',
    fullDescription: 'ref names without the " (", ")" wrapping.',
    description: ' (", ")" wrapping.',
    identifier: 'ref_names' },
  { code: '%e',
    name: 'encoding',
    fullDescription: 'encoding',
    description: '',
    identifier: 'encoding' },
  { code: '%s',
    name: 'subject',
    fullDescription: 'subject',
    description: '',
    identifier: 'subject' },
  { code: '%f',
    name: 'sanitized subject line',
    fullDescription: 'sanitized subject line, suitable for a filename',
    description: ', suitable for a filename',
    identifier: 'sanitized_subject' },
  { code: '%b',
    name: 'body',
    fullDescription: 'body',
    description: '',
    identifier: 'body' },
  { code: '%B',
    name: 'raw body',
    fullDescription: 'raw body (unwrapped subject and body)',
    description: ' (unwrapped subject and body)',
    identifier: 'raw_body' },
  { code: '%N',
    name: 'commit notes',
    fullDescription: 'commit notes',
    description: '',
    identifier: 'commit_notes' },
  { code: '%GG',
    name: 'raw verification message from GPG for a signed commit',
    fullDescription: 'raw verification message from GPG for a signed commit',
    description: '',
    identifier: 'raw_GPG_verification_message' },
  { code: '%G?',
    name: 'show "G" for a good',
    fullDescription: 'show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity, "X" for a good signature that has expired, "Y" for a good signature made by an expired key, "R" for a good signature made by a revoked key, "E" if the signature cannot be checked (e.g. missing key) and "N" for no signature',
    description: ' (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity, "X" for a good signature that has expired, "Y" for a good signature made by an expired key, "R" for a good signature made by a revoked key, "E" if the signature cannot be checked (e.g. missing key) and "N" for no signature',
    identifier: 'signature_validity' },
  { code: '%GS',
    name: 'show the name of the signer for a signed commit',
    fullDescription: 'show the name of the signer for a signed commit',
    description: '',
    identifier: 'signer_name' },
  { code: '%GK',
    name: 'show the key used to sign a signed commit',
    fullDescription: 'show the key used to sign a signed commit',
    description: '',
    identifier: 'key' },
  { code: '%gD',
    name: 'reflog selector',
    fullDescription: 'reflog selector, e.g., refs/stash@{1} or refs/stash@{2 minutes ago}; the format follows the rules described for the -g option. The portion before the @ is the refname as given on the command line (so git log -g refs/heads/master would yield refs/heads/master@{0}).',
    description: ', e.g., refs/stash@{1} or refs/stash@{2 minutes ago}; the format follows the rules described for the -g option. The portion before the @ is the refname as given on the command line (so git log -g refs/heads/master would yield refs/heads/master@{0}).',
    identifier: 'reflog_selector' },
  { code: '%gd',
    name: 'shortened reflog selector',
    fullDescription: 'shortened reflog selector; same as %gD, but the refname portion is shortened for human readability (so refs/heads/master becomes just master).',
    description: '; same as %gD, but the refname portion is shortened for human readability (so refs/heads/master becomes just master).',
    identifier: 'shortened_reflog_selector' },
  { code: '%gn',
    name: 'reflog identity name',
    fullDescription: 'reflog identity name',
    description: '',
    identifier: 'reflog_identity_name' },
  { code: '%gN',
    name: 'reflog identity name',
    fullDescription: 'reflog identity name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'reflog_identity_name_mailmap' },
  { code: '%ge',
    name: 'reflog identity email',
    fullDescription: 'reflog identity email',
    description: '',
    identifier: 'reflog_identity_email' },
  { code: '%gE',
    name: 'reflog identity email',
    fullDescription: 'reflog identity email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'reflog_identity_email_mailmap' },
  { code: '%gs',
    name: 'reflog subject',
    fullDescription: 'reflog subject',
    description: '',
    identifier: 'reflog_subject' } ];

const formatString = exports.formatString = fields.map(field =>
  `${ field.code }%x00`
).join('');
<commit_msg>Disables reflog-related fields<commit_after>
export const fields = [
  { code: '%H',
    name: 'commit hash',
    fullDescription: 'commit hash',
    description: '',
    identifier: 'commit_hash' },
  { code: '%h',
    name: 'abbreviated commit hash',
    fullDescription: 'abbreviated commit hash',
    description: '',
    identifier: 'abbreviated_commit_hash' },
  { code: '%T',
    name: 'tree hash',
    fullDescription: 'tree hash',
    description: '',
    identifier: 'tree_hash' },
  { code: '%t',
    name: 'abbreviated tree hash',
    fullDescription: 'abbreviated tree hash',
    description: '',
    identifier: 'abbreviated_tree_hash' },
  { code: '%P',
    name: 'parent hashes',
    fullDescription: 'parent hashes',
    description: '',
    identifier: 'parent_hashes' },
  { code: '%p',
    name: 'abbreviated parent hashes',
    fullDescription: 'abbreviated parent hashes',
    description: '',
    identifier: 'abbreviated_parent_hashes' },
  { code: '%an',
    name: 'author name',
    fullDescription: 'author name',
    description: '',
    identifier: 'author_name' },
  { code: '%aN',
    name: 'author name',
    fullDescription: 'author name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'author_name_mailmap' },
  { code: '%ae',
    name: 'author email',
    fullDescription: 'author email',
    description: '',
    identifier: 'author_email' },
  { code: '%aE',
    name: 'author email',
    fullDescription: 'author email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'author_email_mailmap' },
  // { code: '%ad',
  //   name: 'author date',
  //   fullDescription: 'author date (format respects --date= option)',
  //   description: ' (format respects --date= option)',
  //   identifier: 'author_date_(format_respects_--date=_option)' },
  // { code: '%aD',
  //   name: 'author date',
  //   fullDescription: 'author date, RFC2822 style',
  //   description: ', RFC2822 style',
  //   identifier: 'author_date_RFC2822_style' },
  { code: '%ar',
    name: 'author date',
    fullDescription: 'author date, relative',
    description: ', relative',
    identifier: 'author_date_relative' },
  // { code: '%at',
  //   name: 'author date',
  //   fullDescription: 'author date, UNIX timestamp',
  //   description: ', UNIX timestamp',
  //   identifier: 'author_date_UNIX_timestamp' },
  // { code: '%ai',
  //   name: 'author date',
  //   fullDescription: 'author date, ISO 8601-like format',
  //   description: ', ISO 8601-like format',
  //   identifier: 'author_date_ISO_8601-like_format' },
  { code: '%aI',
    name: 'author date',
    fullDescription: 'author date, strict ISO 8601 format',
    description: ', strict ISO 8601 format',
    identifier: 'author_date' },
  { code: '%cn',
    name: 'committer name',
    fullDescription: 'committer name',
    description: '',
    identifier: 'committer_name' },
  { code: '%cN',
    name: 'committer name',
    fullDescription: 'committer name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'committer_name_mailmap' },
  { code: '%ce',
    name: 'committer email',
    fullDescription: 'committer email',
    description: '',
    identifier: 'committer_email' },
  { code: '%cE',
    name: 'committer email',
    fullDescription: 'committer email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
    identifier: 'committer_email_mailmap' },
  // { code: '%cd',
  //   name: 'committer date',
  //   fullDescription: 'committer date (format respects --date= option)',
  //   description: ' (format respects --date= option)',
  //   identifier: 'committer_date_(format_respects_--date=_option)' },
  // { code: '%cD',
  //   name: 'committer date',
  //   fullDescription: 'committer date, RFC2822 style',
  //   description: ', RFC2822 style',
  //   identifier: 'committer_date_RFC2822_style' },
  { code: '%cr',
    name: 'committer date',
    fullDescription: 'committer date, relative',
    description: ', relative',
    identifier: 'committer_date_relative' },
  // { code: '%ct',
  //   name: 'committer date',
  //   fullDescription: 'committer date, UNIX timestamp',
  //   description: ', UNIX timestamp',
  //   identifier: 'committer_date_UNIX_timestamp' },
  // { code: '%ci',
  //   name: 'committer date',
  //   fullDescription: 'committer date, ISO 8601-like format',
  //   description: ', ISO 8601-like format',
  //   identifier: 'committer_date_ISO_8601-like_format' },
  { code: '%cI',
    name: 'committer date',
    fullDescription: 'committer date, strict ISO 8601 format',
    description: ', strict ISO 8601 format',
    identifier: 'committer_date' },
  // { code: '%d',
  //   name: 'ref names',
  //   fullDescription: 'ref names, like the --decorate option of git-log[1]',
  //   description: ', like the --decorate option of git-log[1]',
  //   identifier: 'ref_names' },
  { code: '%D',
    name: 'ref names without the "',
    fullDescription: 'ref names without the " (", ")" wrapping.',
    description: ' (", ")" wrapping.',
    identifier: 'ref_names' },
  { code: '%e',
    name: 'encoding',
    fullDescription: 'encoding',
    description: '',
    identifier: 'encoding' },
  { code: '%s',
    name: 'subject',
    fullDescription: 'subject',
    description: '',
    identifier: 'subject' },
  { code: '%f',
    name: 'sanitized subject line',
    fullDescription: 'sanitized subject line, suitable for a filename',
    description: ', suitable for a filename',
    identifier: 'sanitized_subject' },
  { code: '%b',
    name: 'body',
    fullDescription: 'body',
    description: '',
    identifier: 'body' },
  { code: '%B',
    name: 'raw body',
    fullDescription: 'raw body (unwrapped subject and body)',
    description: ' (unwrapped subject and body)',
    identifier: 'raw_body' },
  { code: '%N',
    name: 'commit notes',
    fullDescription: 'commit notes',
    description: '',
    identifier: 'commit_notes' },
  { code: '%GG',
    name: 'raw verification message from GPG for a signed commit',
    fullDescription: 'raw verification message from GPG for a signed commit',
    description: '',
    identifier: 'raw_GPG_verification_message' },
  { code: '%G?',
    name: 'show "G" for a good',
    fullDescription: 'show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity, "X" for a good signature that has expired, "Y" for a good signature made by an expired key, "R" for a good signature made by a revoked key, "E" if the signature cannot be checked (e.g. missing key) and "N" for no signature',
    description: ' (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity, "X" for a good signature that has expired, "Y" for a good signature made by an expired key, "R" for a good signature made by a revoked key, "E" if the signature cannot be checked (e.g. missing key) and "N" for no signature',
    identifier: 'signature_validity' },
  { code: '%GS',
    name: 'show the name of the signer for a signed commit',
    fullDescription: 'show the name of the signer for a signed commit',
    description: '',
    identifier: 'signer_name' },
  { code: '%GK',
    name: 'show the key used to sign a signed commit',
    fullDescription: 'show the key used to sign a signed commit',
    description: '',
    identifier: 'key' },
  // { code: '%gD',
  //   name: 'reflog selector',
  //   fullDescription: 'reflog selector, e.g., refs/stash@{1} or refs/stash@{2 minutes ago}; the format follows the rules described for the -g option. The portion before the @ is the refname as given on the command line (so git log -g refs/heads/master would yield refs/heads/master@{0}).',
  //   description: ', e.g., refs/stash@{1} or refs/stash@{2 minutes ago}; the format follows the rules described for the -g option. The portion before the @ is the refname as given on the command line (so git log -g refs/heads/master would yield refs/heads/master@{0}).',
  //   identifier: 'reflog_selector' },
  // { code: '%gd',
  //   name: 'shortened reflog selector',
  //   fullDescription: 'shortened reflog selector; same as %gD, but the refname portion is shortened for human readability (so refs/heads/master becomes just master).',
  //   description: '; same as %gD, but the refname portion is shortened for human readability (so refs/heads/master becomes just master).',
  //   identifier: 'shortened_reflog_selector' },
  // { code: '%gn',
  //   name: 'reflog identity name',
  //   fullDescription: 'reflog identity name',
  //   description: '',
  //   identifier: 'reflog_identity_name' },
  // { code: '%gN',
  //   name: 'reflog identity name',
  //   fullDescription: 'reflog identity name (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
  //   description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
  //   identifier: 'reflog_identity_name_mailmap' },
  // { code: '%ge',
  //   name: 'reflog identity email',
  //   fullDescription: 'reflog identity email',
  //   description: '',
  //   identifier: 'reflog_identity_email' },
  // { code: '%gE',
  //   name: 'reflog identity email',
  //   fullDescription: 'reflog identity email (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
  //   description: ' (respecting .mailmap, see git-shortlog[1] or git-blame[1])',
  //   identifier: 'reflog_identity_email_mailmap' },
  // { code: '%gs',
  //   name: 'reflog subject',
  //   fullDescription: 'reflog subject',
  //   description: '',
  //   identifier: 'reflog_subject' }
];

const formatString = exports.formatString = fields.map(field =>
  `${ field.code }%x00`
).join('');
<|endoftext|>


<commit_before>import ItemStore from '../../../.dist/store/item-store';
import ModelStore from '../../../.dist/store/model-store';
import { assert } from 'chai';
import { addAction } from '../../util/database';

describe('ItemStore', () => {

    let studentId = '123456';
    let modelAddress;
    let itemAddresses = [];

    before(() => {
        return addAction('CLEAR_ALL_DATA').then(() => {
            return addAction('NEW_MODEL', {
                name: 'Resistor'
            });
        }).then(actionId => {
            modelAddress = ModelStore.getModelByActionId(actionId).address;
            return addAction('NEW_STUDENT', {
                id: studentId,
                name: 'John von Neumann'
            });
        });
    });

    it('should instantiate without any items', () => {
        assert.lengthOf(ItemStore.getItems(), 0);
    });

    it('should create an item', () => {
        return addAction('NEW_ITEM', {
            modelAddress
        }).then(actionId => {
            itemAddresses.push(ItemStore.getItemByActionId(actionId).address);
            assert.lengthOf(ItemStore.getItems(), 1);
        });
    });

    it('should create more items', () => {
        return addAction('NEW_ITEM', {
            modelAddress
        }).then(actionId => {
            itemAddresses.push(ItemStore.getItemByActionId(actionId).address);
            return addAction('NEW_ITEM', {
                modelAddress
            });
        }).then(actionId => {
            itemAddresses.push(ItemStore.getItemByActionId(actionId).address);
            assert.lengthOf(ItemStore.getItems(), 3);
        });
    });

    it('should check out multiple items', () => {
        return addAction('NEW_CHECKOUT', {
            studentId,
            itemAddresses: [itemAddresses[0], itemAddresses[2]]
        }).then(() => {
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[0]).status, 'CHECKED_OUT');
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[1]).status, 'AVAILABLE');
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[2]).status, 'CHECKED_OUT');
        });
    });

    it('should check an item in', () => {
        return addAction('CHECKIN', {
            studentId,
            itemAddress: itemAddresses[0]
        }).then(() => {
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[0]).status, 'AVAILABLE');
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[1]).status, 'AVAILABLE');
            assert.strictEqual(ItemStore.getItemByAddress(itemAddresses[2]).status, 'CHECKED_OUT');
        });
    });

});
<commit_msg>Hold student/model/items, not their id/address<commit_after>import ItemStore from '../../../.dist/store/item-store';
import ModelStore from '../../../.dist/store/model-store';
import StudentStore from '../../../.dist/store/student-store';
import { assert } from 'chai';
import { addAction } from '../../util/database';

describe('ItemStore', () => {

    let student;
    let model;
    let items = [];

    before(() => {
        return addAction('CLEAR_ALL_DATA').then(() => {
            return addAction('NEW_MODEL', {
                name: 'Resistor'
            });
        }).then(actionId => {
            model = ModelStore.getModelByActionId(actionId);
            return addAction('NEW_STUDENT', {
                id: '123456',
                name: 'John von Neumann'
            });
        }).then(actionId => {
            student = StudentStore.getStudentByActionId(actionId);
        });
    });

    it('should instantiate without any items', () => {
        assert.lengthOf(ItemStore.getItems(), 0);
    });

    it('should create an item', () => {
        return addAction('NEW_ITEM', {
            modelAddress: model.address
        }).then(actionId => {
            items.push(ItemStore.getItemByActionId(actionId));
            assert.lengthOf(ItemStore.getItems(), 1);
        });
    });

    it('should create more items', () => {
        return addAction('NEW_ITEM', {
            modelAddress: model.address
        }).then(actionId => {
            items.push(ItemStore.getItemByActionId(actionId));
            return addAction('NEW_ITEM', {
                modelAddress: model.address
            });
        }).then(actionId => {
            items.push(ItemStore.getItemByActionId(actionId));
            assert.lengthOf(ItemStore.getItems(), 3);
        });
    });

    it('should check out multiple items', () => {
        return addAction('NEW_CHECKOUT', {
            studentId: student.id,
            itemAddresses: [items[0].address, items[2].address]
        }).then(() => {
            assert.strictEqual(items[0].status, 'CHECKED_OUT');
            assert.strictEqual(items[1].status, 'AVAILABLE');
            assert.strictEqual(items[2].status, 'CHECKED_OUT');
        });
    });

    it('should check an item in', () => {
        return addAction('CHECKIN', {
            studentId: student.id,
            itemAddress: items[0].address
        }).then(() => {
            assert.strictEqual(items[0].status, 'AVAILABLE');
            assert.strictEqual(items[1].status, 'AVAILABLE');
            assert.strictEqual(items[2].status, 'CHECKED_OUT');
        });
    });

});
<|endoftext|>