<commit_before>'use strict'

const t = require('tap')
const test = t.test
const FindMyWay = require('../')

test('the router is an object with methods', t => {
  t.plan(3)

  const findMyWay = FindMyWay()

  t.is(typeof findMyWay.on, 'function')
  t.is(typeof findMyWay.lookup, 'function')
  t.is(typeof findMyWay.find, 'function')
})

test('register a route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('register a route with multiple methods', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on(['GET', 'POST'], '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'POST', url: '/test' }, null)
})

test('default route', t => {
  t.plan(1)

  const findMyWay = FindMyWay({
    defaultRoute: () => {
      t.ok('inside the default route')
    }
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('parametric route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('multiple parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/other-test/:id', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/other-test/world' }, null)
})

test('multiple parametric route with the same prefix', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/test/:id/world', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/world/world' }, null)
})

test('nested parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('nested parametric route with same prefix', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('long route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/def/ghi/lmn/opq/rst/uvz', (req, res, params) => {
    t.ok('inside long path')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route with common prefix', t => {
  t.plan(9)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc/:def', (req, res, params) => {
    t.is(params.def, 'def')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('common prefix', t => {
  t.plan(4)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/f', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ff', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ffa', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ffb', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.lookup({ method: 'GET', url: '/f' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ff' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ffa' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ffb' }, null)
})

test('wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/*', (req, res, params) => {
    t.is(params['*'], 'hello')
  })

  findMyWay.lookup(
    { method: 'GET', url: '/test/hello' },
    null
  )
})

test('catch all wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '*', (req, res, params) => {
    t.is(params['*'], '/test/hello')
  })

  findMyWay.lookup(
    { method: 'GET', url: '/test/hello' },
    null
  )
})

test('find should return the route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    { handler: fn, params: {}, store: null }
  )
})

test('find should return the route with params', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello'),
    { handler: fn, params: { id: 'hello' }, store: null }
  )
})

test('find should return a null handler if the route does not exist', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    null
  )
})

test('should decode the uri - parametric', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { id: 'he/llo' }, store: null }
  )
})

test('should decode the uri - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { '*': 'he/llo' }, store: null }
  )
})

test('safe decodeURIComponent', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})

test('safe decodeURIComponent - nested route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/hello/world/:id/blah', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello/world/hel%"Flo/blah'),
    null
  )
})

test('safe decodeURIComponent - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})

test('static routes should be inserted before parametric / 1', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/hello', () => {
    t.pass('inside correct handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 2', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.pass('inside correct handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 3', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.ok('inside correct handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 4', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/:id', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.fail('wrong handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/id' }, null)
  findMyWay.lookup({ method: 'GET', url: '/id' }, null)
})

test('Static parametric with shared part of the path', t => {
  t.plan(2)

  const findMyWay = FindMyWay({
    defaultRoute: (req, res) => {
      t.is(req.url, '/example/shared/nested/oops')
    }
  })

  findMyWay.on('GET', '/example/shared/nested/test', (req, res, params) => {
    t.fail('We should not be here')
  })

  findMyWay.on('GET', '/example/:param/nested/test', (req, res, params) => {
    t.is(params.param, 'other')
  })

  findMyWay.lookup({ method: 'GET', url: '/example/shared/nested/oops' }, null)
  findMyWay.lookup({ method: 'GET', url: '/example/other/nested/test' }, null)
})
<commit_msg>Updated test<commit_after>'use strict'

const t = require('tap')
const test = t.test
const FindMyWay = require('../')

test('the router is an object with methods', t => {
  t.plan(3)

  const findMyWay = FindMyWay()

  t.is(typeof findMyWay.on, 'function')
  t.is(typeof findMyWay.lookup, 'function')
  t.is(typeof findMyWay.find, 'function')
})

test('register a route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('register a route with multiple methods', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on(['GET', 'POST'], '/test', () => {
    t.ok('inside the handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'POST', url: '/test' }, null)
})

test('default route', t => {
  t.plan(1)

  const findMyWay = FindMyWay({
    defaultRoute: () => {
      t.ok('inside the default route')
    }
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
})

test('parametric route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('multiple parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/other-test/:id', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/other-test/world' }, null)
})

test('multiple parametric route with the same prefix', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('GET', '/test/:id/world', (req, res, params) => {
    t.is(params.id, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/world/world' }, null)
})

test('nested parametric route', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('nested parametric route with same prefix', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/test/:hello/test/:world', (req, res, params) => {
    t.is(params.hello, 'hello')
    t.is(params.world, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello/test/world' }, null)
})

test('long route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/def/ghi/lmn/opq/rst/uvz', (req, res, params) => {
    t.ok('inside long path')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route', t => {
  t.plan(3)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('long parametric route with common prefix', t => {
  t.plan(9)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc', (req, res, params) => {
    throw new Error('I shoul not be here')
  })

  findMyWay.on('GET', '/abc/:def', (req, res, params) => {
    t.is(params.def, 'def')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.on('GET', '/abc/:def/ghi/:lmn/opq/:rst/uvz', (req, res, params) => {
    t.is(params.def, 'def')
    t.is(params.lmn, 'lmn')
    t.is(params.rst, 'rst')
  })

  findMyWay.lookup({ method: 'GET', url: '/abc/def' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst' }, null)
  findMyWay.lookup({ method: 'GET', url: '/abc/def/ghi/lmn/opq/rst/uvz' }, null)
})

test('common prefix', t => {
  t.plan(4)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/f', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ff', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ffa', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.on('GET', '/ffb', (req, res, params) => {
    t.ok('inside route')
  })

  findMyWay.lookup({ method: 'GET', url: '/f' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ff' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ffa' }, null)
  findMyWay.lookup({ method: 'GET', url: '/ffb' }, null)
})

test('wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/*', (req, res, params) => {
    t.is(params['*'], 'hello')
  })

  findMyWay.lookup(
    { method: 'GET', url: '/test/hello' },
    null
  )
})

test('catch all wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '*', (req, res, params) => {
    t.is(params['*'], '/test/hello')
  })

  findMyWay.lookup(
    { method: 'GET', url: '/test/hello' },
    null
  )
})

test('find should return the route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    { handler: fn, params: {}, store: null }
  )
})

test('find should return the route with params', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello'),
    { handler: fn, params: { id: 'hello' }, store: null }
  )
})

test('find should return a null handler if the route does not exist', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  t.deepEqual(
    findMyWay.find('GET', '/test'),
    null
  )
})

test('should decode the uri - parametric', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { id: 'he/llo' }, store: null }
  )
})

test('should decode the uri - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/he%2Fllo'),
    { handler: fn, params: { '*': 'he/llo' }, store: null }
  )
})

test('safe decodeURIComponent', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/:id', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})

test('safe decodeURIComponent - nested route', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/hello/world/:id/blah', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hello/world/hel%"Flo/blah'),
    null
  )
})

test('safe decodeURIComponent - wildcard', t => {
  t.plan(1)
  const findMyWay = FindMyWay()
  const fn = () => {}

  findMyWay.on('GET', '/test/*', fn)

  t.deepEqual(
    findMyWay.find('GET', '/test/hel%"Flo'),
    null
  )
})

test('static routes should be inserted before parametric / 1', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/hello', () => {
    t.pass('inside correct handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 2', t => {
  t.plan(1)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.pass('inside correct handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 3', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.ok('inside correct handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test' }, null)
  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
})

test('static routes should be inserted before parametric / 4', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/:id', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test', () => {
    t.fail('wrong handler')
  })

  findMyWay.on('GET', '/test/:id', () => {
    t.ok('inside correct handler')
  })

  findMyWay.on('GET', '/test/hello', () => {
    t.fail('wrong handler')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/id' }, null)
  findMyWay.lookup({ method: 'GET', url: '/id' }, null)
})

test('Static parametric with shared part of the path', t => {
  t.plan(2)

  const findMyWay = FindMyWay({
    defaultRoute: (req, res) => {
      t.is(req.url, '/example/shared/nested/oops')
    }
  })

  findMyWay.on('GET', '/example/shared/nested/test', (req, res, params) => {
    t.fail('We should not be here')
  })

  findMyWay.on('GET', '/example/:param/nested/test', (req, res, params) => {
    t.is(params.param, 'other')
  })

  findMyWay.lookup({ method: 'GET', url: '/example/shared/nested/oops' }, null)
  findMyWay.lookup({ method: 'GET', url: '/example/other/nested/test' }, null)
})

test('parametric route with different method', t => {
  t.plan(2)
  const findMyWay = FindMyWay()

  findMyWay.on('GET', '/test/:id', (req, res, params) => {
    t.is(params.id, 'hello')
  })

  findMyWay.on('POST', '/test/:other', (req, res, params) => {
    t.is(params.other, 'world')
  })

  findMyWay.lookup({ method: 'GET', url: '/test/hello' }, null)
  findMyWay.lookup({ method: 'POST', url: '/test/world' }, null)
})
<|endoftext|>


<commit_before>/* eslint-env es6, node */

'use strict';

// People who have this installed as a module (pretty much everyone who is
// reading this) should change this line to:
// const ndt7 = require('@m-lab/ndt7');
const ndt7 = require('../src/ndt7.js');

ndt7.test(
    {
      userAcceptedDataPolicy: true,
    },
    {
      serverChosen: function(server) {
        console.log('Testing to:', {
          machine: server.machine,
          locations: server.location,
        });
      },
      downloadComplete: function(data) {
        // (bytes/second) * (bits/byte) / (megabits/bit) = Mbps
        const serverBw = data.LastServerMeasurement.BBRInfo.BW * 8 / 1000000;
        const clientGoodput = data.LastClientMeasurement.MeanClientMbps;
        console.log(
            `Download test is complete:
    Instantaneous server bottleneck bandwidth estimate: ${serverBw} Mbps
    Mean client goodput: ${clientGoodput} Mbps`);
      },
      uploadComplete: function(data) {
        // TODO: used actual upload duration for rate calculation.
        // bytes * (bits/byte() * (megabits/bit) * (1/seconds) = Mbps
        const serverBw =
            data.LastServerMeasurement.TCPInfo.BytesReceived * 8 / 1000000 / 10;
        const clientGoodput = data.LastClientMeasurement.MeanClientMbps;
        console.log(
            `Upload test is complete:
    Mean server throughput: ${serverBw} Mbps
    Mean client goodput: ${clientGoodput} Mbps`);
      },
      error: function(err) {
        console.log("Error while running the test:", err.message);
      },
    },
).then((exitcode) => {
  process.exit(exitcode);
});
<commit_msg>Use single quotes consistently.<commit_after>/* eslint-env es6, node */

'use strict';

// People who have this installed as a module (pretty much everyone who is
// reading this) should change this line to:
// const ndt7 = require('@m-lab/ndt7');
const ndt7 = require('../src/ndt7.js');

ndt7.test(
    {
      userAcceptedDataPolicy: true,
    },
    {
      serverChosen: function(server) {
        console.log('Testing to:', {
          machine: server.machine,
          locations: server.location,
        });
      },
      downloadComplete: function(data) {
        // (bytes/second) * (bits/byte) / (megabits/bit) = Mbps
        const serverBw = data.LastServerMeasurement.BBRInfo.BW * 8 / 1000000;
        const clientGoodput = data.LastClientMeasurement.MeanClientMbps;
        console.log(
            `Download test is complete:
    Instantaneous server bottleneck bandwidth estimate: ${serverBw} Mbps
    Mean client goodput: ${clientGoodput} Mbps`);
      },
      uploadComplete: function(data) {
        // TODO: used actual upload duration for rate calculation.
        // bytes * (bits/byte() * (megabits/bit) * (1/seconds) = Mbps
        const serverBw =
            data.LastServerMeasurement.TCPInfo.BytesReceived * 8 / 1000000 / 10;
        const clientGoodput = data.LastClientMeasurement.MeanClientMbps;
        console.log(
            `Upload test is complete:
    Mean server throughput: ${serverBw} Mbps
    Mean client goodput: ${clientGoodput} Mbps`);
      },
      error: function(err) {
        console.log('Error while running the test:', err.message);
      },
    },
).then((exitcode) => {
  process.exit(exitcode);
});
<|endoftext|>


<commit_before>define(function (require) {
	var documentKeyboardHandler = require("utilities/documentKeyboardHandler");

	var keyboardShortcuts = function (eventBus) {
		documentKeyboardHandler(function (event, isDown, isRepeated) {
			// spacebar
			if (isDown && event.which === 32) {
				if (!isRepeated)
					eventBus.trigger("togglePlayback");

				return false;
			}

			// shift
			if (event.which === 16) {
				if (!isRepeated) {
					eventBus.trigger("setGridViewState", {
						state: isDown ? "play" : "addOrRemove"
					});
				}

				return false;
			}

			// number keys 1 to 9
			if (isDown && event.which >= 49 && event.which <= 57) {
				if (!isRepeated)
					eventBus.trigger("selectTrack", {
						trackIndex: event.which - 49
					});

				return false;
			}
		});
	};

	return keyboardShortcuts;
});
<commit_msg>Disable keyboard shortcut if target element is an input element.<commit_after>define(function (require) {
	var $ = require("jquery");
	var documentKeyboardHandler = require("utilities/documentKeyboardHandler");

	var keyboardShortcuts = function (eventBus) {
		documentKeyboardHandler(function (event, isDown, isRepeated) {
			// spacebar
			if (isDown && event.which === 32) {
				if (!isRepeated)
					eventBus.trigger("togglePlayback");

				return false;
			}

			// shift
			if (event.which === 16) {
				if (!isRepeated) {
					eventBus.trigger("setGridViewState", {
						state: isDown ? "play" : "addOrRemove"
					});
				}

				return false;
			}

			// number keys 1 to 9
			if (isDown && event.which >= 49 && event.which <= 57) {
				if ($(event.target).is("input"))
					return;

				if (!isRepeated)
					eventBus.trigger("selectTrack", {
						trackIndex: event.which - 49
					});

				return false;
			}
		});
	};

	return keyboardShortcuts;
});
<|endoftext|>


<commit_before>// Create the agent.
create_agent = function() {
    reqwest({
        url: "/node/" + worker_id.concat(":").concat(assignment_id),
        method: 'post',
        type: 'json',
        success: function (resp) {
            my_node_id = resp.node.id;
            get_info(my_node_id);
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            if (err_response.hasOwnProperty('html')) {
                $('body').html(err_response.html);
            } else {
                allow_exit();
                go_to_page('postquestionnaire');
            }
        }
    });
};

get_info = function(info_id) {
    reqwest({
        url: "/node/" + my_node_id + "/received_infos",
        method: 'get',
        type: 'json',
        success: function (resp) {
            story = resp.infos[0].contents;
            storyHTML = markdown.toHTML(story);
            $("#story").html(storyHTML);
            $("#stimulus").show();
            $("#response-form").hide();
            $("#finish-reading").show();
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            $('body').html(err_response.html);
        }
    });
};

finish_reading = function() {
    $("#stimulus").hide();
    $("#response-form").show();
    $("#submit-response").removeClass('disabled');
    $("#submit-response").html('Submit');
};

submit_response = function() {
    $("#submit-response").addClass('disabled');
    $("#submit-response").html('Sending...');

    response = $("#reproduction").val();

    $("#reproduction").val("");

    reqwest({
        url: "/info/" + my_node_id,
        method: 'post',
        data: {
            contents: response,
            info_type: "Info"
        },
        success: function (resp) {
            create_agent();
        }
    });
};
<commit_msg>bartlett: use participant id, not unique_id<commit_after>// Create the agent.
create_agent = function() {
    reqwest({
        url: "/node/" + participant_id,
        method: 'post',
        type: 'json',
        success: function (resp) {
            my_node_id = resp.node.id;
            get_info(my_node_id);
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            if (err_response.hasOwnProperty('html')) {
                $('body').html(err_response.html);
            } else {
                allow_exit();
                go_to_page('postquestionnaire');
            }
        }
    });
};

get_info = function(info_id) {
    reqwest({
        url: "/node/" + my_node_id + "/received_infos",
        method: 'get',
        type: 'json',
        success: function (resp) {
            story = resp.infos[0].contents;
            storyHTML = markdown.toHTML(story);
            $("#story").html(storyHTML);
            $("#stimulus").show();
            $("#response-form").hide();
            $("#finish-reading").show();
        },
        error: function (err) {
            console.log(err);
            err_response = JSON.parse(err.response);
            $('body').html(err_response.html);
        }
    });
};

finish_reading = function() {
    $("#stimulus").hide();
    $("#response-form").show();
    $("#submit-response").removeClass('disabled');
    $("#submit-response").html('Submit');
};

submit_response = function() {
    $("#submit-response").addClass('disabled');
    $("#submit-response").html('Sending...');

    response = $("#reproduction").val();

    $("#reproduction").val("");

    reqwest({
        url: "/info/" + my_node_id,
        method: 'post',
        data: {
            contents: response,
            info_type: "Info"
        },
        success: function (resp) {
            create_agent();
        }
    });
};
<|endoftext|>


<commit_before>var _       = require( 'lodash' );
var should  = require( 'should' );
var sinon   = require( 'sinon' );
var pequire = require( 'proxyquire' );
var tutil   = require( './lib/test-util' );

var HAPPY_PROXY_DEPS = {
    path:         { dirname:        _.noop },
    './hub-util': { isValidHubFile: function (){ return true } }
};

var getAddSubtask = function ( proxyDeps ) {
    return pequire( '../lib/add-subtask', _.assign( {}, HAPPY_PROXY_DEPS, proxyDeps ) );
};

describe( 'add-subtask', function () {

    it( 'errors if subfile is not a valid Gulp Hub file', function () {
        var addSubtask = getAddSubtask( {
            './hub-util': { isValidHubFile: function () { return false } }
        } );
        addSubtask.should.throw( '`subfile` must be a valid Gulp Hub file object.' );
    } );

    it( 'errors if the task registry is not a plain object', function () {
        var addSubtask = getAddSubtask();
        tutil.getTypeExamples( _.isPlainObject ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, type )
                .should.throw('`tasks` must be a plain object.');
        } );
    } );

    it( 'errors if name is not a string', function () {
        var addSubtask = getAddSubtask();
        tutil.getTypeExamples( _.isString ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, type )
                .should.throw('`name` must be a string.');
        } );
    } );

    it( 'errors if param1 is not an array or function', function () {
        var addSubtask = getAddSubtask();
        var excludeFunc = function ( el ) {
            return _.isArray( el ) || _.isFunction( el );
        };
        tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, 'string', type )
                .should.throw('`param1` must be an array or function.');
        } );
    } );

    it( 'errors if param2 is not a or function or undefined', function () {
        var addSubtask = getAddSubtask();
        var excludeFunc = function ( el ) {
            return _.isFunction( el ) || _.isUndefined( el );
        };
        tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, 'string', [], type )
                .should.throw('`param2` must be a function or undefined.');
        } );
    } );

    it( 'registers a master task with `name` if it doesn\'t already exist', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );

        var taskObj = testTasks[ 'task-name' ];
        _.isPlainObject( taskObj ).should.be.true;
        taskObj.name = 'task-name';
        _.isArray( taskObj.subtasks ).should.be.true;
    } );

    it( 'registers the subfile\'s tasks prefixed with its unique name under the master task name', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );
        testTasks[ 'task-name' ].subtasks[ 0 ].name.should.eql( 'unique-name-task-name' );
    } );

    it( 'prefixes the subfile\'s task dependencies with its unique name', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask(
            { uniqueName: 'subfile-unique-name' }, testTasks, 'task-name',
            [ 'task-dep-1', 'task-dep-2' ]
        );
        var subtaskDeps = testTasks[ 'task-name' ].subtasks[ 0 ].param1;
        subtaskDeps[ 0 ].should.eql( 'subfile-unique-name-task-dep-1' );
        subtaskDeps[ 1 ].should.eql( 'subfile-unique-name-task-dep-2' );
    } );

    it( 'wraps the subtask\'s callbacks in a function that corrects the working directory', function () {
        var testTasks = {};
        var callbackSpy = sinon.spy();
        var dirnameSpy = sinon.spy( function () { return '.' } );

        var addSubtask = getAddSubtask( { path: { dirname: dirnameSpy } } );
        addSubtask(
            { uniqueName: 'subfile-unique-name', absolutePath: '.' },
            testTasks, 'task-name', callbackSpy
        );
        testTasks[ 'task-name' ].subtasks[ 0 ].param1();

        dirnameSpy.calledOnce.should.be.true;
        dirnameSpy.calledWith( '.' ).should.be.true;
        callbackSpy.calledOnce.should.be.true;

        dirnameSpy.reset();
        callbackSpy.reset();

        addSubtask(
            { uniqueName: 'subfile-unique-name-2', absolutePath: '.' },
            testTasks, 'task-name-2', [], callbackSpy
        );
        testTasks[ 'task-name-2' ].subtasks[ 0 ].param2();

        dirnameSpy.calledOnce.should.be.true;
        dirnameSpy.calledWith( '.' ).should.be.true;
        callbackSpy.calledOnce.should.be.true;
    } );
} );
<commit_msg>Bring add-subtask test branch coverage to 100%<commit_after>var _       = require( 'lodash' );
var should  = require( 'should' );
var sinon   = require( 'sinon' );
var pequire = require( 'proxyquire' );
var tutil   = require( './lib/test-util' );

var HAPPY_PROXY_DEPS = {
    path:         { dirname:        _.noop },
    './hub-util': { isValidHubFile: function (){ return true } }
};

var getAddSubtask = function ( proxyDeps ) {
    return pequire( '../lib/add-subtask', _.assign( {}, HAPPY_PROXY_DEPS, proxyDeps ) );
};

describe( 'add-subtask', function () {

    it( 'errors if subfile is not a valid Gulp Hub file', function () {
        var addSubtask = getAddSubtask( {
            './hub-util': { isValidHubFile: function () { return false } }
        } );
        addSubtask.should.throw( '`subfile` must be a valid Gulp Hub file object.' );
    } );

    it( 'errors if the task registry is not a plain object', function () {
        var addSubtask = getAddSubtask();
        tutil.getTypeExamples( _.isPlainObject ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, type )
                .should.throw('`tasks` must be a plain object.');
        } );
    } );

    it( 'errors if name is not a string', function () {
        var addSubtask = getAddSubtask();
        tutil.getTypeExamples( _.isString ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, type )
                .should.throw('`name` must be a string.');
        } );
    } );

    it( 'errors if param1 is not an array or function', function () {
        var addSubtask = getAddSubtask();
        var excludeFunc = function ( el ) {
            return _.isArray( el ) || _.isFunction( el );
        };
        tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, 'string', type )
                .should.throw('`param1` must be an array or function.');
        } );
    } );

    it( 'errors if param2 is not a or function or undefined', function () {
        var addSubtask = getAddSubtask();
        var excludeFunc = function ( el ) {
            return _.isFunction( el ) || _.isUndefined( el );
        };
        tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
            addSubtask.bind( null, undefined, {}, 'string', [], type )
                .should.throw('`param2` must be a function or undefined.');
        } );
    } );

    it( 'registers a master task with `name` if it doesn\'t already exist', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );

        var taskObj = testTasks[ 'task-name' ];
        _.isPlainObject( taskObj ).should.be.true;
        taskObj.name = 'task-name';
        _.isArray( taskObj.subtasks ).should.be.true;
    } );

    it( 'skips task registry record initialization if `name` already exists', function () {
        var TASK_NAME = 'task-name';
        var testTasks = {};
        testTasks[ TASK_NAME ] = {
            name: TASK_NAME,
            subtasks: []
        };
        var addSubtask = getAddSubtask();
        addSubtask( { uniqueName: 'unique-name' }, testTasks, TASK_NAME, [] );

        var taskObj = testTasks[ TASK_NAME ];
        _.isPlainObject( taskObj ).should.be.true;
        taskObj.name = TASK_NAME;
        _.isArray( taskObj.subtasks ).should.be.true;
    } );

    it( 'registers the subfile\'s tasks prefixed with its unique name under the master task name', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );
        testTasks[ 'task-name' ].subtasks[ 0 ].name.should.eql( 'unique-name-task-name' );
    } );

    it( 'prefixes the subfile\'s task dependencies with its unique name', function () {
        var testTasks = {};
        var addSubtask = getAddSubtask();
        addSubtask(
            { uniqueName: 'subfile-unique-name' }, testTasks, 'task-name',
            [ 'task-dep-1', 'task-dep-2' ]
        );
        var subtaskDeps = testTasks[ 'task-name' ].subtasks[ 0 ].param1;
        subtaskDeps[ 0 ].should.eql( 'subfile-unique-name-task-dep-1' );
        subtaskDeps[ 1 ].should.eql( 'subfile-unique-name-task-dep-2' );
    } );

    it( 'wraps the subtask\'s callbacks in a function that corrects the working directory', function () {
        var testTasks = {};
        var callbackSpy = sinon.spy();
        var dirnameSpy = sinon.spy( function () { return '.' } );

        var addSubtask = getAddSubtask( { path: { dirname: dirnameSpy } } );
        addSubtask(
            { uniqueName: 'subfile-unique-name', absolutePath: '.' },
            testTasks, 'task-name', callbackSpy
        );
        testTasks[ 'task-name' ].subtasks[ 0 ].param1();

        dirnameSpy.calledOnce.should.be.true;
        dirnameSpy.calledWith( '.' ).should.be.true;
        callbackSpy.calledOnce.should.be.true;

        dirnameSpy.reset();
        callbackSpy.reset();

        addSubtask(
            { uniqueName: 'subfile-unique-name-2', absolutePath: '.' },
            testTasks, 'task-name-2', [], callbackSpy
        );
        testTasks[ 'task-name-2' ].subtasks[ 0 ].param2();

        dirnameSpy.calledOnce.should.be.true;
        dirnameSpy.calledWith( '.' ).should.be.true;
        callbackSpy.calledOnce.should.be.true;
    } );
} );
<|endoftext|>


<commit_before>var editor;
var author_name;
var author_real_name;

function initialize_editor(name, real_name) {
    editor = new EpicEditor({
        clientSideStorage: false,
        textarea: "content",
        basePath: '/static/css/vendor/editor/',
        autogrow: true,
        theme: {
            base: '/themes/base/epiceditor.css',
            preview: '/themes/preview/github.css',
            editor: '/themes/editor/epic-light.css'
        },
    }).load();

    author_name = name;
    author_real_name = real_name;

    iframe = editor.getElement('previewerIframe');

    /* Have to dynamically stuff in the correct css in the iframe for the
     * editor */
    css = document.createElement('link');
    css.href = "/static/css/vendor/github.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    css = document.createElement('link');
    css.href = "/static/css/vendor/bootstrap.min.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    css = document.createElement('link');
    css.href = "/static/css/base.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    /* Inject header information as it would appear on a regular page since
     * this content is not directly in the editor box */
    editor.on('preview', add_article_header_data);
    editor.on('fullscreenenter', function() {
        /* Force top of document up so it aligns with top of the markdown text */
        var html = editor.getElement('previewerIframe').contentDocument.firstChild;
        html.setAttribute('style', html.getAttribute('style') + 'margin-top: -90px;');
    });
}

function add_article_header_data() {
    var preview_div = editor.getElement('previewerIframe').contentDocument.getElementById('epiceditor-preview');
    var title = document.getElementById('title').value;

    var header = document.createElement('div');
    header.className = 'header';

    var h1 = document.createElement('h1')
    h1.id = 'title';
    h1.className = 'tagline gradient-text';
    h1.textContent = title;
    header.appendChild(h1);

    var h4 = document.createElement('h4');
    h4.id = 'author';

    var small = document.createElement('small');
    small.textContent = 'written by ';

    var anchor = document.createElement('a');

    if (author_real_name != undefined && author_real_name != '') {
        anchor.textContent = author_real_name;
    } else if (author_name != undefined && author_name != '') {
        anchor.textContent = author_name;
    } else {
        anchor.textContent = 'you';
    }

    if (author_name != undefined && author_name != '') {
        anchor.href = '/user/' + author_name;
    }

    small.appendChild(anchor);
    h4.appendChild(small);
    header.appendChild(h4);

    var selected_stacks = document.getElementById('stacks').selectedOptions;
    var stacks = '';
    for (ii = 0; ii < selected_stacks.length; ii++) {
        if (selected_stacks[ii].value != '') {
            stacks += selected_stacks[ii].value + ',';
        }
    }

    if (stacks.length) {
        if (stacks[stacks.length - 1] == ',') {
            stacks = stacks.slice(0, -1);
        }
        var h5 = document.createElement('h5');
        h5.id = 'related';
        var small = document.createElement('small');
        small.textContent = 'Related to ' + stacks;

        h5.appendChild(small);
        header.appendChild(h5);
    }

    header.appendChild(document.createElement('hr'));
    preview_div.insertBefore(header, preview_div.firstChild);
}

function save(sha, path, secondary_repo) {
    var form = document.createElement("form");
    form.action = "/save/";
    form.method = "POST";

    var content = document.createElement("input");
    content.name = "content";
    content.value = editor.exportFile("", "json");
    form.appendChild(content.cloneNode());

    var sha_elem = document.createElement("input");
    sha_elem.name = "sha";
    sha_elem.value = sha;
    form.appendChild(sha_elem.cloneNode());

    var path_elem = document.createElement("input");
    path_elem.name = "path";
    path_elem.value = path;
    form.appendChild(path_elem.cloneNode());

    var title = document.getElementById("title");
    form.appendChild(title.cloneNode());

    var stacks_select = document.getElementById("stacks");
    var stacks = document.createElement("input");
    stacks.name = "stacks";
    stacks.value = stacks_select.value;
    form.appendChild(stacks.cloneNode());

    if (secondary_repo) {
        var secondary_repo_elem = document.createElement("input");
        secondary_repo_elem.name = "secondary_repo";
        secondary_repo_elem.value = 1;
        form.appendChild(secondary_repo_elem.cloneNode());
    }

    // To be sent, the form needs to be attached to the main document.
    form.style.display = "none";
    document.body.appendChild(form);

    form.submit();

    // But once the form is sent, it's useless to keep it.
    document.body.removeChild(form);
}
<commit_msg>New design does not have the static header so do not need this workaround<commit_after>var editor;
var author_name;
var author_real_name;

function initialize_editor(name, real_name) {
    editor = new EpicEditor({
        clientSideStorage: false,
        textarea: "content",
        basePath: '/static/css/vendor/editor/',
        autogrow: true,
        theme: {
            base: '/themes/base/epiceditor.css',
            preview: '/themes/preview/github.css',
            editor: '/themes/editor/epic-light.css'
        },
    }).load();

    author_name = name;
    author_real_name = real_name;

    iframe = editor.getElement('previewerIframe');

    /* Have to dynamically stuff in the correct css in the iframe for the
     * editor */
    css = document.createElement('link');
    css.href = "/static/css/vendor/github.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    css = document.createElement('link');
    css.href = "/static/css/vendor/bootstrap.min.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    css = document.createElement('link');
    css.href = "/static/css/base.css";
    css.rel = "stylesheet";
    css.type = "text/css";
    iframe.contentDocument.head.appendChild(css);

    /* Inject header information as it would appear on a regular page since
     * this content is not directly in the editor box */
    editor.on('preview', add_article_header_data);
}

function add_article_header_data() {
    var preview_div = editor.getElement('previewerIframe').contentDocument.getElementById('epiceditor-preview');
    var title = document.getElementById('title').value;

    var header = document.createElement('div');
    header.className = 'header';

    var h1 = document.createElement('h1')
    h1.id = 'title';
    h1.className = 'tagline gradient-text';
    h1.textContent = title;
    header.appendChild(h1);

    var h4 = document.createElement('h4');
    h4.id = 'author';

    var small = document.createElement('small');
    small.textContent = 'written by ';

    var anchor = document.createElement('a');

    if (author_real_name != undefined && author_real_name != '') {
        anchor.textContent = author_real_name;
    } else if (author_name != undefined && author_name != '') {
        anchor.textContent = author_name;
    } else {
        anchor.textContent = 'you';
    }

    if (author_name != undefined && author_name != '') {
        anchor.href = '/user/' + author_name;
    }

    small.appendChild(anchor);
    h4.appendChild(small);
    header.appendChild(h4);

    var selected_stacks = document.getElementById('stacks').selectedOptions;
    var stacks = '';
    for (ii = 0; ii < selected_stacks.length; ii++) {
        if (selected_stacks[ii].value != '') {
            stacks += selected_stacks[ii].value + ',';
        }
    }

    if (stacks.length) {
        if (stacks[stacks.length - 1] == ',') {
            stacks = stacks.slice(0, -1);
        }
        var h5 = document.createElement('h5');
        h5.id = 'related';
        var small = document.createElement('small');
        small.textContent = 'Related to ' + stacks;

        h5.appendChild(small);
        header.appendChild(h5);
    }

    header.appendChild(document.createElement('hr'));
    preview_div.insertBefore(header, preview_div.firstChild);
}

function save(sha, path, secondary_repo) {
    var form = document.createElement("form");
    form.action = "/save/";
    form.method = "POST";

    var content = document.createElement("input");
    content.name = "content";
    content.value = editor.exportFile("", "json");
    form.appendChild(content.cloneNode());

    var sha_elem = document.createElement("input");
    sha_elem.name = "sha";
    sha_elem.value = sha;
    form.appendChild(sha_elem.cloneNode());

    var path_elem = document.createElement("input");
    path_elem.name = "path";
    path_elem.value = path;
    form.appendChild(path_elem.cloneNode());

    var title = document.getElementById("title");
    form.appendChild(title.cloneNode());

    var stacks_select = document.getElementById("stacks");
    var stacks = document.createElement("input");
    stacks.name = "stacks";
    stacks.value = stacks_select.value;
    form.appendChild(stacks.cloneNode());

    if (secondary_repo) {
        var secondary_repo_elem = document.createElement("input");
        secondary_repo_elem.name = "secondary_repo";
        secondary_repo_elem.value = 1;
        form.appendChild(secondary_repo_elem.cloneNode());
    }

    // To be sent, the form needs to be attached to the main document.
    form.style.display = "none";
    document.body.appendChild(form);

    form.submit();

    // But once the form is sent, it's useless to keep it.
    document.body.removeChild(form);
}
<|endoftext|>


<commit_before>angular.module('lngErrorService', [
    'lngX'
]).factory('$errorService', [
    '$rootScope', '$xService', '$sce',
    function ($rootScope, $ex, $sce) {
        $ex.log("[module.service.Error]");

        var parentClass = 'field';
        var parentErrorClass = 'error';
        var errorDetailClass = 'form-error';

        var Errors = {
            messages: function () {
                return this.fields;
            },
            setFieldFrameClass: function (frameClass) {
                parentClass = frameClass;
            },
            setFrameErrorClass: function (errorClass) {
                parentErrorClass = errorClass;
            },
            setErrorDetailClass: function (errorClass) {
                errorDetailClass = errorClass;
            },
            message: function (key) {
                var me = this;
                if (me.fields[key])
                    return me.fields[key].message;
            },
            reset: function (key) {
                var me = this;
                if (!key) {
                    $rootScope.Errors.fields = {};
                } else if (me.fields[key])
                    me.fields[key] = null;
            },
            getAllMessages: function () {
                var errorMessages = [];
                angular.forEach(this.fields, function (err, key) {
                    if (angular.isObject(err))
                        errorMessages.push("Error with " + key + ": " + err.message);
                });
                return errorMessages;
            },
            condensed: function (delimiter) {
                if (!delimiter)
                    delimiter = ' // ';
                return this.getAllMessages().join(delimiter);
            },
            fields: {},
            clear: function () {
                // @TODO clear all fields at the same time
                angular.forEach(Errors.fields, function (err, key) {
                    var elem = angular.element("[name='" + key + "']");
                    if (elem.length) {
                        // found element
                        $ex.log(elem, "Found error element");
                        var Parent = elem.parents('.' + parentClass);
                        // @TODO test Parent.length as way to verify element(s) exist
                        if (Parent.length) {
                            var ErrorDiv = Parent.find('.form-error');
                            if(ErrorDiv.length) {
                                console.log('Found error to reset -> ', ErrorDiv);
                                Parent.removeChild(ErrorDiv);
                            }
                        }
                    }
                });
                //$rootScope.Errors.reset();
            },
            update: function (errors) {
                if (angular.isObject(errors)) {
                    angular.extend(Errors.fields, errors);
                    // check for fields
                    angular.forEach(errors, function (err, key) {
                        var elem = angular.element("[name='" + key + "']");
                        if (elem.length) {
                            // found element
                            $ex.log(elem, "Found error element");
                            var Parent = elem.parents('.' + parentClass),
                                msgHtml = "
" + err.message + "
";
                            // @TODO test Parent.length as way to verify element(s) exist
                            if (Parent.length) {
                                Parent.addClass(parentErrorClass);
                                Parent.append(msgHtml);
                            } else
                                elem.parent().append(msgHtml);
                            // setup focus to clear error
                            elem.on('focus', function (ev) {
                                $ex.log(arguments, 'Focus captured in Error listener!');
                                var thisElem = angular.element(ev.target),
                                    Parent = thisElem.parents('.' + parentClass),
                                    errorViews = Parent.find('.form-error');
                                $ex.log(Parent, 'Element parent');
                                // remove error class from parent
                                Parent.removeClass(parentErrorClass);
                                $ex.log(errorViews, 'Error views for `' + key + '`');
                                angular.forEach(errorViews, function (div) {
                                    div.remove();
                                });
                            });
                        }
                    });
                    $rootScope.Errors = Errors;
                    $ex.log(errors, 'Errors reported!');
                }
            }
        };
        $rootScope.Errors = Errors;
        return Errors;
    }]);<commit_msg>Bug fixes (error div clearing)<commit_after>angular.module('lngErrorService', [
    'lngX'
]).factory('$errorService', [
    '$rootScope', '$xService', '$sce',
    function ($rootScope, $ex, $sce) {
        $ex.log("[module.service.Error]");

        var parentClass = 'field';
        var parentErrorClass = 'error';
        var errorDetailClass = 'form-error';

        var Errors = {
            messages: function () {
                return this.fields;
            },
            setFieldFrameClass: function (frameClass) {
                parentClass = frameClass;
            },
            setFrameErrorClass: function (errorClass) {
                parentErrorClass = errorClass;
            },
            setErrorDetailClass: function (errorClass) {
                errorDetailClass = errorClass;
            },
            message: function (key) {
                var me = this;
                if (me.fields[key])
                    return me.fields[key].message;
            },
            reset: function (key) {
                var me = this;
                if (!key) {
                    $rootScope.Errors.fields = {};
                } else if (me.fields[key])
                    me.fields[key] = null;
            },
            getAllMessages: function () {
                var errorMessages = [];
                angular.forEach(this.fields, function (err, key) {
                    if (angular.isObject(err))
                        errorMessages.push("Error with " + key + ": " + err.message);
                });
                return errorMessages;
            },
            condensed: function (delimiter) {
                if (!delimiter)
                    delimiter = ' // ';
                return this.getAllMessages().join(delimiter);
            },
            fields: {},
            clear: function () {
                // @TODO clear all fields at the same time
                angular.forEach(Errors.fields, function (err, key) {
                    var elem = angular.element("[name='" + key + "']");
                    if (elem.length) {
                        // found element
                        $ex.log(elem, "Found error element");
                        var Parent = elem.parents('.' + parentClass);
                        // @TODO test Parent.length as way to verify element(s) exist
                        if (Parent.length) {
                            var ErrorDiv = Parent.find('.form-error');
                            if(ErrorDiv.length) {
                                console.log('Found error to reset -> ', ErrorDiv);
                                //Parent.removeChild(ErrorDiv);
                                try {
                                    ErrorDiv.remove();
                                } catch(err) {
                                    console.error('Error div clearing failed');
                                }
                            }
                        }
                    }
                });
                //$rootScope.Errors.reset();
            },
            update: function (errors) {
                if (angular.isObject(errors)) {
                    angular.extend(Errors.fields, errors);
                    // check for fields
                    angular.forEach(errors, function (err, key) {
                        var elem = angular.element("[name='" + key + "']");
                        if (elem.length) {
                            // found element
                            $ex.log(elem, "Found error element");
                            var Parent = elem.parents('.' + parentClass),
                                msgHtml = "
" + err.message + "
";
                            // @TODO test Parent.length as way to verify element(s) exist
                            if (Parent.length) {
                                Parent.addClass(parentErrorClass);
                                Parent.append(msgHtml);
                            } else
                                elem.parent().append(msgHtml);
                            // setup focus to clear error
                            elem.on('focus', function (ev) {
                                $ex.log(arguments, 'Focus captured in Error listener!');
                                var thisElem = angular.element(ev.target),
                                    Parent = thisElem.parents('.' + parentClass),
                                    errorViews = Parent.find('.form-error');
                                $ex.log(Parent, 'Element parent');
                                // remove error class from parent
                                Parent.removeClass(parentErrorClass);
                                $ex.log(errorViews, 'Error views for `' + key + '`');
                                angular.forEach(errorViews, function (div) {
                                    div.remove();
                                });
                            });
                        }
                    });
                    $rootScope.Errors = Errors;
                    $ex.log(errors, 'Errors reported!');
                }
            }
        };
        $rootScope.Errors = Errors;
        return Errors;
    }]);<|endoftext|>


<commit_before>var cache = require('memory-cache');
var mongodb = require('../data/mongodb');
var indicator = require('../data/indicator');
var async = require('../lib/async');
var IndicatorSchema = indicator.Indicator;

exports.searchIndicator = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var indicatorResultJSON = {};
	if (query.query != null && query.query.length > 0) {
		var input = query.query;
		var keys = input.split(' ');
		var dimensions = [];
		var results = [];
		var callbackFuncArray = [];
		keys.forEach(function(key, index) {
			if (key.length > 0) {
				var callbackFunc = function(callback) {
					IndicatorSchema.find({
						indicator_text : {
							$regex : key,
							$options : 'i'
						}
					}, function(err, doc) {
						if (err)
							console.log('Exception: ' + err);
						doc.forEach(function(item, index) {
							var tempJson = {
								"uniqueName" : item.indicator_key,
								"text" : item.indicator_text + ' - ' + item.data_source,
								"dimensionStr" : genDimStr(item.dimension)
							};
							results.push(tempJson);
						});
						// match dimension value
						// if (doc.length === 0 && key.length > 2) {
						// var dims = cache.get('dimensions');
						// dims.forEach(function(d) {
						// if ((d.dimension_value +
						// '').toLowerCase().indexOf(key.toLowerCase()) > -1) {
						// dimensions.push(d);
						// }
						// });
						// }
						callback();
					});
				}
				callbackFuncArray.push(callbackFunc);
			}
		});
		async.parallel(callbackFuncArray, function() {
			console.log('matched results count: ' + results.length);
			// console.log('matched dimension value count: ' +
			// dimensions.length);
			// results.forEach(function(r) {
			// dimensions.forEach(function(d) {
			// if (r.dimensionStr.indexOf(d.dimension_key) > -1) {
			// r.text = d.dimension_value + ' - ' + r.text;
			// r.uniqueName = r.uniqueName + '///' + d.dimension_key + '///' +
			// d.dimension_value;
			// results.push(r);
			// }
			// });
			// });
			indicatorResultJSON = {
				"indicators" : results
			};
			// console.log(indicatorResultJSON);
			res.send(indicatorResultJSON);
		});
	} else {
		indicatorResultJSON = {
			"indicators" : []
		};
		res.send(indicatorResultJSON);
	}
};

var genDimStr = function(dimensionArray) {
	var dimensionStr = '';
	dimensionArray.forEach(function(d) {
		dimensionStr += d.dimension_key;
	});
	return dimensionStr;
}

exports.indicatorMapping = function(req, res) {
	var indicatorMappingJSON = {};
	var query = require('url').parse(req.url, true).query;
	var idc = query.idc;
	var dimensions = [];
	var measures = [];
	IndicatorSchema.find({
		indicator_key : idc
	}, function(err, doc) {
		if (err)
			console.log('Exception: ' + err);
		doc.forEach(function(item, index) {
			var tempDimensions = item.dimension;
			tempDimensions.forEach(function(dimension, index) {
				var tempDimension = {
					"uniqueName" : dimension.dimension_key,
					"name" : dimension.dimension_key,
					"text" : dimension.dimension_text
				};
				dimensions.push(tempDimension);
			});
			var tempMesureJson = {
				"uniqueName" : item.indicator_key,
				"name" : item.indicator_key,
				"text" : item.indicator_text,
				"data_source" : item.data_source,
				"source_note" : item.sourceNote,
				"data_type" : item.data_type
			};
			measures.push(tempMesureJson);
		});
		indicatorMappingJSON = {
			"dimensions" : dimensions,
			"measures" : measures
		};
		res.send(indicatorMappingJSON);
	});
}

exports.topicSearch = function(req, res) {
	IndicatorSchema.find({}, {
		_id : 0,
		topics : 1,
		indicator_text : 1,
		indicator_key : 1
	}).sort({
		'topics' : 1
	}).exec(function(err, doc) {
		if (err)
			console.log('Exception: ' + err);
		var topicArray = [];
		var topicObjArray = [];
		doc.forEach(function(item) {
			if (item.topics !== null && item.topics.length > 0) {
				item.topics.forEach(function(topic) {
					if (topic !== null && topic !== '') {
						if (topicArray.indexOf(topic) === -1) {
							var topicObj = {
								'topic' : topic,
								'indicatorKey' : [],
								'indicatorText' : []
							};
							topicArray.push(topic);
							topicObjArray.push(topicObj);
						}
					}
				});
			}
		});
		topicObjArray.forEach(function(topicObj) {
			doc.forEach(function(item) {
				if (item.topics !== null && item.topics.indexOf(topicObj.topic) > -1) {
					topicObj.indicatorKey.push(item.indicator_key);
					topicObj.indicatorText.push(item.indicator_text);
				}
			});
		});
		// console.log(topicObjArray);
		res.send(topicObjArray);
	});
};<commit_msg>append data source in topic view<commit_after>var cache = require('memory-cache');
var mongodb = require('../data/mongodb');
var indicator = require('../data/indicator');
var async = require('../lib/async');
var IndicatorSchema = indicator.Indicator;

exports.searchIndicator = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var indicatorResultJSON = {};
	if (query.query != null && query.query.length > 0) {
		var input = query.query;
		var keys = input.split(' ');
		var dimensions = [];
		var results = [];
		var callbackFuncArray = [];
		keys.forEach(function(key, index) {
			if (key.length > 0) {
				var callbackFunc = function(callback) {
					IndicatorSchema.find({
						indicator_text : {
							$regex : key,
							$options : 'i'
						}
					}, function(err, doc) {
						if (err)
							console.log('Exception: ' + err);
						doc.forEach(function(item, index) {
							var tempJson = {
								"uniqueName" : item.indicator_key,
								"text" : item.indicator_text + ' - ' + item.data_source,
								"dimensionStr" : genDimStr(item.dimension)
							};
							results.push(tempJson);
						});
						// match dimension value
						// if (doc.length === 0 && key.length > 2) {
						// var dims = cache.get('dimensions');
						// dims.forEach(function(d) {
						// if ((d.dimension_value +
						// '').toLowerCase().indexOf(key.toLowerCase()) > -1) {
						// dimensions.push(d);
						// }
						// });
						// }
						callback();
					});
				}
				callbackFuncArray.push(callbackFunc);
			}
		});
		async.parallel(callbackFuncArray, function() {
			console.log('matched results count: ' + results.length);
			// console.log('matched dimension value count: ' +
			// dimensions.length);
			// results.forEach(function(r) {
			// dimensions.forEach(function(d) {
			// if (r.dimensionStr.indexOf(d.dimension_key) > -1) {
			// r.text = d.dimension_value + ' - ' + r.text;
			// r.uniqueName = r.uniqueName + '///' + d.dimension_key + '///' +
			// d.dimension_value;
			// results.push(r);
			// }
			// });
			// });
			indicatorResultJSON = {
				"indicators" : results
			};
			// console.log(indicatorResultJSON);
			res.send(indicatorResultJSON);
		});
	} else {
		indicatorResultJSON = {
			"indicators" : []
		};
		res.send(indicatorResultJSON);
	}
};

var genDimStr = function(dimensionArray) {
	var dimensionStr = '';
	dimensionArray.forEach(function(d) {
		dimensionStr += d.dimension_key;
	});
	return dimensionStr;
}

exports.indicatorMapping = function(req, res) {
	var indicatorMappingJSON = {};
	var query = require('url').parse(req.url, true).query;
	var idc = query.idc;
	var dimensions = [];
	var measures = [];
	IndicatorSchema.find({
		indicator_key : idc
	}, function(err, doc) {
		if (err)
			console.log('Exception: ' + err);
		doc.forEach(function(item, index) {
			var tempDimensions = item.dimension;
			tempDimensions.forEach(function(dimension, index) {
				var tempDimension = {
					"uniqueName" : dimension.dimension_key,
					"name" : dimension.dimension_key,
					"text" : dimension.dimension_text
				};
				dimensions.push(tempDimension);
			});
			var tempMesureJson = {
				"uniqueName" : item.indicator_key,
				"name" : item.indicator_key,
				"text" : item.indicator_text,
				"data_source" : item.data_source,
				"source_note" : item.sourceNote,
				"data_type" : item.data_type
			};
			measures.push(tempMesureJson);
		});
		indicatorMappingJSON = {
			"dimensions" : dimensions,
			"measures" : measures
		};
		res.send(indicatorMappingJSON);
	});
}

exports.topicSearch = function(req, res) {
	IndicatorSchema.find({}, {
		_id : 0,
		topics : 1,
		indicator_key : 1,
		indicator_text : 1,
		data_source : 1
	}).sort({
		'topics' : 1
	}).exec(function(err, doc) {
		if (err)
			console.log('Exception: ' + err);
		var topicArray = [];
		var topicObjArray = [];
		doc.forEach(function(item) {
			if (item.topics !== null && item.topics.length > 0) {
				item.topics.forEach(function(topic) {
					if (topic !== null && topic !== '') {
						if (topicArray.indexOf(topic) === -1) {
							var topicObj = {
								'topic' : topic,
								'indicatorKey' : [],
								'indicatorText' : []
							};
							topicArray.push(topic);
							topicObjArray.push(topicObj);
						}
					}
				});
			}
		});
		topicObjArray.forEach(function(topicObj) {
			doc.forEach(function(item) {
				if (item.topics !== null && item.topics.indexOf(topicObj.topic) > -1) {
					topicObj.indicatorKey.push(item.indicator_key);
					topicObj.indicatorText.push(item.indicator_text + ' - ' + item.data_source);
				}
			});
		});
		// console.log(topicObjArray);
		res.send(topicObjArray);
	});
};<|endoftext|>


<commit_before>import { app, BrowserWindow } from 'electron';

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
  });

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
<commit_msg>Disable global-require check for default template call to electron-squirrel-startup<commit_after>import { app, BrowserWindow } from 'electron';

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
  });

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
<|endoftext|>


<commit_before>const chai = require('chai')
const assert = chai.assert
const rewire = require('rewire')

const metrics = rewire('../server/utils/metrics.js')

describe('metrics.js unit', () => {
	var promBundle = metrics.__get__('promBundle')
	it('promBundle exists', () => {
		assert.exists(
			promBundle,
			'promBundle is null or undefined'
		)
	})

	it('promBundle should be a function', () => {
		assert.isFunction(
			promBundle,
			'promBundle is not a function!')
	})

	const metricsMiddleware = metrics.__get__('metricsMiddleware')
	it('metricsMiddleware should  not null / undefined', () => {

		assert.exists(
			metricsMiddleware,
			'metricsMiddleware is null or undefined'
		)
	})

	it('metricsMiddleware should be a function', () => {
		assert.isFunction(
			metricsMiddleware,
			'metricsMiddleware is not a function!')
	})

	it('metricsMiddleware should have metrics not null/undef', () => {
		assert.exists(
			metricsMiddleware.metrics,
			'metrics is not defined in metricsMiddleware'
		)
	})

	it ('http request duration seconds exists in metrics', () => {
		assert.exists(
			metricsMiddleware.metrics.http_request_duration_seconds,
			'http request duration seconds DOES NOT exists in metrics!'
		)
	})

})<commit_msg>added integration to metrics.test.js<commit_after>const chai = require('chai')
const assert = chai.assert
const chaiHttp = require('chai-http')
const rewire = require('rewire')
const server = require('../server/app')
const metrics = rewire('../server/utils/metrics.js')
const config = require('config')

const basicConfig = config.get('passportConfig')

const should = chai.should()
chai.use(chaiHttp)

before(function (done) {

	/**
	 * Wait for server to start (event appStarted) to start tests
	 */
	server.on('appStarted', function() {
		// remember you need --timeout on mocha CLI to be around 20000
		console.log('app started event listened...')
		done()
	})
})

describe('metrics.js unit', () => {
	var promBundle = metrics.__get__('promBundle')
	it('promBundle exists', () => {
		assert.exists(
			promBundle,
			'promBundle is null or undefined'
		)
	})

	it('promBundle should be a function', () => {
		assert.isFunction(
			promBundle,
			'promBundle is not a function!')
	})

	const metricsMiddleware = metrics.__get__('metricsMiddleware')
	it('metricsMiddleware should  not null / undefined', () => {

		assert.exists(
			metricsMiddleware,
			'metricsMiddleware is null or undefined'
		)
	})

	it('metricsMiddleware should be a function', () => {
		assert.isFunction(
			metricsMiddleware,
			'metricsMiddleware is not a function!')
	})

	it('metricsMiddleware should have metrics not null/undef', () => {
		assert.exists(
			metricsMiddleware.metrics,
			'metrics is not defined in metricsMiddleware'
		)
	})

	it ('http request duration seconds exists in metrics', () => {
		assert.exists(
			metricsMiddleware.metrics.http_request_duration_seconds,
			'http request duration seconds DOES NOT exists in metrics!'
		)
	})
})

/**
 * Integration test using localhost (not mocked)
 */
describe('/passport/metrics - metrics endpoint (integration)', ()  => {
	const gluuBasePath = 'http://127.0.0.1'

	// server should be up and running, integration test
	it('Health check - GET /passport/health-check', (done) => {
		chai.request(gluuBasePath)
			.get('/passport/health-check')

			.end((err, res) => {
				res.should.have.status(200)
				done()
			})
	})

	it('GET request should return status code 200', (done) => {
		chai.request(gluuBasePath)
			.get('/passport/metrics')
			.end(function(err, res) {
				res.should.have.status(200)
				done()
			})
	}
})
<|endoftext|>


<commit_before><commit_msg>Radio: Stopping stream must also stop downloading<commit_after><|endoftext|>