<commit_before>// const chai = require('chai')
// const expect = chai.expect

require('co-mocha')

const assert = require('assert')
const nock = require('nock')
const rewire = require('rewire')
const cheerio = require('cheerio')
const os = require('os')
const path = require('path')
const cheerioTableparser = require('cheerio-tableparser')
const Bus = rewire('../../lib/bus')
const bus = new Bus()

// let rawHomePage = require('fs').readFileSync('test/bus/home_page.txt', 'utf8')
let rawDetailsPage = require('fs').readFileSync('test/bus/details_page_example.txt', 'utf8')

let parsedTimesDetails = {
  'routes': {
    'number': '212',
    'line': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
    'direction': 'PUTIM / TERMINAL CENTRAL',
    'itinerary': 'RUA CARLOS A. DE P. TORO – RUA MESSIAS DE ALVARENGA – AV. JOAO RODOLFO CASTELLI – AV. JOSE IGNACIO BICUDO – RUA JOSE GONCALVES CAMPOS – AV. JOSE IGNACIO BICUDO – AV. JOAO RODOLFO CASTELLI – RUA ITATIAIA – RUA TURUMIRIM – RUA NEPOMUCENO – AV. JOAO RODOLFO CASTELLI – ESTR. MUNIC. GLAUDISTON P. DE OLIVEIRA – AV. DOMINGOS MALDONADO CAMPOY – AV. BRIG. FARIA LIMA – AV. DOS ASTRONAUTAS – VD. DOS BANDEIRANTES – RUA BAHIA – RUA TUPA – PCA CAP. PEDRO PINTO DA CUNHA – AV. PEDRO A. CABRAL – VD. RAQUEL MARCONDES – RUA CEL. MORAES – RUA FRANCISCO RAFAEL – RUA SIQUEIRA CAMPOS – PCA PADRE JOAO – TERMINAL CENTRAL',
    'observation': 'AOS SABADOS E DOMINGOS TODAS AS VIAGENS ENTRAM NO VILA ADRIANA.\n(1) ATENDE AO VILA ADRIANA (2) CDP'
  },
  'times': {
    'dawn': {
      'week': ['05:10', '05:44'],
      'saturday': ['00:50', '05:00', '05:36'],
      'sunday': ['00:45', '05:00', '05:54']
    },
    'morning': {
      'week': ['06:12', '06:40', '07:08', '07:36', '08:04', '08:32', '09:00', '09:50(1)', '10:25(1)', '10:55(1)', '11:25(1)', '11:55(1)'],
      'saturday': ['06:12', '06:48', '07:22', '07:54', '08:26', '09:26', '09:58', '10:30', '11:02', '11:34'],
      'sunday': ['06:48', '07:42', '08:36', '09:56', '10:50', '11:57']
    },
    'afternoon': {
      'week': ['12:25(1)', '12:55(1)', '13:25(1)', '14:00(1)', '14:34(1)', '15:08(1)', '15:42(1)', '16:16(1)', '16:50(1)', '17:24(1)', '17:40(1)', '17:58(1)'],
      'saturday': ['12:06', '12:38', '13:10', '13:42', '13:42(2)', '14:46', '15:32', '16:00', '16:32', '17:04(2)', '17:52'],
      'sunday': ['12:51', '13:45(2)', '14:39', '15:33', '16:27(2)', '17:21']
    },
    'night': {
      'week': ['18:32(1)', '19:06(1)', '19:45(1)', '20:32(1)', '21:06(1)', '21:40(1)', '22:12(1)', '23:06(1)', '23:45(1)'],
      'saturday': ['18:52', '19:34', '20:20', '21:05', '21:55', '22:50', '23:40'],
      'sunday': ['18:15', '19:32', '20:26', '21:20', '22:30', '23:35']
    }
  }
}

describe('transformCSVArrayToObject', function () {
  beforeEach(() => {
    nock.cleanAll()
  })

  it('getPage - should get a nock page with success', function* () {
    // mock the http request for the url and send the static page as response simulating the real page
    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    let $ = yield bus._getPage('http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
    var title = $('head > title').text()

    let expectedTitle = 'Horários e Itinerários'

    assert(title.includes(expectedTitle))
  })

  it('should transform the plain array with the first property as the key and the rest as value', function () {
    let rawList = [
      ['linha', 212, 214],
      ['nome', 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60', 'VILA TESOURO / AV. ENG. FRANCISCO JOSE LONGO (VIA SEBASTIAO GUALBERTO) (CIRCULAR NO CENTRO) O.S.O. 25'],
      ['sentido', 'PUTIM / TERMINAL CENTRAL', 'VILA TESOURO / JOSE LONGO'],
      ['horarios', '', ''],
      ['rota', '', '']
    ]

    let parsedList = [{
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=1',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=1'
    }, {
      'line': 214,
      'name': 'VILA TESOURO / AV. ENG. FRANCISCO JOSE LONGO (VIA SEBASTIAO GUALBERTO) (CIRCULAR NO CENTRO) O.S.O. 25',
      'direction': 'VILA TESOURO / JOSE LONGO',
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=2',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=2'
    }]

    let result = bus._transformCSVArrayToObject(rawList)
    assert.deepEqual(result, parsedList)
  })

  it('parseBuses - should parse and return', function* () {
    let buses = [{
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60 / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=96'
    }]
    // mock the http request for the url and send the static page as response simulating the real page
    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    let result = yield bus._parseBuses(buses)
    assert.deepEqual(result, [parsedTimesDetails])
  })

  it('parseBusPage - should parse and return a single bus', function* () {
    let singleBus = {
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60 / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=96'
    }

    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    const parsedBus = yield bus._parseBusPage(singleBus)

    assert.deepEqual(parsedBus, parsedTimesDetails)
  })

  it('getScheduleTimes - should parse the details page and give the parsed results', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = yield bus._parseDetailsPage(cheerioEntirePage)

    assert.deepEqual(result, parsedTimesDetails)
  })

  it('chunkScheduleByPeriod: should split the schedule by dawn, morning, afternoon and night', function () {
    let rawInput = [
      'De segunda-feira a sexta-feira',
      '0 às 6h',
      '05:10',
      '05:44',
      'Aos sábados',
      '0 às 6h',
      '00:50',
      '05:00',
      '05:36',
      'Aos domingos e feriados',
      '0 às 6h',
      '00:45',
      '05:00',
      '05:54'
    ]

    let expectedDawn = {
      'week': [
        '05:10',
        '05:44'
      ],
      'saturday': [
        '00:50',
        '05:00',
        '05:36'
      ],
      'sunday': [
        '00:45',
        '05:00',
        '05:54'
      ]
    }

    let result = bus._chunkScheduleByPeriod(rawInput)
    assert.deepEqual(result, expectedDawn)
  })

  it('getRouteMetadata - should extract the route data from page', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = yield bus._getRouteMetadata(cheerioEntirePage)

    assert.deepEqual(result, parsedTimesDetails.routes)
  })

  it('getObservationInfo - should extract the observation data', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = bus._getObservationInfo(cheerioEntirePage)

    assert.deepEqual(result, '(1) ATENDE AO VILA ADRIANA (2) CDP')
  })

  it('createFolder - should create a folder if it not exists', function* () {
    const tempPath = os.tmpdir()
    let result = yield bus._saveFile(parsedTimesDetails, tempPath)

    assert.equal(result, undefined)
  })
})
<commit_msg>added tests for the complete execution<commit_after>// const chai = require('chai')
// const expect = chai.expect

require('co-mocha')

const assert = require('assert')
const nock = require('nock')
const rewire = require('rewire')
const cheerio = require('cheerio')
const os = require('os')
const path = require('path')
const cheerioTableparser = require('cheerio-tableparser')
const Bus = rewire('../../lib/bus')
const bus = new Bus()

// let rawHomePage = require('fs').readFileSync('test/bus/home_page.txt', 'utf8')
let rawDetailsPage = require('fs').readFileSync('test/bus/details_page_example.txt', 'utf8')

let parsedTimesDetails = {
  'routes': {
    'number': '212',
    'line': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
    'direction': 'PUTIM / TERMINAL CENTRAL',
    'itinerary': 'RUA CARLOS A. DE P. TORO – RUA MESSIAS DE ALVARENGA – AV. JOAO RODOLFO CASTELLI – AV. JOSE IGNACIO BICUDO – RUA JOSE GONCALVES CAMPOS – AV. JOSE IGNACIO BICUDO – AV. JOAO RODOLFO CASTELLI – RUA ITATIAIA – RUA TURUMIRIM – RUA NEPOMUCENO – AV. JOAO RODOLFO CASTELLI – ESTR. MUNIC. GLAUDISTON P. DE OLIVEIRA – AV. DOMINGOS MALDONADO CAMPOY – AV. BRIG. FARIA LIMA – AV. DOS ASTRONAUTAS – VD. DOS BANDEIRANTES – RUA BAHIA – RUA TUPA – PCA CAP. PEDRO PINTO DA CUNHA – AV. PEDRO A. CABRAL – VD. RAQUEL MARCONDES – RUA CEL. MORAES – RUA FRANCISCO RAFAEL – RUA SIQUEIRA CAMPOS – PCA PADRE JOAO – TERMINAL CENTRAL',
    'observation': 'AOS SABADOS E DOMINGOS TODAS AS VIAGENS ENTRAM NO VILA ADRIANA.\n(1) ATENDE AO VILA ADRIANA (2) CDP'
  },
  'times': {
    'dawn': {
      'week': ['05:10', '05:44'],
      'saturday': ['00:50', '05:00', '05:36'],
      'sunday': ['00:45', '05:00', '05:54']
    },
    'morning': {
      'week': ['06:12', '06:40', '07:08', '07:36', '08:04', '08:32', '09:00', '09:50(1)', '10:25(1)', '10:55(1)', '11:25(1)', '11:55(1)'],
      'saturday': ['06:12', '06:48', '07:22', '07:54', '08:26', '09:26', '09:58', '10:30', '11:02', '11:34'],
      'sunday': ['06:48', '07:42', '08:36', '09:56', '10:50', '11:57']
    },
    'afternoon': {
      'week': ['12:25(1)', '12:55(1)', '13:25(1)', '14:00(1)', '14:34(1)', '15:08(1)', '15:42(1)', '16:16(1)', '16:50(1)', '17:24(1)', '17:40(1)', '17:58(1)'],
      'saturday': ['12:06', '12:38', '13:10', '13:42', '13:42(2)', '14:46', '15:32', '16:00', '16:32', '17:04(2)', '17:52'],
      'sunday': ['12:51', '13:45(2)', '14:39', '15:33', '16:27(2)', '17:21']
    },
    'night': {
      'week': ['18:32(1)', '19:06(1)', '19:45(1)', '20:32(1)', '21:06(1)', '21:40(1)', '22:12(1)', '23:06(1)', '23:45(1)'],
      'saturday': ['18:52', '19:34', '20:20', '21:05', '21:55', '22:50', '23:40'],
      'sunday': ['18:15', '19:32', '20:26', '21:20', '22:30', '23:35']
    }
  }
}

describe('transformCSVArrayToObject', function () {
  beforeEach(() => {
    nock.cleanAll()
  })

  it('getPage - should get a nock page with success', function* () {
    // mock the http request for the url and send the static page as response simulating the real page
    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    let $ = yield bus._getPage('http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
    var title = $('head > title').text()

    let expectedTitle = 'Horários e Itinerários'

    assert(title.includes(expectedTitle))
  })

  it('should transform the plain array with the first property as the key and the rest as value', function () {
    let rawList = [
      ['linha', 212, 214],
      ['nome', 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60', 'VILA TESOURO / AV. ENG. FRANCISCO JOSE LONGO (VIA SEBASTIAO GUALBERTO) (CIRCULAR NO CENTRO) O.S.O. 25'],
      ['sentido', 'PUTIM / TERMINAL CENTRAL', 'VILA TESOURO / JOSE LONGO'],
      ['horarios', '', ''],
      ['rota', '', '']
    ]

    let parsedList = [{
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=1',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=1'
    }, {
      'line': 214,
      'name': 'VILA TESOURO / AV. ENG. FRANCISCO JOSE LONGO (VIA SEBASTIAO GUALBERTO) (CIRCULAR NO CENTRO) O.S.O. 25',
      'direction': 'VILA TESOURO / JOSE LONGO',
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=2',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=2'
    }]

    let result = bus._transformCSVArrayToObject(rawList)
    assert.deepEqual(result, parsedList)
  })

  it('parseBuses - should parse and return', function* () {
    let buses = [{
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60 / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=96'
    }]
    // mock the http request for the url and send the static page as response simulating the real page
    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    let result = yield bus._parseBuses(buses)
    assert.deepEqual(result, [parsedTimesDetails])
  })

  it('parseBusPage - should parse and return a single bus', function* () {
    let singleBus = {
      'busSchedule': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96',
      'direction': 'PUTIM / TERMINAL CENTRAL',
      'line': 212,
      'name': 'PUTIM / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60 / TERMINAL CENTRAL – VIA AV. DOS ASTRONAUTAS (CIRCULAR NO CENTRO) O.S.O. 60',
      'route': 'http://www.sjc.sp.gov.br/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=m&id_linha=96'
    }

    nock('http://www.sjc.sp.gov.br')
      .get('/secretarias/mobilidade_urbana/horario-e-itinerario.aspx?acao=d&id_linha=96')
      .reply(200, rawDetailsPage)

    const parsedBus = yield bus._parseBusPage(singleBus)

    assert.deepEqual(parsedBus, parsedTimesDetails)
  })

  it('getScheduleTimes - should parse the details page and give the parsed results', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = yield bus._parseDetailsPage(cheerioEntirePage)

    assert.deepEqual(result, parsedTimesDetails)
  })

  it('chunkScheduleByPeriod: should split the schedule by dawn, morning, afternoon and night', function () {
    let rawInput = [
      'De segunda-feira a sexta-feira',
      '0 às 6h',
      '05:10',
      '05:44',
      'Aos sábados',
      '0 às 6h',
      '00:50',
      '05:00',
      '05:36',
      'Aos domingos e feriados',
      '0 às 6h',
      '00:45',
      '05:00',
      '05:54'
    ]

    let expectedDawn = {
      'week': [
        '05:10',
        '05:44'
      ],
      'saturday': [
        '00:50',
        '05:00',
        '05:36'
      ],
      'sunday': [
        '00:45',
        '05:00',
        '05:54'
      ]
    }

    let result = bus._chunkScheduleByPeriod(rawInput)
    assert.deepEqual(result, expectedDawn)
  })

  it('getRouteMetadata - should extract the route data from page', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = yield bus._getRouteMetadata(cheerioEntirePage)

    assert.deepEqual(result, parsedTimesDetails.routes)
  })

  it('getObservationInfo - should extract the observation data', function* () {
    let cheerioEntirePage = cheerio.load(rawDetailsPage)
    cheerioTableparser(cheerioEntirePage)

    let result = bus._getObservationInfo(cheerioEntirePage)

    assert.deepEqual(result, '(1) ATENDE AO VILA ADRIANA (2) CDP')
  })

  it('createFolder - should create a folder if it not exists', function* () {
    const tempPath = os.tmpdir()
    let result = yield bus._saveFile(parsedTimesDetails, tempPath)

    assert.equal(result, undefined)
  })

  // it.only('Execute!', function* () {
  //   let result = yield bus.execute()
  //   assert.equal(result, undefined)
  // })
})
<|endoftext|>


<commit_before>var pretender;
module("pretender invoking", {
  setup: function(){
    pretender = new Pretender();
  },
  teardown: function(){
    pretender && pretender.shutdown();
    pretender = null;
  }
});

test("a mapping function is optional", function(){
  var wasCalled;
  pretender.get('/some/path', function(){
    wasCalled = true;
  });

  $.ajax({url: '/some/path'});
  ok(wasCalled);
});

test("params are passed", function(){
  var params;
  pretender.get('/some/path/:id', function(request){
    params = request.params;
  });

  $.ajax({url: '/some/path/1'});
  equal(params.id, 1);
});

test("queryParams are passed", function(){
  var params;
  pretender.get('/some/path', function(request){
    params = request.queryParams;
  });

  $.ajax({url: '/some/path?zulu=nation'});
  equal(params.zulu, 'nation');
});

test("adds requests to the list of handled requests", function(){
  var params;
  pretender.get('/some/path', function(request){
    params = request.queryParams;
  });

  $.ajax({url: '/some/path'});

  var req = pretender.handledRequests[0];
  equal(req.url, '/some/path');
});

test("increments the handler's request count", function(){
  var handler = function(req){};

  pretender.get('/some/path', handler);

  $.ajax({url: '/some/path'});

  equal(handler.numberOfCalls, 1);
});

test("handledRequest is called", function(){
  pretender.get('/some/path', function(){});
  pretender.handledRequest = function(){
    ok(true, "handledRequest hook was called");
  };
  $.ajax({url: '/some/path'});
});

test("prepareBody is called", function(){
  var obj = {foo: 'bar'};
  pretender.prepareBody = JSON.stringify;
  pretender.get('/some/path', function(req){
    return [200, {}, obj];
  });

  $.ajax({
    url: '/some/path',
    success: function(resp){
      deepEqual(JSON.parse(resp), obj);
    }
  });
});
<commit_msg>add a test case for multiple handlers<commit_after>var pretender;
module("pretender invoking", {
  setup: function(){
    pretender = new Pretender();
  },
  teardown: function(){
    pretender && pretender.shutdown();
    pretender = null;
  }
});

test("a mapping function is optional", function(){
  var wasCalled;
  pretender.get('/some/path', function(){
    wasCalled = true;
  });

  $.ajax({url: '/some/path'});
  ok(wasCalled);
});

test("params are passed", function(){
  var params;
  pretender.get('/some/path/:id', function(request){
    params = request.params;
  });

  $.ajax({url: '/some/path/1'});
  equal(params.id, 1);
});

test("queryParams are passed", function(){
  var params;
  pretender.get('/some/path', function(request){
    params = request.queryParams;
  });

  $.ajax({url: '/some/path?zulu=nation'});
  equal(params.zulu, 'nation');
});

test("adds requests to the list of handled requests", function(){
  var params;
  pretender.get('/some/path', function(request){
    params = request.queryParams;
  });

  $.ajax({url: '/some/path'});

  var req = pretender.handledRequests[0];
  equal(req.url, '/some/path');
});

test("increments the handler's request count", function(){
  var handler = function(req){};

  pretender.get('/some/path', handler);

  $.ajax({url: '/some/path'});

  equal(handler.numberOfCalls, 1);
});

test("handledRequest is called", function(){
  pretender.get('/some/path', function(){});
  pretender.handledRequest = function(){
    ok(true, "handledRequest hook was called");
  };
  $.ajax({url: '/some/path'});
});

test("prepareBody is called", function(){
  var obj = {foo: 'bar'};
  pretender.prepareBody = JSON.stringify;
  pretender.get('/some/path', function(req){
    return [200, {}, obj];
  });

  $.ajax({
    url: '/some/path',
    success: function(resp){
      deepEqual(JSON.parse(resp), obj);
    }
  });
});

test("will use the latest defined handler", function(){
  expect(1);
  var latestHandlerWasCalled = false;
  pretender.get('/some/path', function(request){
    // no op
  });
  pretender.get('/some/path', function(request){
    latestHandlerWasCalled = true
  });
  $.ajax({url: '/some/path'});
  ok(latestHandlerWasCalled, 'calls the latest handler');
});
<|endoftext|>


<commit_before>define(["helper/Test", "Tone/core/Context", "Tone/core/Tone", "helper/Offline", "helper/Supports", "helper/LoadHTML"],
	function(Test, Context, Tone, Offline, Supports, LoadHTML){

		describe("Context", function(){

			if (!Supports.AUDIO_CONTEXT_CLOSE_RESOLVES){
				return;
			}

			context("AudioContext", function(){

				it("extends the AudioContext methods", function(){
					var ctx = new Context();
					expect(ctx).to.have.property("createGain");
					expect(ctx.createGain()).to.be.instanceOf(GainNode);
					expect(ctx).to.have.property("createOscillator");
					expect(ctx.createOscillator()).to.be.instanceOf(OscillatorNode);
					expect(ctx).to.have.property("createDelay");
					expect(ctx.createDelay()).to.be.instanceOf(DelayNode);
					expect(ctx).to.have.property("createConstantSource");
					return ctx.dispose();
				});

				it("clock is running", function(done){
					var interval = setInterval(function(){
						if (Tone.context.currentTime > 0.5){
							clearInterval(interval);
							done();
						}
					}, 20);
				});

				it("can be created an disposed", function(){
					var ctx = new Context();
					return ctx.dispose().then(function(){
						Test.wasDisposed(ctx);
					});
				});

				it("has a rawContext", function(){
					var ctx = new Context();
					expect(ctx.rawContext).is.instanceOf(window.AudioContext);
					return ctx.dispose();
				});

				it("'dispose' returns a promise which resolves", function(){
					var ctx = new Context();
					var promise = ctx.dispose();
					expect(promise).to.have.property("then");
					return promise;
				});

				it("can be constructed with an options object", function(){
					var ctx = new Context({
						"lookAhead" : 0.2,
						"latencyHint" : "fastest",
						"clockSource" : "timeout"
					});
					expect(ctx.lookAhead).to.equal(0.2);
					expect(ctx.latencyHint).to.equal("fastest");
					expect(ctx.clockSource).to.equal("timeout");
					return ctx.dispose();
				});
			});

			context("clockSource", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("defaults to 'worker'", function(){
					expect(ctx.clockSource).to.equal("worker");
				});

				it("provides callback", function(done){
					expect(ctx.clockSource).to.equal("worker");
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("can be set to 'timeout'", function(done){
					ctx.clockSource = "timeout";
					expect(ctx.clockSource).to.equal("timeout");
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("can be set to 'offline'", function(done){
					ctx.clockSource = "offline";
					expect(ctx.clockSource).to.equal("offline");
					//provides no callback
					ctx.setTimeout(function(){
						throw new Error("shouldn't be called");
					}, 0.1);
					setTimeout(function(){
						done();
					}, 200);
				});
			});

			context("setTimeout", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("can set a timeout", function(done){
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("returns an id", function(){
					expect(ctx.setTimeout(function(){}, 0.1)).to.be.a("number");
					//try clearing a random ID, shouldn't cause any errors
					ctx.clearTimeout(-2);
				});

				it("timeout is not invoked when cancelled", function(done){
					var id = ctx.setTimeout(function(){
						throw new Error("shouldn't be invoked");
					}, 0.01);
					ctx.clearTimeout(id);
					ctx.setTimeout(function(){
						done();
					}, 0.02);
				});

				it("order is maintained", function(done){
					var wasInvoked = false;
					ctx.setTimeout(function(){
						expect(wasInvoked).to.be.true;
						done();
					}, 0.02);
					ctx.setTimeout(function(){
						wasInvoked = true;
					}, 0.01);
				});

				it("is invoked in the offline context", function(){
					return Offline(function(Transport){
						Transport.context.setTimeout(function(){
							expect(Tone.now()).to.be.closeTo(0.01, 0.005);
						}, 0.01);
					}, 0.05);
				});
			});

			context("Tone", function(){

				it("has a context", function(){
					expect(Tone.context).to.exist;
					expect(Tone.context).to.be.instanceOf(Context);
				});

				it("can set a new context", function(){
					var originalContext = Tone.context;
					Tone.context = new Context();
					return Tone.context.dispose().then(function(){
						Tone.context = originalContext;
					});
				});

				it("has a consistent context after offline rendering", function(){
					var initialContext = Tone.context;
					var initialTransport = Tone.Transport;
					return Offline(function(){}).then(function(){
						expect(Tone.context).to.equal(initialContext);
						expect(Tone.Transport).to.equal(initialTransport);
					});
				});

				it("invokes the resume promise", function(){
					return Tone.context.resume();
				});

				it("invokes init when a new context is set", function(done){
					this.timeout(200);
					var initFn = function(context){
						expect(Tone.context).to.equal(context);
						Context.off("init", initFn);
						done();
					};
					Context.on("init", initFn);
					Tone.context = new Context();
				});

				it("invokes close when a context is disposed", function(done){
					this.timeout(200);
					var closeFn = function(context){
						expect(context).to.be.instanceOf(Context);
						Context.off("close", closeFn);
						//set a new context
						Tone.context = new Context();
						done();
					};
					Context.on("close", closeFn);
					Tone.context.dispose();
				});

				it("can have two instances running on the same page", function(){
					var baseUrl = "../test/html/";
					if (window.__karma__){
						baseUrl = "/base/test/html/";
					}
					return LoadHTML(baseUrl + "multiple_instances.html");
				});

				/*it("Transport and Master instance is the same after running Tone.Offline", function(){
					var baseUrl = "../test/html/";
					if (window.__karma__){
						baseUrl = "/base/test/html/";
					}
					return LoadHTML(baseUrl + "same_transport.html");
				});*/
			});

			context("get/set", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("can set the lookAhead", function(){
					ctx.lookAhead = 0.05;
					expect(ctx.lookAhead).to.equal(0.05);
				});

				it("can set the updateInterval", function(){
					ctx.updateInterval = 0.05;
					expect(ctx.updateInterval).to.equal(0.05);
				});

				it("can set the latencyHint", function(){
					ctx.latencyHint = "fastest";
					expect(ctx.latencyHint).to.equal("fastest");
					expect(ctx.lookAhead).to.be.closeTo(0.01, 0.05);
					expect(ctx.updateInterval).to.be.closeTo(0.01, 0.05);
					// test all other latency hints
					var latencyHints = ["interactive", "playback", "balanced", 0.2];
					latencyHints.forEach(function(hint){
						ctx.latencyHint = hint;
						expect(ctx.latencyHint).to.equal(hint);
					});
				});

				it("gets a constant signal", function(){
					var bufferSrc = ctx.getConstant(1);
					expect(bufferSrc).is.instanceOf(AudioBufferSourceNode);
					var buffer = bufferSrc.buffer.getChannelData(0);
					for (var i = 0; i < buffer.length; i++){
						expect(buffer[i]).to.equal(1);
					}
				});

				it("multiple calls return the same buffer source", function(){
					var bufferA = ctx.getConstant(2);
					var bufferB = ctx.getConstant(2);
					expect(bufferA).to.equal(bufferB);
				});

			});
		});

	});
<commit_msg>removing test<commit_after>define(["helper/Test", "Tone/core/Context", "Tone/core/Tone", "helper/Offline", "helper/Supports", "helper/LoadHTML"],
	function(Test, Context, Tone, Offline, Supports, LoadHTML){

		describe("Context", function(){

			if (!Supports.AUDIO_CONTEXT_CLOSE_RESOLVES){
				return;
			}

			context("AudioContext", function(){

				it("extends the AudioContext methods", function(){
					var ctx = new Context();
					expect(ctx).to.have.property("createGain");
					expect(ctx.createGain()).to.be.instanceOf(GainNode);
					expect(ctx).to.have.property("createOscillator");
					expect(ctx.createOscillator()).to.be.instanceOf(OscillatorNode);
					expect(ctx).to.have.property("createDelay");
					expect(ctx.createDelay()).to.be.instanceOf(DelayNode);
					expect(ctx).to.have.property("createConstantSource");
					return ctx.dispose();
				});

				it("clock is running", function(done){
					var interval = setInterval(function(){
						if (Tone.context.currentTime > 0.5){
							clearInterval(interval);
							done();
						}
					}, 20);
				});

				it("can be created an disposed", function(){
					var ctx = new Context();
					return ctx.dispose().then(function(){
						Test.wasDisposed(ctx);
					});
				});

				it("has a rawContext", function(){
					var ctx = new Context();
					expect(ctx.rawContext).is.instanceOf(window.AudioContext);
					return ctx.dispose();
				});

				it("'dispose' returns a promise which resolves", function(){
					var ctx = new Context();
					var promise = ctx.dispose();
					expect(promise).to.have.property("then");
					return promise;
				});

				it("can be constructed with an options object", function(){
					var ctx = new Context({
						"lookAhead" : 0.2,
						"latencyHint" : "fastest",
						"clockSource" : "timeout"
					});
					expect(ctx.lookAhead).to.equal(0.2);
					expect(ctx.latencyHint).to.equal("fastest");
					expect(ctx.clockSource).to.equal("timeout");
					return ctx.dispose();
				});
			});

			context("clockSource", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("defaults to 'worker'", function(){
					expect(ctx.clockSource).to.equal("worker");
				});

				it("provides callback", function(done){
					expect(ctx.clockSource).to.equal("worker");
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("can be set to 'timeout'", function(done){
					ctx.clockSource = "timeout";
					expect(ctx.clockSource).to.equal("timeout");
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("can be set to 'offline'", function(done){
					ctx.clockSource = "offline";
					expect(ctx.clockSource).to.equal("offline");
					//provides no callback
					ctx.setTimeout(function(){
						throw new Error("shouldn't be called");
					}, 0.1);
					setTimeout(function(){
						done();
					}, 200);
				});
			});

			context("setTimeout", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("can set a timeout", function(done){
					ctx.setTimeout(function(){
						done();
					}, 0.1);
				});

				it("returns an id", function(){
					expect(ctx.setTimeout(function(){}, 0.1)).to.be.a("number");
					//try clearing a random ID, shouldn't cause any errors
					ctx.clearTimeout(-2);
				});

				it("timeout is not invoked when cancelled", function(done){
					var id = ctx.setTimeout(function(){
						throw new Error("shouldn't be invoked");
					}, 0.01);
					ctx.clearTimeout(id);
					ctx.setTimeout(function(){
						done();
					}, 0.02);
				});

				it("order is maintained", function(done){
					var wasInvoked = false;
					ctx.setTimeout(function(){
						expect(wasInvoked).to.be.true;
						done();
					}, 0.02);
					ctx.setTimeout(function(){
						wasInvoked = true;
					}, 0.01);
				});

				it("is invoked in the offline context", function(){
					return Offline(function(Transport){
						Transport.context.setTimeout(function(){
							expect(Tone.now()).to.be.closeTo(0.01, 0.005);
						}, 0.01);
					}, 0.05);
				});
			});

			context("Tone", function(){

				it("has a context", function(){
					expect(Tone.context).to.exist;
					expect(Tone.context).to.be.instanceOf(Context);
				});

				it("can set a new context", function(){
					var originalContext = Tone.context;
					Tone.context = new Context();
					return Tone.context.dispose().then(function(){
						Tone.context = originalContext;
					});
				});

				it("has a consistent context after offline rendering", function(){
					var initialContext = Tone.context;
					var initialTransport = Tone.Transport;
					return Offline(function(){}).then(function(){
						expect(Tone.context).to.equal(initialContext);
						expect(Tone.Transport).to.equal(initialTransport);
					});
				});

				it("invokes the resume promise", function(){
					return Tone.context.resume();
				});

				it("invokes init when a new context is set", function(done){
					this.timeout(200);
					var initFn = function(context){
						expect(Tone.context).to.equal(context);
						Context.off("init", initFn);
						done();
					};
					Context.on("init", initFn);
					Tone.context = new Context();
				});

				it("invokes close when a context is disposed", function(done){
					this.timeout(200);
					var closeFn = function(context){
						expect(context).to.be.instanceOf(Context);
						Context.off("close", closeFn);
						//set a new context
						Tone.context = new Context();
						done();
					};
					Context.on("close", closeFn);
					Tone.context.dispose();
				});

				/*it("can have two instances running on the same page", function(){
					var baseUrl = "../test/html/";
					if (window.__karma__){
						baseUrl = "/base/test/html/";
					}
					return LoadHTML(baseUrl + "multiple_instances.html");
				});*/

				/*it("Transport and Master instance is the same after running Tone.Offline", function(){
					var baseUrl = "../test/html/";
					if (window.__karma__){
						baseUrl = "/base/test/html/";
					}
					return LoadHTML(baseUrl + "same_transport.html");
				});*/
			});

			context("get/set", function(){

				var ctx;
				beforeEach(function(){
					ctx = new Context();
					return ctx.resume();
				});

				afterEach(function(){
					return ctx.dispose();
				});

				it("can set the lookAhead", function(){
					ctx.lookAhead = 0.05;
					expect(ctx.lookAhead).to.equal(0.05);
				});

				it("can set the updateInterval", function(){
					ctx.updateInterval = 0.05;
					expect(ctx.updateInterval).to.equal(0.05);
				});

				it("can set the latencyHint", function(){
					ctx.latencyHint = "fastest";
					expect(ctx.latencyHint).to.equal("fastest");
					expect(ctx.lookAhead).to.be.closeTo(0.01, 0.05);
					expect(ctx.updateInterval).to.be.closeTo(0.01, 0.05);
					// test all other latency hints
					var latencyHints = ["interactive", "playback", "balanced", 0.2];
					latencyHints.forEach(function(hint){
						ctx.latencyHint = hint;
						expect(ctx.latencyHint).to.equal(hint);
					});
				});

				it("gets a constant signal", function(){
					var bufferSrc = ctx.getConstant(1);
					expect(bufferSrc).is.instanceOf(AudioBufferSourceNode);
					var buffer = bufferSrc.buffer.getChannelData(0);
					for (var i = 0; i < buffer.length; i++){
						expect(buffer[i]).to.equal(1);
					}
				});

				it("multiple calls return the same buffer source", function(){
					var bufferA = ctx.getConstant(2);
					var bufferB = ctx.getConstant(2);
					expect(bufferA).to.equal(bufferB);
				});

			});
		});

	});
<|endoftext|>


<commit_before>var test = require('tape');
var parse = require('../');

test('boolean default true', function (t) {
    var argv = parse([], {
        boolean: 'sometrue',
        default: { sometrue: true }
    });
    t.equal(argv.sometrue, true);
    t.end();
});

test('boolean default false', function (t) {
    var argv = parse([], {
        boolean: 'somefalse',
        default: { somefalse: false }
    });
    t.equal(argv.somefalse, false);
    t.end();
});
<commit_msg>test for setting a boolean to a null default<commit_after>var test = require('tape');
var parse = require('../');

test('boolean default true', function (t) {
    var argv = parse([], {
        boolean: 'sometrue',
        default: { sometrue: true }
    });
    t.equal(argv.sometrue, true);
    t.end();
});

test('boolean default false', function (t) {
    var argv = parse([], {
        boolean: 'somefalse',
        default: { somefalse: false }
    });
    t.equal(argv.somefalse, false);
    t.end();
});

test('boolean default to null', function (t) {
    var argv = parse([], {
        boolean: 'maybe',
        default: { maybe: null }
    });
    t.equal(argv.maybe, null);
    var argv = parse(['--maybe'], {
        boolean: 'maybe',
        default: { maybe: null }
    });
    t.equal(argv.maybe, true);
    t.end();

})
<|endoftext|>


<commit_before>'use strict';

// Chai is a BDD / TDD assertion library
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var config = require('./protractor.conf.js').config;

var helperForms = require('./utils/forms');
var helperBrowser = require('./utils/browser');

chai.use(chaiAsPromised);
var expect = chai.expect;

// For some weird reason config ignores allScriptsTimeout
browser.manage().timeouts().setScriptTimeout(20000);

describe('register form', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should render the register form', function(done) {
    expect($("form[name='registerForm']").getText())
      .to.exist
      .and.notify(done);
  });
});

describe('user name field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should accept a non-existing user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "-new")
      .then(function(){
        var message = $("form[name='registerForm'] .success[rp-error-valid]");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny an existing user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username)
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='exists']");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a reserved user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("google")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='reserved']");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a too short user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("xy")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='tooshort']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name with a wrong charset', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "ä")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='charset']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name starting with a hyphen', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("-" + config.user.username)
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='starthyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name ending with a hyphen', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "-")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='endhyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name with multiple hyphens', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "--x")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='multhyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('password field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny a weak password', function(done) {
    $(".auth-form-wrapper #register_password")
      .sendKeys("123456")
      .then(function(){
        var message = $(".ng-invalid-rp-strong-password#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a strong password', function(done) {
    $(".auth-form-wrapper #register_password")
      .sendKeys("73571n6.")
      .then(function(){
        var message = $(".ng-valid-rp-strong-password#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny non-matching passwords', function(done) {
    $(".auth-form-wrapper #register_password").sendKeys("73571n6.");
    $(".auth-form-wrapper #register_password2").sendKeys("73571n6")
      .then(function(){
        var message = $(".ng-invalid-rp-same-in-set#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept matching passwords', function(done) {
    $(".auth-form-wrapper #register_password").sendKeys("73571n6.");
    $(".auth-form-wrapper #register_password2").sendKeys("73571n6.")
      .then(function(){
        var message = $(".ng-valid-rp-same-in-set#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('email field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny an invalid email', function(done) {
    $(".auth-form-wrapper #register_email").sendKeys("e2e-test")
      .then(function(){
        var message = $(".ng-invalid-email#register_email");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a valid email', function(done) {
    $(".auth-form-wrapper #register_email").sendKeys("e2e-test+index@example.com")
      .then(function(){
        var message = $(".ng-valid-email#register_email");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('secret field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny an invalid secret', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys("test-invalid-key")
      .then(function(){
        var message = $(".ng-invalid-rp-master-key#register_masterkey");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a valid secret', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys(config.oldUser.secret)
      .then(function(){
        var message = $(".ng-valid-rp-master-key#register_masterkey");
        expect(message.isPresent())
          .to.eventually.be.true;
        message = $(".ng-valid-rp-master-address-exists#register_masterkey");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a valid secret that already has an account', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys(config.user.secret)
      .then(function(){
        var message = $(".register_masterkey .auth-attention:not(.ng-hide)");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('register button', function() {

  var username = "e2e-test-reg-" + Math.floor(Math.random() * 1000000);

  before(function(){
    browser.get('#/register');
    $(".auth-form-wrapper #register_username").sendKeys(username);
    $(".auth-form-wrapper #register_password").sendKeys(config.user.password);
    $(".auth-form-wrapper #register_password2").sendKeys(config.user.password);
    $(".auth-form-wrapper #register_email").sendKeys("test@example.com");
    $(".auth-form-wrapper #terms").click()
      .then(function(){
        var message = $("form[name='registerForm'] .success[rp-error-valid]");
        helperBrowser.waitForElement(message);
      });
  });

  it('should be active', function(done) {
    expect($(".submit-btn-container button").getAttribute('disabled'))
      .to.eventually.not.equal('disabled')
      .and.notify(done);
  });

  it('click should register the user', function(done) {
    $(".submit-btn-container button").click()
    .then(function () {
      var message = $("form[name='resendForm']");
      helperBrowser.waitForElement(message);
      expect(message.isPresent())
        .to.eventually.be.true
        .and.notify(done);
    });
  });

});
<commit_msg>[FIX] e2e: Remove setScriptTimeout for register.js<commit_after>'use strict';

// Chai is a BDD / TDD assertion library
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var config = require('./protractor.conf.js').config;

var helperForms = require('./utils/forms');
var helperBrowser = require('./utils/browser');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('register form', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should render the register form', function(done) {
    expect($("form[name='registerForm']").getText())
      .to.exist
      .and.notify(done);
  });
});

describe('user name field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should accept a non-existing user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "-new")
      .then(function(){
        var message = $("form[name='registerForm'] .success[rp-error-valid]");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny an existing user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username)
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='exists']");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a reserved user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("google")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='reserved']");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a too short user name', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("xy")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='tooshort']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name with a wrong charset', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "ä")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='charset']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name starting with a hyphen', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys("-" + config.user.username)
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='starthyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name ending with a hyphen', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "-")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='endhyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a user name with multiple hyphens', function(done) {
    $(".auth-form-wrapper #register_username")
      .sendKeys(config.user.username + "--x")
      .then(function(){
        var message = $("form[name='registerForm'] .errorGroup[rp-errors='register_username'] span[ng-switch-when='multhyphen']");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('password field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny a weak password', function(done) {
    $(".auth-form-wrapper #register_password")
      .sendKeys("123456")
      .then(function(){
        var message = $(".ng-invalid-rp-strong-password#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a strong password', function(done) {
    $(".auth-form-wrapper #register_password")
      .sendKeys("73571n6.")
      .then(function(){
        var message = $(".ng-valid-rp-strong-password#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny non-matching passwords', function(done) {
    $(".auth-form-wrapper #register_password").sendKeys("73571n6.");
    $(".auth-form-wrapper #register_password2").sendKeys("73571n6")
      .then(function(){
        var message = $(".ng-invalid-rp-same-in-set#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept matching passwords', function(done) {
    $(".auth-form-wrapper #register_password").sendKeys("73571n6.");
    $(".auth-form-wrapper #register_password2").sendKeys("73571n6.")
      .then(function(){
        var message = $(".ng-valid-rp-same-in-set#register_password");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('email field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny an invalid email', function(done) {
    $(".auth-form-wrapper #register_email").sendKeys("e2e-test")
      .then(function(){
        var message = $(".ng-invalid-email#register_email");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a valid email', function(done) {
    $(".auth-form-wrapper #register_email").sendKeys("e2e-test+index@example.com")
      .then(function(){
        var message = $(".ng-valid-email#register_email");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('secret field', function() {

  beforeEach(function(){
    browser.get('#/register');
  });

  it('should deny an invalid secret', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys("test-invalid-key")
      .then(function(){
        var message = $(".ng-invalid-rp-master-key#register_masterkey");
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should accept a valid secret', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys(config.oldUser.secret)
      .then(function(){
        var message = $(".ng-valid-rp-master-key#register_masterkey");
        expect(message.isPresent())
          .to.eventually.be.true;
        message = $(".ng-valid-rp-master-address-exists#register_masterkey");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });

  it('should deny a valid secret that already has an account', function(done) {
    $(".auth-form-wrapper a[ng-click='showMasterKeyInput=true']").click();
    $(".auth-form-wrapper #register_masterkey").sendKeys(config.user.secret)
      .then(function(){
        var message = $(".register_masterkey .auth-attention:not(.ng-hide)");
        helperBrowser.waitForElement(message);
        expect(message.isPresent())
          .to.eventually.be.true
          .and.notify(done);
      });
  });
});

describe('register button', function() {

  var username = "e2e-test-reg-" + Math.floor(Math.random() * 1000000);

  before(function(){
    browser.get('#/register');
    $(".auth-form-wrapper #register_username").sendKeys(username);
    $(".auth-form-wrapper #register_password").sendKeys(config.user.password);
    $(".auth-form-wrapper #register_password2").sendKeys(config.user.password);
    $(".auth-form-wrapper #register_email").sendKeys("test@example.com");
    $(".auth-form-wrapper #terms").click()
      .then(function(){
        var message = $("form[name='registerForm'] .success[rp-error-valid]");
        helperBrowser.waitForElement(message);
      });
  });

  it('should be active', function(done) {
    expect($(".submit-btn-container button").getAttribute('disabled'))
      .to.eventually.not.equal('disabled')
      .and.notify(done);
  });

  it('click should register the user', function(done) {
    $(".submit-btn-container button").click()
    .then(function () {
      var message = $("form[name='resendForm']");
      helperBrowser.waitForElement(message);
      expect(message.isPresent())
        .to.eventually.be.true
        .and.notify(done);
    });
  });

});
<|endoftext|>


<commit_before>{
        'type': 'game', // game or console
        'name': 'Frogger',
        'authors': [],
        'company': ['Konami'],
        'year': '1981',
        'headline': 'Frogger',
        'resume': [
            'O título foi lançado pela Konami em 1981 para os arcades ',
            'e um ano depois, em 1982, foi lançado para o Atari 2600 ',
            'com algumas pequenas alterações gráficas devido às limitações ',
            'de cada plataforma. O objetivo do jogo era muito simples: ',
            'o jogador controlava um sapo, movendo-se para os lados, frente e trás ',
            'que precisa atravessar uma rua repleta de veículos e em seguida ',
            'um riacho, passando por cima de troncos que boiavam. Se o sapo ',
            'fosse atropelado por qualquer veículo ou caísse na água, Acabava o jogo.'.
        ].join(''),
        'full_text': [
            'Frogger foi um jogo criado em 1981 em uma parceria entre as então jovens ',
            'empresas de informática SEGA e Konami. Inicialmente fabricado para ',
            'máquinas de arcade, logo foi fabricado em grande escala para o console ',
            'mais popular da época, o Atari 2600, tornando-se também  um de seus jogos ',
            'mais jogados. A mecânica do jogo era simples, onde o jogador controla um sapo ',
            'podendo ser movimentado para os lados, para frente e para trás. E a cada ',
            'cinco anfíbios que o jogador conseguisse colocar do outro lado do rio, ',
            'um novo nível era iniciado. A dificuldade de cada fase era medida pela ',
            'velocidade dos objetos na avenida e no rio, deixando tudo bastante complicado ',
            'depois de alguns níveis. Frequentemente, moscas e outros sapos apareciam ',
            'durante o percurso, e se o jogador conseguisse pegá-lo, ganhava pontos. ',
            'Frogger foi um fenômeno dos videogames nos arcades e no Atari, ',
            'além de ter sido o primeiro grande hit da Konami. ',
            'Uma curiosidade de frogger é que aparece também em um seriado Americano, ',
            'chamado Seinfield, quando George Constanza, um dos personagens, cruza ',
            'a cidade com um fliperama original de Frogger, parodiando a própria ',
            'travessia de avenidas do título, Constanza fez um recorde ficcional de ',
            '863,050 pontos. A única pontuação real registrada que supera a de Seinfield ',
            'é de Michael Smith, de Springfield, em 2012, com 970,440 de pontos.'
            'Superando o norte-americano Pat Laffaye, com 896,980 pontos. Além disso, ',
            'o Frogger original, ou conversões similares da versão arcade, foi lançado ',
            'para mais de 10 plataformas, desde as mais conhecidas às mais raras. ',
            'Consoles como o Playstation ganharam uma versão 3D, que retomava ',
            'o jogo original e incluía novos níveis para controlar o sapinho. ',
            'No Super NES, Frogger foi um dos últimos jogos a ser lançados. ',
            'Entre os consoles atuais, somente o Xbox 360 disponibiliza-o para baixar.'.
        ].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"},
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
            {'name': 'picture2.png', 'caption': "description2"},
            {'name': 'picture3.png', 'caption': "description3"}
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=l9fO-YuWPSk', 'caption': "Frogger arcade game", 'type': "youtube"} // type: youtube or vimeo
            'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=vEsq-PGRJ5I', 'caption': "Frogger Atari 2600", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'demonstration_url', 'caption': "description"}
        ],
        'references': [
            {'url': 'reference_url1', 'caption': "description"},
            {'url': 'reference_url2', 'caption': "description"},
            {'url': 'reference_url3', 'caption': "description"}
        ]
}
<commit_msg>Update Frogger_temp.js<commit_after>{
        'type': 'game', // game or console
        'name': 'Frogger',
        'authors': [],
        'company': ['Konami'],
        'year': '1981',
        'headline': 'Frogger',
        'resume': [
            'O título foi lançado pela Konami em 1981 para os arcades ',
            'e um ano depois, em 1982, foi lançado para o Atari 2600 ',
            'com algumas pequenas alterações gráficas devido às limitações ',
            'de cada plataforma. O objetivo do jogo era muito simples: ',
            'o jogador controlava um sapo, movendo-se para os lados, frente e trás ',
            'que precisa atravessar uma rua repleta de veículos e em seguida ',
            'um riacho, passando por cima de troncos que boiavam. Se o sapo ',
            'fosse atropelado por qualquer veículo ou caísse na água, Acabava o jogo.'.
        ].join(''),
        'full_text': [
            'Frogger foi um jogo criado em 1981 em uma parceria entre as então jovens ',
            'empresas de informática SEGA e Konami. Inicialmente fabricado para ',
            'máquinas de arcade, logo foi fabricado em grande escala para o console ',
            'mais popular da época, o Atari 2600, tornando-se também  um de seus jogos ',
            'mais jogados. A mecânica do jogo era simples, onde o jogador controla um sapo ',
            'podendo ser movimentado para os lados, para frente e para trás. E a cada ',
            'cinco anfíbios que o jogador conseguisse colocar do outro lado do rio, ',
            'um novo nível era iniciado. A dificuldade de cada fase era medida pela ',
            'velocidade dos objetos na avenida e no rio, deixando tudo bastante complicado ',
            'depois de alguns níveis. Frequentemente, moscas e outros sapos apareciam ',
            'durante o percurso, e se o jogador conseguisse pegá-lo, ganhava pontos. ',
            'Frogger foi um fenômeno dos videogames nos arcades e no Atari, ',
            'além de ter sido o primeiro grande hit da Konami. ',
            'Uma curiosidade de frogger é que aparece também em um seriado Americano, ',
            'chamado Seinfield, quando George Constanza, um dos personagens, cruza ',
            'a cidade com um fliperama original de Frogger, parodiando a própria ',
            'travessia de avenidas do título, Constanza fez um recorde ficcional de ',
            '863,050 pontos. A única pontuação real registrada que supera a de Seinfield ',
            'é de Michael Smith, de Springfield, em 2012, com 970,440 de pontos.'
            'Superando o norte-americano Pat Laffaye, com 896,980 pontos. Além disso, ',
            'o Frogger original, ou conversões similares da versão arcade, foi lançado ',
            'para mais de 10 plataformas, desde as mais conhecidas às mais raras. ',
            'Consoles como o Playstation ganharam uma versão 3D, que retomava ',
            'o jogo original e incluía novos níveis para controlar o sapinho. ',
            'No Super NES, Frogger foi um dos últimos jogos a ser lançados. ',
            'Entre os consoles atuais, somente o Xbox 360 disponibiliza-o para baixar.'.
        ].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"},
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
            {'name': 'picture2.png', 'caption': "description2"},
            {'name': 'picture3.png', 'caption': "description3"}
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=l9fO-YuWPSk', 'caption': "Frogger arcade game", 'type': "youtube"} // type: youtube or vimeo
            'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=vEsq-PGRJ5I', 'caption': "Frogger Atari 2600", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'http://www.ojogos.com.br/jogo/frogger', 'caption': "Jogar frogger!"}
        ],
        'references': [
            {'url': 'reference_url1', 'caption': "description"},
            {'url': 'reference_url2', 'caption': "description"},
            {'url': 'reference_url3', 'caption': "description"}
        ]
}
<|endoftext|>


<commit_before>var request = require('./support/http'),
    should = require('should'),
    json = JSON.stringify,
    connection,
    app,
    User,
    mongoose = require('mongoose'),
    UserSchema = new mongoose.Schema({
        username: {type: String, required: true, unique: true, index: true},
        count: {type: Number},
        meta: {
            created: {
                type: Date
            }
        }
    });

function setup(connection) {
    var express = require('express'),
        rest = require('../index'),
        compat = require('../lib/compat');
    User = connection.model('User', UserSchema);
    app = express();
    app.use(compat.bodyParser());
    app.use('/rest', rest({mongoose: connection}).rest());

}
d = new Date();
function date(offset) {
    return new Date(d.getTime() + offset);
}

var score = 0;

var usernames = ['abc', 'def', 'acc', 'dff'];

function insert(done) {
    console.log('insert');
    var us = [].concat(usernames);
    var save = function (username) {
        var u = new User({
            username: username,
            count: score++,
            meta: {
                created: date(-10000 * score)
            }
        });
        console.log('saving ', u.username);
        u.save(doneSave);
    };

    var doneSave = function (err) {
        if (err) {
            console.log('error', err);
        }
        if (us.length == 0) {
            console.log('done');
            done();
        } else {
            save(us.shift());
        }

    };
    save(us.shift());
}
describe('filtering conditions', function () {
    before(function onBefore(done) {
        console.log('filter-mocha');
        connection = mongoose.createConnection();
        setup(connection);
        connection.on('connected', function () {
            connection.db.dropDatabase(function () {
                insert(function () {
                    done();
                });
            });
        });
        connection.open('mongodb://localhost/filter-mocha');
    });

    after(function onAfter(done) {
        connection.on('disconnected', function () {
            done();
        });
        connection.close();
    });

    it('should filter by username string', function (done) {
        request(app)
            .get('/rest/User?filter[username]=abc')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;
                payload[0].should.have.property('username', 'abc');
                done();

            })
    });
    it('should fiter greater than number', function (done) {
        request(app)
            .get('/rest/User?filter[count]=>1')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;

                done();

            })
    });
    it('should filter less than number', function (done) {
        request(app)
            .get('/rest/User?filter[count]=<1')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;

                done();

            })
    });

    it('should filter less than date', function (done) {
        request(app)
            .get("/rest/User?filter[meta][created]=<" + (date(-10000 * 3).toJSON()))
            .expect(200).end(function (err, res) {
                if (err) {
                    console.log('Error', res, err);
                    done(err);
                }
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;
                payload.should.have.length(2);

                done();

            })
    });

});<commit_msg>updated timeout<commit_after>var request = require('./support/http'),
    should = require('should'),
    json = JSON.stringify,
    connection,
    app,
    User,
    mongoose = require('mongoose'),
    UserSchema = new mongoose.Schema({
        username: {type: String, required: true, unique: true, index: true},
        count: {type: Number},
        meta: {
            created: {
                type: Date
            }
        }
    });

function setup(connection) {
    var express = require('express'),
        rest = require('../index'),
        compat = require('../lib/compat');
    User = connection.model('User', UserSchema);
    app = express();
    app.use(compat.bodyParser());
    app.use('/rest', rest({mongoose: connection}).rest());

}
d = new Date();
function date(offset) {
    return new Date(d.getTime() + offset);
}

var score = 0;

var usernames = ['abc', 'def', 'acc', 'dff'];

function insert(done) {
    console.log('insert');
    var us = [].concat(usernames);
    var save = function (username) {
        var u = new User({
            username: username,
            count: score++,
            meta: {
                created: date(-10000 * score)
            }
        });
        console.log('saving ', u.username);
        u.save(doneSave);
    };

    var doneSave = function (err) {
        if (err) {
            console.log('error', err);
        }
        if (us.length == 0) {
            console.log('done');
            done();
        } else {
            save(us.shift());
        }

    };
    save(us.shift());
}
describe('filtering conditions', function () {
    before(function onBefore(done) {
        this.timeout(5000);
        console.log('filter-mocha');
        connection = mongoose.createConnection();
        setup(connection);
        connection.on('connected', function () {
            connection.db.dropDatabase(function () {
                insert(function () {
                    done();
                });
            });
        });
        connection.open('mongodb://localhost/filter-mocha');
    });

    after(function onAfter(done) {
        connection.on('disconnected', function () {
            done();
        });
        connection.close();
    });

    it('should filter by username string', function (done) {
        request(app)
            .get('/rest/User?filter[username]=abc')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;
                payload[0].should.have.property('username', 'abc');
                done();

            })
    });
    it('should fiter greater than number', function (done) {
        request(app)
            .get('/rest/User?filter[count]=>1')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;

                done();

            })
    });
    it('should filter less than number', function (done) {
        request(app)
            .get('/rest/User?filter[count]=<1')
            .expect(200).end(function (err, res) {
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;

                done();

            })
    });

    it('should filter less than date', function (done) {
        request(app)
            .get("/rest/User?filter[meta][created]=<" + (date(-10000 * 3).toJSON()))
            .expect(200).end(function (err, res) {
                if (err) {
                    console.log('Error', res, err);
                    done(err);
                }
                res.body.should.have.property('status', 0);
                var payload = res.body.should.have.property('payload').obj;
                payload.should.have.length(2);

                done();

            })
    });

});<|endoftext|>


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

// Stop exec calls from happening
// TODO: This will become mock
var shell = require('shelljs');
shell.exec = function () {};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS
// TODO: Strongly consider running tests within a Vagrant to prevent publication since nothing is configured

var tmp = shell.tempdir();
var fixtureDir = path.join(tmp, 'foundry_test');
before(function deleteFixtureDir (done) {
  wrench.rmdirRecursive(fixtureDir, done);
});
before(function createFixtureDir (done) {
  wrench.mkdirRecursive(fixtureDir, done);
});
before(function goToFixtureDir (done) {
  process.chdir(fixtureDir);
});

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

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

  // });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder (done) {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirRecursive(this.gitDir, done);
    });
    before(function initializeGitFolder (done) {
      var that = this;
      process.chdir(this.gitDir);
      console.log(this.gitDir);
      // childProcess.exec('git init', function (err, stdout, stderr) {
      //   that.stdout = stdout;
        done(err);
      // });
    });

    it('adds a git tag', function () {

    });
  });
});
<commit_msg>Fixing up test parts<commit_after>// Load in dependencies
var childProcess = require('child_process');
var path = require('path');
var wrench = require('wrench');
var foundry = require('../bin/foundry');

// Stop exec calls from happening
// TODO: This will become mock
var shell = require('shelljs');
shell.exec = function () {};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS
// TODO: Strongly consider running tests within a Vagrant to prevent publication since nothing is configured

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

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

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

  // });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder () {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirSyncRecursive(this.gitDir);
    });
    before(function initializeGitFolder (done) {
      var that = this;
      process.chdir(this.gitDir);
      console.log(this.gitDir);
      // childProcess.exec('git init', function (err, stdout, stderr) {
      //   that.stdout = stdout;
        done(err);
      // });
    });

    it('adds a git tag', function () {

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


<commit_before>'use strict';

const { Server } = require('http');
const handler = require('serve-handler');

const server = new Server((request, response) => {
    handler(request, response, {
        public: 'dist',
        directoryListing: false,
    });
});

module.exports = {
    before: done => {
        server.listen(process.env.npm_package_config_port, done);
    },
    after: done => {
        server.close(done);
    },
};
<commit_msg>Silence max listeners warnings<commit_after>'use strict';

const { Server } = require('http');
const handler = require('serve-handler');

const server = new Server((request, response) => {
    handler(request, response, {
        public: 'dist',
        directoryListing: false,
    });
});

module.exports = {
    before: done => {
        process.setMaxListeners(0);
        server.listen(process.env.npm_package_config_port, done);
    },
    after: done => {
        server.close(done);
    },
};
<|endoftext|>


<commit_before>pjax_config_page("limitsws", function(){
    return {
        onLoad: function() {
            if (!$.cookie('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            Content.populate();
            document.getElementById('client_message').setAttribute('style', 'display:none');

            BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);

                    if (/^VRT/.test(TUser.get().loginid)) {
                        LimitsWS.limitsError();
                    } else if (response && !/^VRT/.test(TUser.get().loginid)) {
                        var type = response.msg_type;
                        var error = response.error;

                        if (type === 'get_limits' && !error){
                            LimitsWS.limitsHandler(response);
                        } else if (error) {
                            LimitsWS.limitsError();
                        }
                    }
                }
            });

            BinarySocket.send({get_limits: 1});
        },
        onUnload: function(){
            LimitsWS.clean();
        }
    };
});
<commit_msg>limits<commit_after>pjax_config_page("limitsws", function(){
    return {
        onLoad: function() {
            if (!$.cookie('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            Content.populate();
            document.getElementById('client_message').setAttribute('style', 'display:none');

            BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);

                    if (!page.client.is_real) {
                        LimitsWS.limitsError();
                    } else if (response) {
                        var type = response.msg_type;
                        var error = response.error;

                        if (type === 'get_limits' && !error){
                            LimitsWS.limitsHandler(response);
                        } else if (error) {
                            LimitsWS.limitsError();
                        }
                    }
                }
            });

            BinarySocket.send({get_limits: 1});
        },
        onUnload: function(){
            LimitsWS.clean();
        }
    };
});
<|endoftext|>


<commit_before>import { remote, shell } from 'electron';
import jetpack from 'fs-jetpack';
import url from 'url';

let fh = {};

fh.jetpack = jetpack;
fh.appPath = remote.app.getAppPath();
fh.userPath = remote.app.getPath('userData');
fh.userDir = jetpack.cwd(fh.userPath);
fh.appDir = jetpack.cwd(fh.appPath);

// log app directory for reference
console.log('App directory: ' + fh.appPath);

// helper function for loading json file
fh.loadJsonFile = function(filename, defaultValue = []) {
    if (fh.jetpack.exists(filename) === 'file') {
        return fh.jetpack.read(filename, 'json');
    } else {
        return defaultValue;
    }
};

fh.loadTextFile = function(filename, defaultValue = '') {
    if (fh.jetpack.exists(filename) === 'file') {
        return fh.jetpack.read(filename);
    } else {
        return defaultValue;
    }
};

fh.loadResource = function(filename, defaultValue = []) {
    if (fh.appDir.exists(filename) === 'file') {
        return fh.appDir.read(filename, 'json');
    } else {
        return defaultValue;
    }
};

// helper function for saving json files
fh.saveJsonFile = function(filename, value, minify = false) {
    fh.jetpack.write(filename, minify ? JSON.stringify(value) : value);
};

fh.saveTextFile = function(filename, value) {
    fh.jetpack.write(filename, value);
};

fh.open = function(filename) {
    if (fh.jetpack.exists(filename)) {
        shell.openItem(fh.jetpack.cwd() + '\\' + filename);
    }
};

fh.getFileUrl = function(path) {
    return url.format({
        pathname: jetpack.path(path).replace(/\\/g, '/'),
        protocol: 'file:',
        slashes: true
    })
};

fh.getDateModified = function(filename) {
    return fh.jetpack.inspect(filename, {times: true}).modifyTime;
};

// helper function for selecting a directory
fh.selectDirectory = function(title, defaultPath) {
    let selection = remote.dialog.showOpenDialog({
        title: title,
        defaultPath: defaultPath,
        properties: ['openDirectory']
    });
    if (!selection) return defaultPath;
    return selection[0];
};

export default fh;
<commit_msg>added more helpers to fileHelpers<commit_after>import { remote, shell } from 'electron';
import jetpack from 'fs-jetpack';
import extract from 'extract-zip';
import url from 'url';

let fh = {};

fh.jetpack = jetpack;
fh.appPath = remote.app.getAppPath();
fh.userPath = remote.app.getPath('userData');
fh.userDir = jetpack.cwd(fh.userPath);
fh.appDir = jetpack.cwd(fh.appPath);

// log app directory for reference
console.log('App directory: ' + fh.appPath);

// helper function for loading json file
fh.loadJsonFile = function(filename, defaultValue = []) {
    if (fh.jetpack.exists(filename) === 'file') {
        return fh.jetpack.read(filename, 'json');
    } else {
        return defaultValue;
    }
};

fh.loadTextFile = function(filename, defaultValue = '') {
    if (fh.jetpack.exists(filename) === 'file') {
        return fh.jetpack.read(filename);
    } else {
        return defaultValue;
    }
};

fh.loadResource = function(filename, defaultValue = []) {
    if (fh.appDir.exists(filename) === 'file') {
        return fh.appDir.read(filename, 'json');
    } else {
        return defaultValue;
    }
};

// helper function for saving json files
fh.saveJsonFile = function(filename, value, minify = false) {
    fh.jetpack.write(filename, minify ? JSON.stringify(value) : value);
};

fh.saveTextFile = function(filename, value) {
    fh.jetpack.write(filename, value);
};

fh.open = function(filename) {
    if (fh.jetpack.exists(filename)) {
        shell.openItem(fh.jetpack.cwd() + '\\' + filename);
    }
};

fh.getFileUrl = function(path) {
    return url.format({
        pathname: jetpack.path(path).replace(/\\/g, '/'),
        protocol: 'file:',
        slashes: true
    })
};

fh.extractArchive = function(filePath, destDir, empty = false) {
    fh.jetpack.dir(destDir, { empty: empty });
    extract(filePath, { dir: destDir }, (err) => { throw err });
};

fh.getFileExt = function(filePath) {
    let match = filePath.match(/.*\.(.*)/);
    return match[1];
};

fh.getFileName = function(filePath) {
    let match = filePath.match(/.*\\(.*)/);
    return match[1];
};

fh.getDateModified = function(filename) {
    return fh.jetpack.inspect(filename, {times: true}).modifyTime;
};

fh.getDirectories = function(path) {
    return fh.jetpack.find(path, {
        matching: '*',
        files: false,
        directories: true
    });
};

// helper function for selecting a directory
fh.selectDirectory = function(title, defaultPath) {
    let selection = remote.dialog.showOpenDialog({
        title: title,
        defaultPath: defaultPath,
        properties: ['openDirectory']
    });
    if (!selection) return defaultPath;
    return selection[0];
};

// helper function for selecting a theme
fh.selectFile = function(title, defaultPath, filters = []) {
    let selection = remote.dialog.showOpenDialog({
        title: title,
        defaultPath: defaultPath,
        filter: filters,
        properties: ['openFile']
    });
    return selection && selection[0];
};

export default fh;
<|endoftext|>