<commit_before>const test = require('ava')
const helpers = require('./_helpers')
const laabr = require('../src')

let consoleClone
let interceptOut
let interceptErr

test.beforeEach('setup interceptor', (t) => {
  consoleClone = Object.assign({}, console)
  interceptOut = helpers.getInterceptor()
  interceptErr = helpers.getInterceptor({ stream: process.stderr })
})

test.afterEach('cleanup interceptor', (t) => {
  Object.assign(console, consoleClone)
  helpers.disableInterceptor(interceptOut, interceptErr)
})

test.cb.serial('listen to `onPostStart/onPostStop` events', (t) => {
  laabr.format('onPostStart', ':time :level :message :host[uri]')

  helpers.getServer({}, (server) => {
    server.start().then(() => {
      t.truthy(interceptOut.find('info server started http://127.0.0.1:1337'))

      server.stop({ timeout: 1000 }, () => {
        t.truthy(interceptOut.find('info server stopped'))
        t.end()
      })
    })
  })
})

test.cb.serial('listen to `response` event', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('GET 127.0.0.1 /response/200 200 {}'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – post', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('POST 127.0.0.1 /response/204 204 {"foo":42}'))
      t.end()
    })

    server.inject({
      method: 'POST',
      url: '/response/204',
      payload: {
        foo: 42
      }
    })
  })
})

test.cb.serial('listen to `request-error` event', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      const result = JSON.parse(interceptOut.find('"error": "foobar"').string)

      t.is(result.error, 'foobar')
      t.truthy(result.timestamp)
      t.is(result.level, 'warn')
      t.is(result.environment, 'test')
      t.deepEqual(Object.keys(result).sort(), ['timestamp', 'error', 'level', 'environment'].sort())
      t.truthy(interceptOut.find('GET 127.0.0.1 /requestError 500 {}'))

      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/requestError'
    })
  })
})

test.cb.serial('listen to `log` event', (t) => {
  helpers.getServer({ indent: 0 }, (server) => {
    server.log('info', 'foobar')
    const result = JSON.parse(interceptOut.find('"message":"foobar"').string)

    t.is(result.message, 'foobar')
    t.truthy(result.timestamp)
    t.is(result.level, 'info')
    t.is(result.environment, 'test')
    t.deepEqual(Object.keys(result).sort(), ['timestamp', 'message', 'level', 'environment'].sort())
    t.end()
  })
})

test.cb.serial('listen to `response` event – customized', (t) => {
  laabr.format('response', ':get[req.headers]')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('{"user-agent":"shot","host":"127.0.0.1:1337"}'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – preset', (t) => {
  laabr.preset('test.env', ':time :environment :method')
  laabr.format('response', 'test.env')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('test GET'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no token', (t) => {
  laabr.format('response', ':foobar')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find(':foobar'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no json token', (t) => {
  laabr.format('response', '({ foobar::foobar })')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('"foobar": ":foobar"'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no format', (t) => {
  laabr.format('response', false)

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      const result = JSON.parse(interceptOut.find('"msg": "request completed"').string)

      t.truthy(result)
      t.is(result.level, 30)
      t.truthy(result.pid)
      t.truthy(result.hostname)
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `log` event – customized', (t) => {
  const mockData = {
    foo: {
      bar: 42
    }
  }

  helpers.getServer({ indent: 0 }, (server) => {
    server.log('info', mockData)
    const result = JSON.parse(interceptOut.find('"message":{"foo":{"bar":42}}').string)

    t.truthy(result)
    t.deepEqual(result.message, mockData)
    t.truthy(result.timestamp)
    t.is(result.level, 'info')
    t.is(result.environment, 'test')
    t.deepEqual(Object.keys(result).sort(), ['timestamp', 'message', 'level', 'environment'].sort())
    t.end()
  })
})

test.cb.serial('listen to `log` event – multiple tags', (t) => {
  const mockData = {
    foo: {
      bar: 42
    }
  }

  laabr.format('log', '({ tags::tags, message::message })')
  helpers.getServer({ indent: 0 }, (server) => {
    server.log(['info', 'foobar'], mockData)
    const result = JSON.parse(interceptOut.find('"message":{"foo":{"bar":42}}').string)

    t.truthy(result)
    t.deepEqual(result.message, mockData)
    t.deepEqual(result.tags, ['info', 'foobar'])
    t.end()
  })
})

test.cb.serial('get deprecation messages because of deprecating options', (t) => {
  helpers.getServer({ indent: 0, plugin: {} }, () => {
    t.truthy(interceptErr.find('`options.plugin` will be deprecated soon. Use `options.hapiPino` instead'))
    t.end()
  })
})

test.cb.serial('get log message by overriden `console.warn` – single', (t) => {
  helpers.getServer({ indent: 0, override: true }, () => {
    console.warn('foobar')
    t.truthy(interceptOut.find('"message":"foobar"'))
    t.end()
  })
})

test.cb.serial('get log message by overriden `console.warn` – multiple', (t) => {
  helpers.getServer({ indent: 0, override: true }, () => {
    console.warn('foo', 'bar')

    t.truthy(interceptOut.find('"message":["foo","bar"]'))
    t.end()
  })
})
<commit_msg>add tests for inline and concat strings<commit_after>const test = require('ava')
const helpers = require('./_helpers')
const laabr = require('../src')

let consoleClone
let interceptOut
let interceptErr

test.beforeEach('setup interceptor', (t) => {
  consoleClone = Object.assign({}, console)
  interceptOut = helpers.getInterceptor()
  interceptErr = helpers.getInterceptor({ stream: process.stderr })
})

test.afterEach('cleanup interceptor', (t) => {
  Object.assign(console, consoleClone)
  helpers.disableInterceptor(interceptOut, interceptErr)
})

test.cb.serial('listen to `onPostStart/onPostStop` events', (t) => {
  laabr.format('onPostStart', ':time :level :message :host[uri]')

  helpers.getServer({}, (server) => {
    server.start().then(() => {
      t.truthy(interceptOut.find('info server started http://127.0.0.1:1337'))

      server.stop({ timeout: 1000 }, () => {
        t.truthy(interceptOut.find('info server stopped'))
        t.end()
      })
    })
  })
})

test.cb.serial('listen to `response` event', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('GET 127.0.0.1 /response/200 200 {}'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – post', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('POST 127.0.0.1 /response/204 204 {"foo":42}'))
      t.end()
    })

    server.inject({
      method: 'POST',
      url: '/response/204',
      payload: {
        foo: 42
      }
    })
  })
})

test.cb.serial('listen to `request-error` event', (t) => {
  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      const result = JSON.parse(interceptOut.find('"error": "foobar"').string)

      t.is(result.error, 'foobar')
      t.truthy(result.timestamp)
      t.is(result.level, 'warn')
      t.is(result.environment, 'test')
      t.deepEqual(Object.keys(result).sort(), ['timestamp', 'error', 'level', 'environment'].sort())
      t.truthy(interceptOut.find('GET 127.0.0.1 /requestError 500 {}'))

      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/requestError'
    })
  })
})

test.cb.serial('listen to `log` event', (t) => {
  helpers.getServer({ indent: 0 }, (server) => {
    server.log('info', 'foobar')
    const result = JSON.parse(interceptOut.find('"message":"foobar"').string)

    t.is(result.message, 'foobar')
    t.truthy(result.timestamp)
    t.is(result.level, 'info')
    t.is(result.environment, 'test')
    t.deepEqual(Object.keys(result).sort(), ['timestamp', 'message', 'level', 'environment'].sort())
    t.end()
  })
})

test.cb.serial('listen to `response` event – customized', (t) => {
  laabr.format('response', ':get[req.headers]')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('{"user-agent":"shot","host":"127.0.0.1:1337"}'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – preset', (t) => {
  laabr.preset('test.env', ':time :environment :method')
  laabr.format('response', 'test.env')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('test GET'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no token', (t) => {
  laabr.format('response', ':foobar')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find(':foobar'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no json token', (t) => {
  laabr.format('response', '({ foobar::foobar })')

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      t.truthy(interceptOut.find('"foobar": ":foobar"'))
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `response` event – no format', (t) => {
  laabr.format('response', false)

  helpers.getServer({}, (server) => {
    server.on('tail', () => {
      const result = JSON.parse(interceptOut.find('"msg": "request completed"').string)

      t.truthy(result)
      t.is(result.level, 30)
      t.truthy(result.pid)
      t.truthy(result.hostname)
      t.end()
    })

    server.inject({
      method: 'GET',
      url: '/response/200'
    })
  })
})

test.cb.serial('listen to `log` event – customized', (t) => {
  const mockData = {
    foo: {
      bar: 42
    }
  }

  helpers.getServer({ indent: 0 }, (server) => {
    server.log('info', mockData)
    const result = JSON.parse(interceptOut.find('"message":{"foo":{"bar":42}}').string)

    t.truthy(result)
    t.deepEqual(result.message, mockData)
    t.truthy(result.timestamp)
    t.is(result.level, 'info')
    t.is(result.environment, 'test')
    t.deepEqual(Object.keys(result).sort(), ['timestamp', 'message', 'level', 'environment'].sort())
    t.end()
  })
})

test.cb.serial('listen to `log` event – multiple tags', (t) => {
  const mockData = {
    foo: {
      bar: 42
    }
  }

  laabr.format('log', '({ tags::tags, message::message })')
  helpers.getServer({ indent: 0 }, (server) => {
    server.log(['info', 'foobar'], mockData)
    const result = JSON.parse(interceptOut.find('"message":{"foo":{"bar":42}}').string)

    t.truthy(result)
    t.deepEqual(result.message, mockData)
    t.deepEqual(result.tags, ['info', 'foobar'])
    t.end()
  })
})

test.cb.serial('get deprecation messages because of deprecating options', (t) => {
  helpers.getServer({ indent: 0, plugin: {} }, () => {
    t.truthy(interceptErr.find('`options.plugin` will be deprecated soon. Use `options.hapiPino` instead'))
    t.end()
  })
})

test.cb.serial('get log message by overriden `console.warn` – single', (t) => {
  helpers.getServer({ indent: 0, override: true }, () => {
    console.warn('foobar')
    t.truthy(interceptOut.find('"message":"foobar"'))
    t.end()
  })
})

test.cb.serial('get log message by overriden `console.warn` – multiple', (t) => {
  helpers.getServer({ indent: 0, override: true }, () => {
    console.warn('foo', 'bar')

    t.truthy(interceptOut.find('"message":["foo","bar"]'))
    t.end()
  })
})

test.cb.serial('listen to `log` event – concat strings', (t) => {
  const mockData = 'foo'

  laabr.format('log', '({ message:(:message) + `bar` })')
  helpers.getServer({ indent: 0 }, (server) => {
    server.log(['info'], mockData)
    const result = JSON.parse(interceptOut.find('"message":"foobar"').string)

    t.truthy(result)
    t.deepEqual(result.message, 'foobar')
    t.end()
  })
})

test.cb.serial('listen to `log` event – inline strings', (t) => {
  const mockData = 'foo'

  laabr.format('log', '({ message: [:message,`bar`] })')
  helpers.getServer({ indent: 0 }, (server) => {
    server.log(['info'], mockData)
    const result = JSON.parse(interceptOut.find('"message":["foo","bar"]').string)

    t.truthy(result)
    t.deepEqual(result.message, ['foo', 'bar'])
    t.end()
  })
})
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chai = require('chai');
var packageDependenciesFilePaths = require('../');
var path = require('path');

var MOCHA_TIMEOUT = 50000;

var cwd = process.cwd();
var expect = chai.expect;
var pkgJson = require('../package.json');

describe('package-dependencies-file-paths', function() {
    this.timeout(MOCHA_TIMEOUT);

    function validateDependenciesPaths(filePaths, pkgJson) {
        _.forEach(_.keys(pkgJson.dependencies), function(dependency) {
            var dependencyPackageJsonFilePath = path.join('node_modules', dependency, 'package.json');
            expect(filePaths).to.include(dependencyPackageJsonFilePath);
        });
    }

    function transformFilePath(filePath) {
        return filePath.replace(cwd + path.sep, '');
    }

    it('should resolve package.json dependencies file paths', function(done) {
        var options = {
            includeDotFiles: true,
            ignore: [
                '**/{doc,docs,example,examples,fixture,fixtures,spec,test,tests}/**',
                '**/{.,}{eslint,jscs,jshint}rc{.json,}',
                '**/.{editorconfig,gitattributes,gitmodules}',
                '**/.{eslint,git,npm}ignore',
                '**/.travis.yml',
                '**/{bower,component}.json',
                '**/{gulpfile,Gruntfile}.js',
                '**/{LICENCE,LICENSE,License,license}',
                '**/*.{spec,test}.js',
                '**/*.{markdown,md,ts}'
            ],
            transformPath: transformFilePath,
            sort: true
        };
        packageDependenciesFilePaths(pkgJson, options, function(err, filePaths) {
            expect(err).to.not.exists;

            // Validate file paths Array is not empty
            expect(filePaths).to.be.instanceof(Array);
            expect(filePaths).to.not.be.empty;

            _.forEach(filePaths, function(filePath) {
                // Validate documentation, example, fixtures, spec and test folders have been ignored
                expect(filePath).to.not.match(/.+\/(doc|example|fixture|spec|test)s?\/.+\.(js|json|yml)$/i);

                // Validate dot files have been ignored
                expect(filePath).to.not.match(/\.(editorconfig|gitattributes|gitmodules)/i);
                expect(filePath).to.not.match(/\.(eslint|git|npm)ignore/i);
                expect(filePath).to.not.match(/\.?(eslint|jscs|jshint)rc\.json$/i);
                expect(filePath).to.not.match(/\.travis\.yml$/i);

                // Validate Markdown and Typescript files have been ignored
                expect(filePath).to.not.match(/\.(markdown|md|ts)$/i);

                // Validate spec and test files have been ignored
                expect(filePath).to.not.match(/\.(spec|test)\.js$/i);

                // Validate bower.json, component.json, Gruntfile.js and gulpfile.json files have been ignored
                expect(filePath).to.not.match(/(bower|component)\.json$/i);
                expect(filePath).to.not.match(/(Gruntfile|gulpfile)\.js$/i);

                // Validate license files have been ignored
                expect(filePath).to.not.match(/licen(c|s)e$/i);
            });

            // Validate package.json dependencies paths are included in file paths
            validateDependenciesPaths(filePaths, pkgJson);

            done();
        });
    });

    it('should resolve package.json dependencies file paths without including dot files', function(done) {
        var options = {
            transformPath: transformFilePath
        };
        packageDependenciesFilePaths(pkgJson, options, function(err, filePaths) {
            expect(err).to.not.exists;

            // Validate file paths Array is not empty
            expect(filePaths).to.be.instanceof(Array);
            expect(filePaths).to.not.be.empty;

            _.forEach(filePaths, function(filePath) {
                // Validate dot files have been ignored
                expect(filePath).to.not.match(/\.(editorconfig|gitattributes|gitmodules)/i);
                expect(filePath).to.not.match(/\.(eslint|git|npm)ignore/i);
                expect(filePath).to.not.match(/\.?(eslint|jscs|jshint)rc\.json$/i);
                expect(filePath).to.not.match(/\.travis\.yml$/i);
            });

            // Validate package.json dependencies paths are included in file paths
            validateDependenciesPaths(filePaths, pkgJson);

            done();
        });
    });
});
<commit_msg>Improve tests<commit_after>'use strict';

var _ = require('lodash');
var chai = require('chai');
var packageDependenciesFilePaths = require('../');
var path = require('path');

var MOCHA_TIMEOUT = 50000;

var cwd = process.cwd();
var expect = chai.expect;
var pkgJson = require('../package.json');

describe('package-dependencies-file-paths', function() {
    this.timeout(MOCHA_TIMEOUT);

    function validateDependenciesPaths(filePaths, pkgJson) {
        _.forEach(_.keys(pkgJson.dependencies), function(dependency) {
            var dependencyPackageJsonFilePath = path.join('node_modules', dependency, 'package.json');
            expect(filePaths).to.include(dependencyPackageJsonFilePath);
        });
    }

    function transformFilePath(filePath) {
        return filePath.replace(cwd + path.sep, '');
    }

    it('should resolve package.json dependencies file paths', function(done) {
        var options = {
            includeDotFiles: true,
            ignore: [
                '**/{doc,docs,example,examples,fixture,fixtures,spec,test,tests}/**',
                '**/{.,}{eslint,jscs,jshint}rc{.json,}',
                '**/.{editorconfig,gitattributes,gitmodules}',
                '**/.{eslint,git,npm}ignore',
                '**/.travis.yml',
                '**/{bower,component}.json',
                '**/{gulpfile,Gruntfile}.js',
                '**/{LICENCE,LICENSE,License,license}',
                '**/*.{spec,test}.js',
                '**/*.{markdown,md,ts}'
            ],
            transformPath: transformFilePath,
            sort: true
        };
        packageDependenciesFilePaths(pkgJson, options, function(err, filePaths) {
            expect(err).to.not.exists;

            // Validate file paths Array
            expect(filePaths).to.be.instanceof(Array);
            expect(filePaths).to.not.be.empty;

            _.forEach(filePaths, function(filePath) {
                // Validate documentation, example, fixtures, spec and test folders have been ignored
                expect(filePath).to.not.match(/.+\/(doc|example|fixture|spec|test)s?\/.+/i);

                // Validate dot files have been ignored
                expect(filePath).to.not.match(/\.(editorconfig|gitattributes|gitmodules)$/i);
                expect(filePath).to.not.match(/\.(eslint|git|npm)ignore$/i);
                expect(filePath).to.not.match(/\.?(eslint|jscs|jshint)rc(\.json)?$/i);
                expect(filePath).to.not.match(/\.travis\.yml$/i);

                // Validate Markdown and Typescript files have been ignored
                expect(filePath).to.not.match(/\.(markdown|md|ts)$/i);

                // Validate spec and test files have been ignored
                expect(filePath).to.not.match(/\.(spec|test)\.js$/i);

                // Validate bower.json, component.json, Gruntfile.js and gulpfile.json files have been ignored
                expect(filePath).to.not.match(/(bower|component)\.json$/i);
                expect(filePath).to.not.match(/(gruntfile|gulpfile)\.js$/i);

                // Validate license files have been ignored
                expect(filePath).to.not.match(/licen(c|s)e$/i);
            });

            // Validate package.json dependencies paths are included in file paths
            validateDependenciesPaths(filePaths, pkgJson);

            done();
        });
    });

    it('should resolve package.json dependencies file paths without including dot files', function(done) {
        var options = {
            transformPath: transformFilePath
        };
        packageDependenciesFilePaths(pkgJson, options, function(err, filePaths) {
            expect(err).to.not.exists;

            // Validate file paths Array
            expect(filePaths).to.be.instanceof(Array);
            expect(filePaths).to.not.be.empty;

            _.forEach(filePaths, function(filePath) {
                // Validate dot files have been ignored
                expect(filePath).to.not.match(/\.(editorconfig|gitattributes|gitmodules)$/i);
                expect(filePath).to.not.match(/\.(eslint|git|npm)ignore$/i);
                expect(filePath).to.not.match(/\.?(eslint|jscs|jshint)rc(\.json)?$/i);
                expect(filePath).to.not.match(/\.travis\.yml$/i);
            });

            // Validate package.json dependencies paths are included in file paths
            validateDependenciesPaths(filePaths, pkgJson);

            done();
        });
    });
});
<|endoftext|>


<commit_before>const getResults = require('../lib')
const nock = require('nock')
const test = require('tape')

test('check results', (assert) => {
  let today = (new Date()).toISOString().substring(0, 10)

  getResults(today)
    .then(results => {
      assert.equal(Array.isArray(results), true, 'results should be an array')
      results.every(i => assert.ok(typeof i === 'object', 'every item in results should be an object'))
      assert.end()
    })
})

test('check invalid date parameter', (assert) => {
  let today = 'this is not a valid date'

  getResults(today)
    .catch(error => {
      assert.equal(typeof error, 'object', 'error should be an object')
      assert.end()
    })
})

test('check 404 network error', (assert) => {
  let today = (new Date()).toISOString().substring(0, 10)

  nock('http://www.dejugadas.com/quinielas/datospizarra.php')
    .get('*')
    .reply(404)

  getResults(today)
    .catch(error => {
      assert.equal(typeof error, 'object', 'error should be an object')
      assert.end()
    })
})
<commit_msg>test(library): Fix scopes for tests<commit_after>const getResults = require('../lib')
const nock = require('nock')
const test = require('tape')

test('check results', (assert) => {
  let today = (new Date()).toISOString().substring(0, 10)

  getResults(today)
    .then(results => {
      assert.equal(Array.isArray(results), true, 'results should be an array')
      results.every(i => assert.ok(typeof i === 'object', 'every item in results should be an object'))
      assert.end()
    })
})

test('check invalid date parameter', (assert) => {
  let today = 'this is not a valid date'

  getResults(today)
    .catch(error => {
      assert.equal(typeof error, 'object', 'error should be an object after an invalid date parameter')
      assert.end()
    })
})

test('check network error (404)', (assert) => {
  let today = (new Date()).toISOString().substring(0, 10)

  nock('http://www.dejugadas.com/quinielas/datospizarra.php')
    .get('*')
    .reply(404)

  getResults(today)
    .catch(error => {
      assert.equal(typeof error, 'object', 'error should be an object after a network error (404)')
      assert.end()
    })
})
<|endoftext|>


<commit_before>/*
 Copyright 2008-present Shaiksphere, Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

const mindsmine = require("../../../dist/@REQUIRE_FILE@");

test("mindsmine.productName should return product name", () => {
    expect(mindsmine.productName).toBe("mindsmine-js");
});

test("mindsmine.productVersion should return product version", () => {
    expect(mindsmine.productVersion).toBe("4.8.0");
});

//_MORE_CODE

//_CONCATENATED_HOLDER_CODE

//_CONCATENATED_HELPER_CODE
<commit_msg>Updating the versions<commit_after>/*
 Copyright 2008-present Shaiksphere, Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

const mindsmine = require("../../../dist/@REQUIRE_FILE@");

test("mindsmine.productName should return product name", () => {
    expect(mindsmine.productName).toBe("mindsmine-js");
});

test("mindsmine.productVersion should return product version", () => {
    expect(mindsmine.productVersion).toBe("4.8.1");
});

//_MORE_CODE

//_CONCATENATED_HOLDER_CODE

//_CONCATENATED_HELPER_CODE
<|endoftext|>


<commit_before>var expect = require("chai").expect,
	proxyquire = require("proxyquire"),
	sinon = require("sinon");

var pgStub = {},
	clientStub = {},
	done = sinon.spy();

var votes = [ { score: 12, country: "Narnia" },
              { score: 10, country: "Archenland" } ];

var index = proxyquire("../routes/index", {
	'pg' : pgStub
});

pgStub.connect = function(url, callback) {
	callback(null, clientStub, done);
};

clientStub.query = function(sql, callback) {
	var results = { rows: votes };
	callback(null, results);
};

describe("routes/index", function() {
	var req = {}, res = {};
	var spy = res.render = sinon.spy();

	beforeEach(function() {
		spy.reset();
		done.reset();
	});

	it("should render home page", function() {
		index.index(req, res);

		expect(spy.calledOnce).to.equal(true);
		expect(spy.args[0][0]).to.equal("index");
	});

	it("should set page title and navbarActive properties", function() {
		index.index(req, res);

		var locals = spy.args[0][1];
		expect(locals).to.have.property("title").that.equals("Eurovision 2015");
		expect(locals).to.have.property("navbarActive").that.equals("Home");
	});

	it("should include votes in the response", function() {
		index.index(req, res);

		var locals = spy.args[0][1];
		expect(locals).to.have.property("results").that.equals(votes);
	});

	it("should call done() after retrieving results", function() {
		index.index(req, res);
		expect(done.calledOnce).to.equal(true);
	});
});
<commit_msg>Refactored index.test.js to use sinon stubs for pg<commit_after>var expect = require("chai").expect,
	proxyquire = require("proxyquire"),
	sinon = require("sinon");

var pgStub = {},
	clientStub = {},
	done = sinon.spy();

var votes = [ { score: 12, country: "Narnia" },
              { score: 10, country: "Archenland" } ];

var index = proxyquire("../routes/index", {
	'pg' : pgStub
});

pgStub.connect = sinon.stub();
clientStub.query = sinon.stub();

describe("routes/index", function() {
	var req = {}, res = {};
	var spy = res.render = sinon.spy();

	beforeEach(function() {
		pgStub.connect.callsArgWith(1, null, clientStub, done);
		clientStub.query.callsArgWith(1, null, { rows: votes });
		spy.reset();
		done.reset();
	});

	it("should render home page", function() {
		index.index(req, res);

		expect(spy.calledOnce).to.equal(true);
		expect(spy.args[0][0]).to.equal("index");
	});

	it("should set page title and navbarActive properties", function() {
		index.index(req, res);

		var locals = spy.args[0][1];
		expect(locals).to.have.property("title").that.equals("Eurovision 2015");
		expect(locals).to.have.property("navbarActive").that.equals("Home");
	});

	it("should include votes in the response", function() {
		index.index(req, res);

		var locals = spy.args[0][1];
		expect(locals).to.have.property("results").that.equals(votes);
	});

	it("should call done() after retrieving results", function() {
		index.index(req, res);
		expect(done.calledOnce).to.equal(true);
	});
});
<|endoftext|>


<commit_before>if (process.env.CI) {
  process.env.DEBUG = '*';
}

var mvm = require('../'),
  assert = require('assert'),
  exec = require('child_process').exec,
  path = require('path'),
  debug = require('debug')('mongodb-version-manager:test');

var M = path.resolve(__dirname, '../bin/m.js');

debug('path to bin is %s', M);

var run = function(args, done) {
  if (typeof args === 'function') {
    done = args;
    args = '';
  }
  var cmd = 'node ' + M + ' ' + args;
  debug('running `%s`', cmd);

  exec(M, function(err, stdout, stderr) {
    debug('`%s` exec result', cmd, err, stdout, stderr);
    if (err) return done(err);
    done();
  });

};

describe('mvm', function() {
  describe('bin', function() {
    it('should work if i just run `m`', function(done) {
      run(done);
    });

    it('should work if i run `m ls`', function(done) {
      run('ls', done);
    });

    it('should work if i run `m available`', function(done) {
      run('available', done);
    });

    it('should work if i run `m path`', function(done) {
      run('path', done);
    });
  });
  describe('current', function() {
    it('should provide the current version', function(done) {
      mvm.current(function(err) {
        done(err);
      });
    });
  });
  describe('available', function() {
    it('should list stable versions', function(done) {
      mvm.available({
        stable: true
      }, function(err, versions) {
          assert.ifError(err);
          var unstable = versions.filter(function(v) {
            return (parseInt(v.split('.')[1], 10) % 2) > 0;
          });
          assert.equal(unstable.length, 0);
          done();
        });
    });
    it('should list unstable versions', function(done) {
      mvm.available({
        unstable: true
      }, function(err, versions) {
          assert.ifError(err);
          var stable = versions.filter(function(v) {
            return (parseInt(v.split('.')[1], 10) % 2) === 0;
          });
          assert.equal(stable.length, 0);
          done();
        });
    });
    it('should list rc versions', function(done) {
      mvm.available({
        rc: true
      }, function(err, versions) {
          assert.ifError(err);
          var stable = versions.filter(function(v) {
            return v.indexOf('rc') === -1;
          });
          assert.equal(stable.length, 0);
          done();
        });
    });
  });
});
<commit_msg>[#15] debugging tests (need full node.exe path)<commit_after>if (process.env.CI) {
  process.env.DEBUG = '*';
}

var mvm = require('../'),
  assert = require('assert'),
  exec = require('child_process').exec,
  path = require('path'),
  which = require('which'),
  debug = require('debug')('mongodb-version-manager:test');

var M = path.resolve(__dirname, '../bin/m.js');
var NODE = which.sync('node');

debug('path to m bin is %s', M);
debug('path to node bin is %s', NODE);

var run = function(args, done) {
  if (typeof args === 'function') {
    done = args;
    args = '';
  }

  var cmd = NODE + ' ' + M + ' ' + args;
  debug('running `%s`', cmd);

  exec(M, function(err, stdout, stderr) {
    debug('`%s` exec result', cmd, err, stdout, stderr);
    if (err) return done(err);
    done();
  });

};

describe('mvm', function() {
  describe('bin', function() {
    it('should work if i just run `m`', function(done) {
      run(done);
    });

    it('should work if i run `m ls`', function(done) {
      run('ls', done);
    });

    it('should work if i run `m available`', function(done) {
      run('available', done);
    });

    it('should work if i run `m path`', function(done) {
      run('path', done);
    });
  });
  describe('current', function() {
    it('should provide the current version', function(done) {
      mvm.current(function(err) {
        done(err);
      });
    });
  });
  describe('available', function() {
    it('should list stable versions', function(done) {
      mvm.available({
        stable: true
      }, function(err, versions) {
          assert.ifError(err);
          var unstable = versions.filter(function(v) {
            return (parseInt(v.split('.')[1], 10) % 2) > 0;
          });
          assert.equal(unstable.length, 0);
          done();
        });
    });
    it('should list unstable versions', function(done) {
      mvm.available({
        unstable: true
      }, function(err, versions) {
          assert.ifError(err);
          var stable = versions.filter(function(v) {
            return (parseInt(v.split('.')[1], 10) % 2) === 0;
          });
          assert.equal(stable.length, 0);
          done();
        });
    });
    it('should list rc versions', function(done) {
      mvm.available({
        rc: true
      }, function(err, versions) {
          assert.ifError(err);
          var stable = versions.filter(function(v) {
            return v.indexOf('rc') === -1;
          });
          assert.equal(stable.length, 0);
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @class
 * @augments ControlView
 */
var ScrollPanelView = ContainerView.extend(/** @lends ScrollPanelView.prototype */ {

    className: 'pl-scrollpanel panel panel-default',

    template: InfinniUI.Template["new/controls/scrollPanel/template/scrollPanel.tpl.html"],

    UI: {

    },

    initialize: function (options) {
        ContainerView.prototype.initialize.call(this, options);
    },

    render: function () {
        this.prerenderingActions();

        this.removeChildElements();
        this.$el.html(this.template({
            items: this.model.get('items')
        }));
        this.renderItemsContents();

        this.bindUIElements();

        this.postrenderingActions();

        this.trigger('render');
        this.updateProperties();
        return this;
    },

    initHandlersForProperties: function () {
        ContainerView.prototype.initHandlersForProperties.call(this);
        this.listenTo(this.model, 'change:horizontalScroll', this.updateHorizontalScroll);
        this.listenTo(this.model, 'change:verticalScroll', this.updateVerticalScroll);
    },

    updateProperties: function () {
        ContainerView.prototype.updateProperties.call(this);
        this.updateHorizontalScroll();
        this.updateVerticalScroll();
    },

    /**
     * @protected
     * @description Set one of CSS class: "pl-horizontal-scroll-(visible|hidden|auto)",
     */
    updateHorizontalScroll: function () {
        var name = '';
        switch (this.model.get('horizontalScroll')) {
            case ScrollVisibility.visible:
                name = 'visible';
                break;
            case ScrollVisibility.hidden:
                name = 'hidden';
                break;
            case ScrollVisibility.auto:
            default:
                name = 'auto';
                break;
        }
        this.switchClass('pl-horizontal-scroll', name, this.$el);
    },

    /**
     * @protected
     * @description Set one of CSS class: "pl-vertical-scroll-(visible|hidden|auto)",
     */
    updateVerticalScroll: function (model, value) {
        var name = '';
        switch (this.model.get('verticalScroll')) {
            case ScrollVisibility.visible:
                name = 'visible';
                break;
            case ScrollVisibility.hidden:
                name = 'hidden';
                break;
            case ScrollVisibility.auto:
            default:
                name = 'auto';
                break;
        }
        this.switchClass('pl-vertical-scroll', name, this.$el);
    },

    renderItemsContents: function () {
        var $items = this.$el.find('.pl-scrollpanel-i'),
            items = this.model.get('items'),
            itemTemplate = this.model.get('itemTemplate'),
            that = this,
            element, item;

        $items.each(function (i, el) {
            item = items.getByIndex(i);
            element = itemTemplate(undefined, {item: item, index: i});
            that.addChildElement(element);
            $(el)
                .append(element.render());
        });
    },

    updateGrouping: function () {

    }

});
<commit_msg>UI-1882: Panel разворачивается вверх#resolve<commit_after>/**
 * @class
 * @augments ControlView
 */
var ScrollPanelView = ContainerView.extend(/** @lends ScrollPanelView.prototype */ {

    className: 'pl-scrollpanel panel panel-default',

    template: InfinniUI.Template["new/controls/scrollPanel/template/scrollPanel.tpl.html"],

    UI: {

    },

    initialize: function (options) {
        ContainerView.prototype.initialize.call(this, options);
    },

    render: function () {
        this.prerenderingActions();

        this.removeChildElements();
        this.$el.html(this.template({
            items: this.model.get('items')
        }));
        this.renderItemsContents();

        this.bindUIElements();

        this.postrenderingActions();

        this.trigger('render');
        this.updateProperties();

        (function ($el) {
            //Firefox сохраняет позицию прокрутки. Принудительно крутим в начало.
            setTimeout(function () {
                $el.scrollTop(0);
            }, 0);
        })(this.$el);

        return this;
    },

    initHandlersForProperties: function () {
        ContainerView.prototype.initHandlersForProperties.call(this);
        this.listenTo(this.model, 'change:horizontalScroll', this.updateHorizontalScroll);
        this.listenTo(this.model, 'change:verticalScroll', this.updateVerticalScroll);
    },

    updateProperties: function () {
        ContainerView.prototype.updateProperties.call(this);
        this.updateHorizontalScroll();
        this.updateVerticalScroll();
    },

    /**
     * @protected
     * @description Set one of CSS class: "pl-horizontal-scroll-(visible|hidden|auto)",
     */
    updateHorizontalScroll: function () {
        var name = '';
        switch (this.model.get('horizontalScroll')) {
            case ScrollVisibility.visible:
                name = 'visible';
                break;
            case ScrollVisibility.hidden:
                name = 'hidden';
                break;
            case ScrollVisibility.auto:
            default:
                name = 'auto';
                break;
        }
        this.switchClass('pl-horizontal-scroll', name, this.$el);
    },

    /**
     * @protected
     * @description Set one of CSS class: "pl-vertical-scroll-(visible|hidden|auto)",
     */
    updateVerticalScroll: function (model, value) {
        var name = '';
        switch (this.model.get('verticalScroll')) {
            case ScrollVisibility.visible:
                name = 'visible';
                break;
            case ScrollVisibility.hidden:
                name = 'hidden';
                break;
            case ScrollVisibility.auto:
            default:
                name = 'auto';
                break;
        }
        this.switchClass('pl-vertical-scroll', name, this.$el);
    },

    renderItemsContents: function () {
        var $items = this.$el.find('.pl-scrollpanel-i'),
            items = this.model.get('items'),
            itemTemplate = this.model.get('itemTemplate'),
            that = this,
            element, item;

        $items.each(function (i, el) {
            item = items.getByIndex(i);
            element = itemTemplate(undefined, {item: item, index: i});
            that.addChildElement(element);
            $(el)
                .append(element.render());
        });
    },

    updateGrouping: function () {

    }

});
<|endoftext|>


<commit_before>var
  should = require('should'),
  EventEmitter = require('events'),
  proxyquire = require('proxyquire');

describe('plugin implementation', function () {
  var
    Plugin,
    plugin,
    emitter,
    setPort,
    fakeId = 'Verbal Kint',
    destination,
    linkedChannel,
    messageSent;

  before(function () {
    // stubbing socket.io
    Plugin = proxyquire('../lib/index', {
      'socket.io': portNumber => {
        emitter = new EventEmitter();

        setPort = portNumber;

        emitter.id = fakeId;
        emitter.set = () => {};
        emitter.to = () => {
          return {
            emit: (channel, payload) => {
              messageSent = payload;
              destination = channel;
            }
          };
        };

        emitter.sockets = { connected: {} };
        emitter.sockets.connected[fakeId] = {
          join: channel => linkedChannel = channel,
          leave: channel => linkedChannel = channel
        };

        return emitter;
      }
    });
  });

  beforeEach(function () {
    setPort = -1;
    destination = null;
    messageSent = null;
    linkedChannel = null;
    plugin = new Plugin();
  });

  describe('#general', function () {
    it('should expose an init function', function () {
      should(plugin.init).be.a.Function();
    });

    it('should expose a hooks object', function () {
      var hooks = require('../lib/config/hooks');
      should(plugin.hooks).match(hooks);
    });
  });

  describe('#init', function () {
    var
      config = {port: 1234},
      context = {foo: 'bar'};

    it('should throw an error if no "config" argument has been provided', function (done) {
      try {
        plugin.init(undefined, {}, true);
        done(new Error('Expected a throw, but nothing happened'));
      }
      catch (e) {
        done();
      }
    });

    it('should fallback to dummy-mode if no port configuration has been provided', function () {
      var ret = plugin.init({}, {}, false);

      should(ret).be.false();
      should(plugin.isDummy).be.true();
    });

    it('should set internal properties correctly', function () {
      var
        ret = plugin.init(config, context, true);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.true();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(-1);
    });

    it('should start a socket.io broker if not in dummy mode', function () {
      var ret = plugin.init(config, context, false);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.false();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(1234);
    });

    it('should manage new connections on a "connection" event', function (done) {
      var
        stubSocket = { thisIsNot: 'aSocket' };

      this.timeout(50);

      plugin.newConnection = socket => {
        should(socket).be.eql(stubSocket);
        done();
      };

      plugin.init(config, context, false);
      emitter.emit('connection', stubSocket);
    });

    it('should fallback to dummy-mode if the broker is unable to start', function (done) {
      this.timeout(50);

      plugin.init(config, context, false);
      emitter.emit('error', 'fake error');
      process.nextTick(() => {
        should(plugin.isDummy).be.true();
        done();
      });
    });
  });

  describe('#broadcast', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.broadcast({channel,payload});
      should(messageSent).be.null();
      should(destination).be.null();
    });

    it('should broadcast a message correctly', function () {
      plugin.broadcast({channel,payload});
      should(messageSent).be.eql(payload);
      should(destination).be.eql(channel);
    });
  });

  describe('#joinChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.joinChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#leaveChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.leaveChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#newConnection', function () {
    // some heavy stubbing here...
    var
      connection = {foo: 'bar'},
      fakeRequestId = 'fakeRequestId',
      serializedResponse = {bar: 'foo'},
      connected,
      executed,
      disconnected,
      response = {
        toJson: () => {
          return serializedResponse;
        }
      },
      context = {
        RequestObject: function (foo) {
          foo.requestId = fakeRequestId;
          return foo;
        },
        getRouter: () => {
          return {
            newConnection: (protocol, id) => {
              if (!id) {
                return Promise.rejected(new Error('rejected'));
              }

              should(protocol).be.eql(plugin.protocol);
              should(id).be.eql(emitter.id);
              connected = true;
              return Promise.resolve(connection);
            },
            execute: (token, request, conn) => {
              should(conn).be.eql(connection);
              executed = true;

              if (request.errorMe) {
                return Promise.reject(response);
              }

              return Promise.resolve(response);
            },
            removeConnection: () => {
              disconnected = true;
            }
          };
        }
      };

    beforeEach(function () {
      plugin.init({port: 1234, room: 'foo'}, context, false);
      connected = executed = disconnected = false;
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;

      should(plugin.newConnection(emitter)).be.false();
      should(connected).be.false();
    });

    it('should initialize a new connection', function () {
      plugin.newConnection(emitter);
      should(connected).be.true();
    });

    it('should listen to incoming requests and forward them to Kuzzle', function (done) {
      var payload = {fake: 'data'};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 20);
      }, 20);
    });

    it('should forward an error to clients if Kuzzle throws one', function (done) {
      var payload = {errorMe: true};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 20);
      }, 20);
    });

    it('should handle client disconnections', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('disconnect', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });

    it('should handle client socket errors', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('error', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });
  });
});
<commit_msg>upgrade timeout to eventemiter<commit_after>var
  should = require('should'),
  EventEmitter = require('events'),
  proxyquire = require('proxyquire');

describe('plugin implementation', function () {
  var
    Plugin,
    plugin,
    emitter,
    setPort,
    fakeId = 'Verbal Kint',
    destination,
    linkedChannel,
    messageSent;

  before(function () {
    // stubbing socket.io
    Plugin = proxyquire('../lib/index', {
      'socket.io': portNumber => {
        emitter = new EventEmitter();

        setPort = portNumber;

        emitter.id = fakeId;
        emitter.set = () => {};
        emitter.to = () => {
          return {
            emit: (channel, payload) => {
              messageSent = payload;
              destination = channel;
            }
          };
        };

        emitter.sockets = { connected: {} };
        emitter.sockets.connected[fakeId] = {
          join: channel => linkedChannel = channel,
          leave: channel => linkedChannel = channel
        };

        return emitter;
      }
    });
  });

  beforeEach(function () {
    setPort = -1;
    destination = null;
    messageSent = null;
    linkedChannel = null;
    plugin = new Plugin();
  });

  describe('#general', function () {
    it('should expose an init function', function () {
      should(plugin.init).be.a.Function();
    });

    it('should expose a hooks object', function () {
      var hooks = require('../lib/config/hooks');
      should(plugin.hooks).match(hooks);
    });
  });

  describe('#init', function () {
    var
      config = {port: 1234},
      context = {foo: 'bar'};

    it('should throw an error if no "config" argument has been provided', function (done) {
      try {
        plugin.init(undefined, {}, true);
        done(new Error('Expected a throw, but nothing happened'));
      }
      catch (e) {
        done();
      }
    });

    it('should fallback to dummy-mode if no port configuration has been provided', function () {
      var ret = plugin.init({}, {}, false);

      should(ret).be.false();
      should(plugin.isDummy).be.true();
    });

    it('should set internal properties correctly', function () {
      var
        ret = plugin.init(config, context, true);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.true();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(-1);
    });

    it('should start a socket.io broker if not in dummy mode', function () {
      var ret = plugin.init(config, context, false);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.false();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(1234);
    });

    it('should manage new connections on a "connection" event', function (done) {
      var
        stubSocket = { thisIsNot: 'aSocket' };

      this.timeout(50);

      plugin.newConnection = socket => {
        should(socket).be.eql(stubSocket);
        done();
      };

      plugin.init(config, context, false);
      emitter.emit('connection', stubSocket);
    });

    it('should fallback to dummy-mode if the broker is unable to start', function (done) {
      this.timeout(50);

      plugin.init(config, context, false);
      emitter.emit('error', 'fake error');
      process.nextTick(() => {
        should(plugin.isDummy).be.true();
        done();
      });
    });
  });

  describe('#broadcast', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.broadcast({channel,payload});
      should(messageSent).be.null();
      should(destination).be.null();
    });

    it('should broadcast a message correctly', function () {
      plugin.broadcast({channel,payload});
      should(messageSent).be.eql(payload);
      should(destination).be.eql(channel);
    });
  });

  describe('#joinChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.joinChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#leaveChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.leaveChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#newConnection', function () {
    // some heavy stubbing here...
    var
      connection = {foo: 'bar'},
      fakeRequestId = 'fakeRequestId',
      serializedResponse = {bar: 'foo'},
      connected,
      executed,
      disconnected,
      response = {
        toJson: () => {
          return serializedResponse;
        }
      },
      context = {
        RequestObject: function (foo) {
          foo.requestId = fakeRequestId;
          return foo;
        },
        getRouter: () => {
          return {
            newConnection: (protocol, id) => {
              if (!id) {
                return Promise.rejected(new Error('rejected'));
              }

              should(protocol).be.eql(plugin.protocol);
              should(id).be.eql(emitter.id);
              connected = true;
              return Promise.resolve(connection);
            },
            execute: (request, conn) => {
              should(conn).be.eql(connection);
              executed = true;

              if (request.errorMe) {
                return Promise.reject(response);
              }

              return Promise.resolve(response);
            },
            removeConnection: () => {
              disconnected = true;
            }
          };
        }
      };

    beforeEach(function () {
      plugin.init({port: 1234, room: 'foo'}, context, false);
      connected = executed = disconnected = false;
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;

      should(plugin.newConnection(emitter)).be.false();
      should(connected).be.false();
    });

    it('should initialize a new connection', function () {
      plugin.newConnection(emitter);
      should(connected).be.true();
    });

    it('should listen to incoming requests and forward them to Kuzzle', function (done) {
      var payload = {fake: 'data'};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 40);
      }, 20);
    });

    it('should forward an error to clients if Kuzzle throws one', function (done) {
      var payload = {errorMe: true};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 20);
      }, 20);
    });

    it('should handle client disconnections', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('disconnect', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });

    it('should handle client socket errors', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('error', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });
  });
});
<|endoftext|>


<commit_before>import * as runjs from '../lib/index';
import chalk from 'chalk';
import chProcess from 'child_process';
import {expect, spy} from 'mochaccino';

/* primitive version of run function for script testing purposes */
export function exec(cmd, options = {}){
  options.stdio = 'inherit';
  let cwd = options.cwd || '';
  console.log(chalk.yellow.bold(`RUNNING SCRIPT [${cmd}] IN [${cwd}]`));
  chProcess.execSync(cmd, options);
  console.log(chalk.yellow.bold('------'));
}

describe('run script', () => {
  const RUN = `${process.cwd()}/bin/run.js`;
  describe('in a package without any babel transpiler', () => {
    const cwd = `${process.cwd()}/test/sandbox/no-babel`;

    it('should call basic task from the runfile', () => {
      exec(`${RUN} echo 1 2 3`, {cwd});
    });
  });

  describe('in a package with pre installed babel5', () => {
    const cwd = `${process.cwd()}/test/sandbox/babel5`;

    before(() => {
      exec('npm install', {cwd});
    });

    it('should call basic task from the runfile', () => {
      exec(`${RUN} echo 1 2 3`, {cwd});
    });
  });

  describe.skip('in a package with pre installed babel6', () => {
    before(() => {

    });

    it('should call basic task from the runfile', () => {

    });
  });

  describe.skip('in a package with pre installed babel6 and .babelrc file', () => {
    before(() => {

    });

    it('should call basic task from the runfile', () => {

    });
  });
});

describe('api', () => {
  describe('.call()', () => {
    let a, b, obj, consl;
    beforeEach(() => {
      a = spy();
      b = spy();
      obj = {
        a: a,
        b: b
      };
      consl = {
        log: spy()
      };
    });

    it('should call method with given name on given object', () => {
      runjs.call(obj, ['a'], consl);
      expect(a).toHaveBeenCalled();
    });

    it('should call method with given name on given object with given arguments', () => {
      runjs.call(obj, ['b', '1', '2'], consl);
      expect(b).toHaveBeenCalledWith('1', '2');
    });

    it('should print list of all methods available in object if method name not given', () => {
      runjs.call(obj, [], consl);
      expect(consl.log).toHaveBeenCalledTimes(3);
      expect(consl.log).toHaveBeenCalledWith('Available tasks:');
      expect(consl.log).toHaveBeenCalledWith('a');
      expect(consl.log).toHaveBeenCalledWith('b');
    });

    it('should print error message if method not exist on given object', () => {
      runjs.call(obj, ['abc'], consl);
      expect(consl.log).toHaveBeenCalledTimes(1);
      expect(consl.log).toHaveBeenCalledWith(chalk.red('Task abc not found'));
    });
  });
});<commit_msg>Tests: adding done() call for long fixtures<commit_after>import * as runjs from '../lib/index';
import chalk from 'chalk';
import chProcess from 'child_process';
import {expect, spy} from 'mochaccino';

/* primitive version of run function for script testing purposes */
export function exec(cmd, options = {}){
  options.stdio = 'inherit';
  let cwd = options.cwd || '';
  console.log(chalk.yellow.bold(`RUNNING SCRIPT [${cmd}] IN [${cwd}]`));
  chProcess.execSync(cmd, options);
  console.log(chalk.yellow.bold('------'));
}

describe('run script', () => {
  const RUN = `${process.cwd()}/bin/run.js`;
  describe('in a package without any babel transpiler', () => {
    const cwd = `${process.cwd()}/test/sandbox/no-babel`;

    it('should call basic task from the runfile', () => {
      exec(`${RUN} echo 1 2 3`, {cwd});
    });
  });

  describe('in a package with pre installed babel5', () => {
    const cwd = `${process.cwd()}/test/sandbox/babel5`;

    before((done) => {
      exec('npm install', {cwd});
      done();
    });

    it('should call basic task from the runfile', () => {
      exec(`${RUN} echo 1 2 3`, {cwd});
    });
  });

  describe.skip('in a package with pre installed babel6', () => {
    before(() => {

    });

    it('should call basic task from the runfile', () => {

    });
  });

  describe.skip('in a package with pre installed babel6 and .babelrc file', () => {
    before(() => {

    });

    it('should call basic task from the runfile', () => {

    });
  });
});

describe('api', () => {
  describe('.call()', () => {
    let a, b, obj, consl;
    beforeEach(() => {
      a = spy();
      b = spy();
      obj = {
        a: a,
        b: b
      };
      consl = {
        log: spy()
      };
    });

    it('should call method with given name on given object', () => {
      runjs.call(obj, ['a'], consl);
      expect(a).toHaveBeenCalled();
    });

    it('should call method with given name on given object with given arguments', () => {
      runjs.call(obj, ['b', '1', '2'], consl);
      expect(b).toHaveBeenCalledWith('1', '2');
    });

    it('should print list of all methods available in object if method name not given', () => {
      runjs.call(obj, [], consl);
      expect(consl.log).toHaveBeenCalledTimes(3);
      expect(consl.log).toHaveBeenCalledWith('Available tasks:');
      expect(consl.log).toHaveBeenCalledWith('a');
      expect(consl.log).toHaveBeenCalledWith('b');
    });

    it('should print error message if method not exist on given object', () => {
      runjs.call(obj, ['abc'], consl);
      expect(consl.log).toHaveBeenCalledTimes(1);
      expect(consl.log).toHaveBeenCalledWith(chalk.red('Task abc not found'));
    });
  });
});<|endoftext|>


<commit_before>var clubhouseManagement = function()
{
	// load data locally for edit window
	var clubhousesInfo = [];
	var allClubhousesObjects;
	const ADDPAGE = 1;
	const EDITPAGE = 2;
	const FAIL = -1;
	var page;

	// edit page vars
	var clubToEdit;
	var edit_clubname;
	var edit_clubIndex;

	///////////////////////////////////////

     //-------------------------------------------------------------------------------------------------
     // INJECTION FOR ADDING NEW CLUBHOUSE PAGE
	var addClubhousePage={
        inputSection:
		'
'+
			'
'+
						'
'+
							'
'+
								'
הוספת מועדונית
'+
								'
'+
							'
'+
						'
 '+

						'
'+
							'<form class="form-horizontal" method="post" action="#">'+

								'
'+
									':שם מועדונית'+
									'
'+
										'
'+
											''+
											'<input type="text" class="form-control" name="clubhouseName" id="clubhouseNameID"  placeholder="הכנס שם מועדונית"/>'+
										'
'+
									'
'+
								'
'+

								'
'+
									':כתובת המועדונית'+
									'
'+
										'
'+
											''+
											'<input type="text" class="form-control" name="clubhouseAddress" id="clubhouseAddrID"  placeholder="הכנס כתובת מועדונית"/>'+
										'
'+
									'
'+
								'
'+

								'
'+

								'
'+
							'</form>'+
						'
'+

				'
'
			}

			var addClubhouseBtn={
       		 inputSection:'<button type="button" id="addClubhouseBtn" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" >הוספה</button>'+
									'
'
			}

			var editClubhouseBtn={
       		 inputSection:'<button type="button" id="editClubhouseBtn" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" >עריכה</button>'+
									'
'
			}
       //-------------------------------------------------------------------------------------------------
       //       INJECTION FOR EDIT OPTION - clubhouse and user choosing
        var EditClubhousePage={
        inputSection:
                '
'+
					'
'+
						'בחר מועדונית'+
					'
'+
					'
'+
						'
'+

						'
'+
					'
'+
					'
'+
						'<button id ="editCHbtn" type="button" class="btn btn-primary btn-block btn-lg edit-button"  >ערוך פרטי מועדונית</button>'+
						'<button id ="deleteCHbtn" type="button" class="btn-danger btn-danger btn-block btn-lg  delete-button"  >הסר מועדונית</button>'+
					'
'+
				'
'
        }

    //-------------------------------------------------------------------------------------------------
    // Initial page for add clubHouse
	 var addClubhouse = function ()
	 {
		page = ADDPAGE;
		$('.Nav').collapse('hide');
		$("#body").html(addClubhousePage.inputSection); // opens page
		$('#buttonSection').html(addClubhouseBtn.inputSection);
		$("#addClubhouseBtn").click(addClubhouseListener);
	 }
	 //-------------------------------------------------------------------------------------------------
    // Initial page for edit clubHouse
	 var editClubhouse = function()
	 {
		page = EDITPAGE;
		loadClubhousesData();
		$('.Nav').collapse('hide');
		$("#body").html(EditClubhousePage.inputSection);
        $("#editCHbtn").click(EditCluhouseListener);
		$('#deleteCHbtn').click(removeCHlistener);
	 }

	//////////////////////////////////////////////////////////////////////////
	// 					ADD CLUBHOUSE										//
	//					-------------										//
	// check if club is exist, if not - create and push to DB new clubhouse.//
	/////////////////////////////////////////////////////////////////////////
	var validateAndPush = function(nameArg,addressAarg)
	{
		var ref = firebase.database().ref("clubhouse");
		ref.once("value")
		.then(function(data)		// 		when value recieved
		{
			// in case the root is empty  ->  name is not exist
			if (data.val() == null)
				return false;

			var allClubhouses = data.val();   // get the whole tree of clubhouses
			var keys = Object.keys(allClubhouses);	// get all keys

			// loop on the answere array to find clubhouse name.
			for(var i =0; i<keys.length;i++)
			{
				var k = keys[i];
				var tempName = allClubhouses[k].name;

				if( tempName == nameArg )
					return true;
			}
			return false;

		}).then(function(res)
		{
			if(res)		// name is already exist in DB
			{
				alert("המועדונית שהוזנה כבר קיימת במערכת");
				return false;
			}
			// else - push clubhouse to DB
			var newclubhouse = clubHouse.create(nameArg,addressAarg);
			var key = firebase.database().ref('clubhouse').push(newclubhouse);
			firebase.database().ref('clubhouse/'+key.key+'/ClubhouseDBkey').set(key.key); // set key property
			return true;
		}).then(function(result){
			if(result)
				alert("מועדונית התווספה בהצלחה");
			addClubhouse();
		});
	}

	//---------------------------------------------------------------------

	var addClubhouseListener = function()
	{
		var name = 	document.getElementById("clubhouseNameID").value;
		var address = document.getElementById("clubhouseAddrID").value;
		if (name == "" || address == "" )
		{
			alert("אנא הכנס שם מועדונית וכתובת");
			return;
		}
		// check if clubhouse already exists on DB and push if not.
		validateAndPush(name,address);
	}

	//////////////////////////////////////////////////////////////
	// 		EDIT CLUBHOUSE										//
	//		-------------										//
	//////////////////////////////////////////////////////////////
	// edit button from clubhosue edit menu
	var EditCluhouseListener = function(e)
	{
		var clubRef = firebase.database().ref('clubhouse/'+clubhousesInfo[edit_clubIndex].key);
		clubRef.once("value").then(function(data)
		{
			clubToEdit = data.val();	// keep ch info
			// inject html and set listener for edit page
			$('.Nav').collapse('hide');
			$("#body").html(addClubhousePage.inputSection);
			document.getElementById('titleCH').innerHTML ="עריכת מועדונית"; // change top title
			// set inputs
			$('#clubhouseAddrID').val(data.val().address);
			$('#clubhouseNameID').val(data.val().name);
			$('#buttonSection').html(editClubhouseBtn.inputSection);
			$('#editClubhouseBtn').click(changeCHListener);
		});
	}

	var changeCHListener = function()
	{
		var obj={};
		var name = $('#clubhouseNameID').val();  //current value
		var address = $('#clubhouseAddrID').val();

		if(clubToEdit.name != name)
			obj.name = name;

		if(clubToEdit.address != address)
			obj.address = address;

		var cref = firebase.database().ref('clubhouse/');
		cref.child(clubhousesInfo[edit_clubIndex].key).update(obj);
	}

	var CHsellection = function(e)
	{
		edit_clubname = e.target.innerText;
		edit_clubIndex = getClubKeyIndex(e.target.innerText.trim());
	}

	var removeCHlistener = function()
	{
		if(!edit_clubname)
			alert('לא נבחרה מועדונית');
		else
			alert('האם אתה בטוח ?פעולה זו תמחק את כל המשתמשים');
		removeAllUsersFromCh(clubhousesInfo[edit_clubIndex].key);
		firebase.database().ref('clubhouse/'+clubhousesInfo[edit_clubIndex].key).remove()
		.then(function(res)
		{
			clubhousesInfo = [];
			editClubhouse();
		});

	}

//	 not working yet need to do!!!!!!!!
// MICHAELLLLLL
	var removeAllUsersFromCh = function(clubKey)
	{

		firebase.database().ref('clubhouse/'+clubKey+"/usersList").once("value")
		.then(function(data)
		{
			if(data.val() == null)
				return;
			var allUsers = data.val();   // get the whole tree of clubhouses
			var keys=Object.keys(allUsers);

			console.log(keys);
			for (var i = 0; i < keys.length; i++)
			{
				var uRefKey= keys[i];
				console.log(allUsers[uRefKey].userkey);
				firebase.database().ref("users/"+allUsers[uRefKey].userkey).remove();

			}

		});

	}

	// loads only strings of names for now.
	var loadClubhousesData = function()
	{
		var ref = firebase.database().ref("clubhouse");
		ref.once("value")
		.then(function(data)		// 		when value recieved
		{
			if (data.val() == null)
			{
				alert("לא נמצאו מועדוניות להציג");
				return;
			}
			allClubhousesObjects = data.val();
			var allClubhouses = data.val();   // get the whole tree of clubhouses
			var keys = Object.keys(allClubhouses);	// get all keys

			for(var i =0; i<keys.length;i++)
			{
				if(page == EDITPAGE)
				{
					clubhousesInfo[i] = {key:keys[i],name:allClubhouses[keys[i]].name};
					var tempBtnID = 'btn'+i;
					var btnInput =
					''+
					'
 '
					+clubhousesInfo[i].name+
					'';
					if ( i%3 == 2 && i>1 )
						btnInput += '
';
					$('#clubBottunGroup_edcm').append(btnInput);
					$('#'+tempBtnID).click(CHsellection);
				}
				if(page == ADDPAGE)
				{
					clubhousesInfo[i] = {key:keys[i],name:allClubhouses[keys[i]].name};
					$('#clubhouse_select').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>');
				}
			}
		});
	}

	var getClubKeyIndex = function (clubName)
	{
		for (var i = 0; i < clubhousesInfo.length; i++)
		{
			if(clubName.trim() == clubhousesInfo[i].name)
				return i;
		}
		return FAIL;
	}

	var getClubhousesInfo = function()
	{
		return{ clubhousesInfo:clubhousesInfo} ;
	}

    return{getClubhousesInfo:getClubhousesInfo  , addClubhouse:addClubhouse , editClubhouse:editClubhouse};
}();<commit_msg>remove clubhouse without removing the gen messages from the image db<commit_after>var clubhouseManagement = function()
{
	// load data locally for edit window
	var clubhousesInfo = [];
	var allClubhousesObjects;
	const ADDPAGE = 1;
	const EDITPAGE = 2;
	const FAIL = -1;
	var page;

	// edit page vars
	var clubToEdit;
	var edit_clubname;
	var edit_clubIndex;

	///////////////////////////////////////

     //-------------------------------------------------------------------------------------------------
     // INJECTION FOR ADDING NEW CLUBHOUSE PAGE
	var addClubhousePage={
        inputSection:
		'
'+
			'
'+
						'
'+
							'
'+
								'
הוספת מועדונית
'+
								'
'+
							'
'+
						'
 '+

						'
'+
							'<form class="form-horizontal" method="post" action="#">'+

								'
'+
									':שם מועדונית'+
									'
'+
										'
'+
											''+
											'<input type="text" class="form-control" name="clubhouseName" id="clubhouseNameID"  placeholder="הכנס שם מועדונית"/>'+
										'
'+
									'
'+
								'
'+

								'
'+
									':כתובת המועדונית'+
									'
'+
										'
'+
											''+
											'<input type="text" class="form-control" name="clubhouseAddress" id="clubhouseAddrID"  placeholder="הכנס כתובת מועדונית"/>'+
										'
'+
									'
'+
								'
'+

								'
'+

								'
'+
							'</form>'+
						'
'+

				'
'
			}

			var addClubhouseBtn={
       		 inputSection:'<button type="button" id="addClubhouseBtn" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" >הוספה</button>'+
									'
'
			}

			var editClubhouseBtn={
       		 inputSection:'<button type="button" id="editClubhouseBtn" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" >עריכה</button>'+
									'
'
			}
       //-------------------------------------------------------------------------------------------------
       //       INJECTION FOR EDIT OPTION - clubhouse and user choosing
        var EditClubhousePage={
        inputSection:
                '
'+
					'
'+
						'בחר מועדונית'+
					'
'+
					'
'+
						'
'+

						'
'+
					'
'+
					'
'+
						'<button id ="editCHbtn" type="button" class="btn btn-primary btn-block btn-lg edit-button"  >ערוך פרטי מועדונית</button>'+
						'<button id ="deleteCHbtn" type="button" class="btn-danger btn-danger btn-block btn-lg  delete-button"  >הסר מועדונית</button>'+
					'
'+
				'
'
        }

    //-------------------------------------------------------------------------------------------------
    // Initial page for add clubHouse
	 var addClubhouse = function ()
	 {
		page = ADDPAGE;
		$('.Nav').collapse('hide');
		$("#body").html(addClubhousePage.inputSection); // opens page
		$('#buttonSection').html(addClubhouseBtn.inputSection);
		$("#addClubhouseBtn").click(addClubhouseListener);
	 }
	 //-------------------------------------------------------------------------------------------------
    // Initial page for edit clubHouse
	 var editClubhouse = function()
	 {
		page = EDITPAGE;
		loadClubhousesData();
		$('.Nav').collapse('hide');
		$("#body").html(EditClubhousePage.inputSection);
        $("#editCHbtn").click(EditCluhouseListener);
		$('#deleteCHbtn').click(removeCHlistener);
	 }

	//////////////////////////////////////////////////////////////////////////
	// 					ADD CLUBHOUSE										//
	//					-------------										//
	// check if club is exist, if not - create and push to DB new clubhouse.//
	/////////////////////////////////////////////////////////////////////////
	var validateAndPush = function(nameArg,addressAarg)
	{
		var ref = firebase.database().ref("clubhouse");
		ref.once("value")
		.then(function(data)		// 		when value recieved
		{
			// in case the root is empty  ->  name is not exist
			if (data.val() == null)
				return false;

			var allClubhouses = data.val();   // get the whole tree of clubhouses
			var keys = Object.keys(allClubhouses);	// get all keys

			// loop on the answere array to find clubhouse name.
			for(var i =0; i<keys.length;i++)
			{
				var k = keys[i];
				var tempName = allClubhouses[k].name;

				if( tempName == nameArg )
					return true;
			}
			return false;

		}).then(function(res)
		{
			if(res)		// name is already exist in DB
			{
				alert("המועדונית שהוזנה כבר קיימת במערכת");
				return false;
			}
			// else - push clubhouse to DB
			var newclubhouse = clubHouse.create(nameArg,addressAarg);
			var key = firebase.database().ref('clubhouse').push(newclubhouse);
			firebase.database().ref('clubhouse/'+key.key+'/ClubhouseDBkey').set(key.key); // set key property
			return true;
		}).then(function(result){
			if(result)
				alert("מועדונית התווספה בהצלחה");
			addClubhouse();
		});
	}

	//---------------------------------------------------------------------

	var addClubhouseListener = function()
	{
		var name = 	document.getElementById("clubhouseNameID").value;
		var address = document.getElementById("clubhouseAddrID").value;
		if (name == "" || address == "" )
		{
			alert("אנא הכנס שם מועדונית וכתובת");
			return;
		}
		// check if clubhouse already exists on DB and push if not.
		validateAndPush(name,address);
	}

	//////////////////////////////////////////////////////////////
	// 		EDIT CLUBHOUSE										//
	//		-------------										//
	//////////////////////////////////////////////////////////////
	// edit button from clubhosue edit menu
	var EditCluhouseListener = function(e)
	{
		var clubRef = firebase.database().ref('clubhouse/'+clubhousesInfo[edit_clubIndex].key);
		clubRef.once("value").then(function(data)
		{
			clubToEdit = data.val();	// keep ch info
			// inject html and set listener for edit page
			$('.Nav').collapse('hide');
			$("#body").html(addClubhousePage.inputSection);
			document.getElementById('titleCH').innerHTML ="עריכת מועדונית"; // change top title
			// set inputs
			$('#clubhouseAddrID').val(data.val().address);
			$('#clubhouseNameID').val(data.val().name);
			$('#buttonSection').html(editClubhouseBtn.inputSection);
			$('#editClubhouseBtn').click(changeCHListener);
		});
	}

	var changeCHListener = function()
	{
		var obj={};
		var name = $('#clubhouseNameID').val();  //current value
		var address = $('#clubhouseAddrID').val();

		if(clubToEdit.name != name)
			obj.name = name;

		if(clubToEdit.address != address)
			obj.address = address;

		var cref = firebase.database().ref('clubhouse/');
		cref.child(clubhousesInfo[edit_clubIndex].key).update(obj);
	}

	var CHsellection = function(e)
	{
		edit_clubname = e.target.innerText;
		edit_clubIndex = getClubKeyIndex(e.target.innerText.trim());
	}

	var removeCHlistener = function()
	{
		if(!edit_clubname)
			alert('לא נבחרה מועדונית');
		else
			alert('האם אתה בטוח ?פעולה זו תמחק את כל המשתמשים');
		removeAllUsersFromCh(clubhousesInfo[edit_clubIndex].key);

		// var genRef=firebase.database().ref('clubhouse/'+clubhousesInfo[edit_clubIndex].key+'/generalMessages');
		// genRef.once("value").then(function(data)
		// {
		// 	if(data.val() == null)
		// 		return;
		// 	var msgs = data.val();
		// 	var mKeys = Object.keys(msgs);

		// 	for(var i=0;i<mKeys.length;i++)
		// 	{
		// 		removeAllMsgs(clubhousesInfo[edit_clubIndex].key,i);
		// 	}
			removeCH(clubhousesInfo[edit_clubIndex].key);
		//});

	}
	var removeCH = function(clubKey)
	{
		firebase.database().ref('clubhouse/'+clubKey).remove()
		.then(function(res)
		{
			clubhousesInfo = [];
			editClubhouse();
		});

	}

	var removeAllMsgs = function(clubKey,i)
	{
		var club = clubKey;
        var delMsg = firebase.database().ref("clubhouse/" + club + "/generalMessages").once("value")
        .then(function(data)
        {
            var messages = data.val();
            var keys = Object.keys(messages);

            firebase.database().ref("clubhouse/" + club + "/generalMessages/" + keys[i]).once("value")
			.then(function(data)
			{
            	var curMessage = data.val();        //  take the message object

            	if(curMessage.imageURL != -1)      // delete an image from storage
            	{
                	var storage = firebase.storage();
                	var storageRef = storage.ref();
                	var desertRef;

					if(curMessage.imageKey == -1)  // delete image to specific club
					{
					desertRef  = storageRef.child('/generalMessagesImages/' + club + '/' + curMessage.imageName);
					desertRef.delete().then(function(){}).catch(function(error){});
					}
					else
					{
						firebase.database().ref("Images/" + curMessage.imageKey).once("value")
						.then(function(data)
						{
							var details = data.val();
							if(details.capacity == 1)
							{
								desertRef  = storageRef.child('/generalMessagesImages/allClubs/' + curMessage.imageName);
								desertRef.delete().then(function(){}).catch(function(error){});
								firebase.database().ref("Images/" + curMessage.imageKey).remove();
							}
							else
							{
								var obj = {capacity:details.capacity-1};
								var imageRef = firebase.database().ref('Images/');
								imageRef.child(curMessage.imageKey).update(obj);
							}
						});

                	}
            	}
            	var deleteMsg = firebase.database().ref("clubhouse/" + club + "/generalMessages/" +keys[i]);
            	deleteMsg.remove();

           });
        });

	}

	var removeAllUsersFromCh = function(clubKey)
	{

		firebase.database().ref('clubhouse/'+clubKey+"/usersList").once("value")
		.then(function(data)
		{
			if(data.val() == null)
				return;
			var allUsers = data.val();   // get the whole tree of clubhouses
			var keys=Object.keys(allUsers);

			for (var i = 0; i < keys.length; i++)
			{
				var uRefKey= keys[i];
				firebase.database().ref("users/"+allUsers[uRefKey].userkey).remove();
			}

		});

	}

	// loads only strings of names for now.
	var loadClubhousesData = function()
	{
		var ref = firebase.database().ref("clubhouse");
		ref.once("value")
		.then(function(data)		// 		when value recieved
		{
			if (data.val() == null)
			{
				alert("לא נמצאו מועדוניות להציג");
				return;
			}
			allClubhousesObjects = data.val();
			var allClubhouses = data.val();   // get the whole tree of clubhouses
			var keys = Object.keys(allClubhouses);	// get all keys

			for(var i =0; i<keys.length;i++)
			{
				if(page == EDITPAGE)
				{
					clubhousesInfo[i] = {key:keys[i],name:allClubhouses[keys[i]].name};
					var tempBtnID = 'btn'+i;
					var btnInput =
					''+
					'
 '
					+clubhousesInfo[i].name+
					'';
					if ( i%3 == 2 && i>1 )
						btnInput += '
';
					$('#clubBottunGroup_edcm').append(btnInput);
					$('#'+tempBtnID).click(CHsellection);
				}
				if(page == ADDPAGE)
				{
					clubhousesInfo[i] = {key:keys[i],name:allClubhouses[keys[i]].name};
					$('#clubhouse_select').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>');
				}
			}
		});
	}

	var getClubKeyIndex = function (clubName)
	{
		for (var i = 0; i < clubhousesInfo.length; i++)
		{
			if(clubName.trim() == clubhousesInfo[i].name)
				return i;
		}
		return FAIL;
	}

	var getClubhousesInfo = function()
	{
		return{ clubhousesInfo:clubhousesInfo} ;
	}

    return{getClubhousesInfo:getClubhousesInfo  , addClubhouse:addClubhouse , editClubhouse:editClubhouse};
}();<|endoftext|>