<commit_before>/**
 * @file 测试用例
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

import should from 'should';
import {existsSync, readFileSync, writeFileSync, readdirSync} from 'fs';
import {removeSync, mkdirpSync} from 'fs-extra';
import {resolve, dirname} from 'path';

import KeyCache from '../src/main';
import types from './types';

describe('key-cache', () => {
    let cache = new KeyCache();

    // 每次执行完成后清空缓存
    afterEach(() => {
        cache.remove();
        removeSync('./test/temp');
    });

    it('new', () => {
        should.throws(
            () => {
                let keyCache = KeyCache;
                keyCache();
            }
        );
    });

    it('new KeyCache() check option', () => {
        should.doesNotThrow(() => {
            types.forEach(key => new KeyCache(key));
        }, 'option type error');
    });

    it('options.md5key', () => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath,
            md5key: false
        });

        let arr = [
            '中文',
            'en',
            '空格   ',
            '～！@#￥%……&*（））——',
            '~!@#$%^&*()_+',
            '{}[];"\'',
            '<>,./?\\:',
            '::::',
            '1234566'
        ];

        // 设置值
        arr.forEach((val, index) => {
            cache2.set(val, index);
        });

        // 验证目录是否存在
        existsSync(filepath).should.be.true();

        // 目录里的文件必须是数组的长度
        readdirSync(filepath).length.should.equal(arr.length);

        // 验证获取
        arr.forEach((val, index) => {
            index.should.equal(cache2.get(val));
        });
    });

    // 判断只要写入文件就算成功
    it('options.dir', () => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath
        });

        // 写入文件
        cache2.set('test', 1);

        // 必须目录存在
        existsSync(filepath).should.be.true();

        // 必须有1个文件
        readdirSync(filepath).length.should.equal(1);
    });

    it('options.timeout', done => {
        let cache2 = new KeyCache({
            timeout: 1
        });

        cache2.set('timeout', 1);

        cache2.get('timeout').should.equal(1);

        setTimeout(() => {
            cache2.get('timeout').should.equal(1);
        }, 100);

        setTimeout(() => {
            (cache2.get('timeout') === null).should.be.true();
            done();
        }, 1500);
    });

    it('get(key)', () => {
        cache.set('get(key)', 1);
        cache.get('get(key)').should.equal(1);

        types.forEach(key => {
            (cache.get(key) === null).should.be.true();
        });
    });

    it('get json parse error', () => {
        let cache = new KeyCache();

        let filepath = resolve(__dirname, './temp/notime.json');

        mkdirpSync(dirname(filepath));

        // 写个假的
        writeFileSync(filepath, JSON.stringify({
            name: 'key-cache'
        }));

        // 重写获取路径
        cache._getFilePath = () => filepath;

        (cache.get() === null).should.be.true();
    });

    it('get json error', () => {
        let cache = new KeyCache();
        let filepath = resolve('./test/temp/parseerror.json');

        mkdirpSync(dirname(filepath));

        // 写入错误文件
        writeFileSync(filepath, '{');

        // 重写获取路径
        cache._getFilePath = () => filepath;

        (cache.get() === null).should.be.true();
    });

    // 判断只要写入文件就算成功
    it('set(key, value)', () => {
        let filepath;

        // 写入文件
        cache.set('test', 1);

        cache.get('test').should.equal(1);

        // 使用内置方法读取出来路径
        filepath = cache._getFilePath('test');

        // 文件必须存在
        existsSync(filepath).should.be.true();

        // 查看是否能正常的解析
        should.doesNotThrow(() => {
            JSON.parse(readFileSync(filepath).toString());
        }, 'parse json file error');
    });

    // 判断只要写入文件就算成功
    it('set(key, value, {dir: path})', () => {
        let filepath = './test/temp/.' + Date.now();

        // 写入文件
        cache.set('test', 1, {
            dir: filepath
        });

        // 目录必须存在，并且里面文件必须有1个
        existsSync(filepath).should.be.true();
        readdirSync(filepath).length.should.equal(1);
    });

    it('set(key, value, {timeout: ""})', done => {
        cache.set('test', 1, {
            timeout: 1
        });

        cache.get('test').should.equal(1);

        // 过期时间为1m，但执行会有延迟的
        setTimeout(() => {
            cache.get('test').should.equal(1);
        }, 100);

        setTimeout(() => {
            (cache.get('test') === null).should.be.true();
            done();
        }, 1500);
    });

    it('return set()', () => {
        cache.set().should.equal(cache);
    });

    it('return set(key)', () => {
        types.forEach(key => cache.set(key).should.equal(cache));
    });

    it('return set(key, value)', () => {
        types.forEach(key => cache.set(key, key).should.equal(cache));
    });

    it('remove(key)', () => {
        cache.set('aaa', 1);

        cache.remove('aaa');

        (cache.get('aaa') === null).should.be.true();
    });

    it('remove()', () => {
        cache.set('aaa', 1);
        cache.set('bbb', 1);
        cache.set('ccc', 1);

        readdirSync(cache.options.dir).length.should.equal(3);

        cache.remove();

        readdirSync(cache.options.dir).length.should.equal(0);
    });

    it('return remove()', () => {
        cache.remove().should.equal(cache);
    });

    it('return remove(key)', () => {
        types.forEach(key => cache.remove(key).should.equal(cache));

        cache.set('key', 1);
        cache.remove('key').should.equal(cache);
    });

    it('timeout remove file', done => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath,
            timeout: 1
        });

        // 写入文件
        cache2.set('test', 1);

        setTimeout(() => {
            // 得先获取下才可以
            cache2.get('test');

            // 验证文件为空
            readdirSync(resolve(filepath)).length.should.equal(0);

            done();
        }, 1500);
    });

    it('string check', () => {
        cache.set('test', '1');
        cache.get('test').should.equal('1');
        cache.get('test').should.be.type('string');
    });

    it('boolean check', () => {
        cache.set('true', true);
        cache.set('false', false);

        cache.get('true').should.be.type('boolean');
        cache.get('true').should.equal(true);
        cache.get('false').should.equal(false);
    });

    it('number check', () => {
        cache.set('test', 1);
        cache.set('0', 0);

        cache.get('test').should.be.type('number');
        cache.get('test').should.equal(1);
        cache.get('0').should.equal(0);
    });

    it('function check', () => {
        cache.set('test', () => {});

        (cache.get('test') === null).should.be.true();
    });

    it('undefined check', () => {
        let a;
        cache.set('test', a);

        (cache.get('test') === null).should.be.true();
    });

    it('object check', () => {
        let result;
        let json = {
            status: 'ok',
            code: 0,
            flag: true,
            array: [
                0
            ]
        };

        cache.set('test', json);

        result = cache.get('test');

        result.should.eql(json);

        result.status.should.equal(json.status);
        result.code.should.equal(json.code);
        result.flag.should.equal(json.flag);
        result.array.should.eql(json.array);

        cache.set('null', null);
        (cache.get('null') === null).should.be.true();
    });
});<commit_msg>fix: 修正fecs报错<commit_after>/**
 * @file 测试用例
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

import should from 'should';
import {existsSync, readFileSync, writeFileSync, readdirSync} from 'fs';
import {removeSync, mkdirpSync} from 'fs-extra';
import {resolve, dirname} from 'path';

import KeyCache from '../src/main';
import types from './types';

describe('key-cache', () => {
    let cache = new KeyCache();

    // 每次执行完成后清空缓存
    afterEach(() => {
        cache.remove();
        removeSync('./test/temp');
    });

    it('new', () => {
        should.throws(
            () => {
                let keyCache = KeyCache;
                keyCache();
            }
        );
    });

    it('new KeyCache() check option', () => {
        should.doesNotThrow(() => {
            types.forEach(key => new KeyCache(key));
        }, 'option type error');
    });

    it('options.md5key', () => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath,
            md5key: false
        });

        let arr = [
            '中文',
            'en',
            '空格   ',
            '～！@#￥%……&*（））——',
            '~!@#$%^&*()_+',
            '{}[];"\'',
            '<>,./?\\:',
            '::::',
            '1234566'
        ];

        // 设置值
        arr.forEach((val, index) => {
            cache2.set(val, index);
        });

        // 验证目录是否存在
        existsSync(filepath).should.be.true();

        // 目录里的文件必须是数组的长度
        readdirSync(filepath).length.should.equal(arr.length);

        // 验证获取
        arr.forEach((val, index) => {
            index.should.equal(cache2.get(val));
        });
    });

    // 判断只要写入文件就算成功
    it('options.dir', () => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath
        });

        // 写入文件
        cache2.set('test', 1);

        // 必须目录存在
        existsSync(filepath).should.be.true();

        // 必须有1个文件
        readdirSync(filepath).length.should.equal(1);
    });

    it('options.timeout', done => {
        let cache2 = new KeyCache({
            timeout: 1
        });

        cache2.set('timeout', 1);

        cache2.get('timeout').should.equal(1);

        setTimeout(() => {
            cache2.get('timeout').should.equal(1);
        }, 100);

        setTimeout(() => {
            (cache2.get('timeout') === null).should.be.true();
            done();
        }, 1500);
    });

    it('get(key)', () => {
        cache.set('get(key)', 1);
        cache.get('get(key)').should.equal(1);

        types.forEach(key => {
            (cache.get(key) === null).should.be.true();
        });
    });

    it('get json parse error', () => {
        let cache = new KeyCache();

        let filepath = resolve(__dirname, './temp/notime.json');

        mkdirpSync(dirname(filepath));

        // 写个假的
        writeFileSync(filepath, JSON.stringify({
            name: 'key-cache'
        }));

        // 重写获取路径
        cache._getFilePath = () => filepath;

        (cache.get() === null).should.be.true();
    });

    it('get json error', () => {
        let cache = new KeyCache();
        let filepath = resolve('./test/temp/parseerror.json');

        mkdirpSync(dirname(filepath));

        // 写入错误文件
        writeFileSync(filepath, '{');

        // 重写获取路径
        cache._getFilePath = () => filepath;

        (cache.get() === null).should.be.true();
    });

    // 判断只要写入文件就算成功
    it('set(key, value)', () => {
        let filepath;

        // 写入文件
        cache.set('test', 1);

        cache.get('test').should.equal(1);

        // 使用内置方法读取出来路径
        filepath = cache._getFilePath('test');

        // 文件必须存在
        existsSync(filepath).should.be.true();

        // 查看是否能正常的解析
        should.doesNotThrow(() => {
            JSON.parse(readFileSync(filepath).toString());
        }, 'parse json file error');
    });

    // 判断只要写入文件就算成功
    it('set(key, value, {dir: path})', () => {
        let filepath = './test/temp/.' + Date.now();

        // 写入文件
        cache.set('test', 1, {
            dir: filepath
        });

        // 目录必须存在，并且里面文件必须有1个
        existsSync(filepath).should.be.true();
        readdirSync(filepath).length.should.equal(1);
    });

    it('set(key, value, {timeout: ""})', done => {
        cache.set('test', 1, {
            timeout: 1
        });

        cache.get('test').should.equal(1);

        // 过期时间为1m，但执行会有延迟的
        setTimeout(() => {
            cache.get('test').should.equal(1);
        }, 100);

        setTimeout(() => {
            (cache.get('test') === null).should.be.true();
            done();
        }, 1500);
    });

    it('return set()', () => {
        cache.set().should.equal(cache);
    });

    it('return set(key)', () => {
        types.forEach(key => cache.set(key).should.equal(cache));
    });

    it('return set(key, value)', () => {
        types.forEach(key => cache.set(key, key).should.equal(cache));
    });

    it('remove(key)', () => {
        cache.set('aaa', 1);

        cache.remove('aaa');

        (cache.get('aaa') === null).should.be.true();
    });

    it('remove()', () => {
        cache.set('aaa', 1);
        cache.set('bbb', 1);
        cache.set('ccc', 1);

        readdirSync(cache.options.dir).length.should.equal(3);

        cache.remove();

        readdirSync(cache.options.dir).length.should.equal(0);
    });

    it('return remove()', () => {
        cache.remove().should.equal(cache);
    });

    it('return remove(key)', () => {
        types.forEach(key => cache.remove(key).should.equal(cache));

        cache.set('key', 1);
        cache.remove('key').should.equal(cache);
    });

    it('timeout remove file', done => {
        let filepath = './test/temp/.' + Date.now();
        let cache2 = new KeyCache({
            dir: filepath,
            timeout: 1
        });

        // 写入文件
        cache2.set('test', 1);

        setTimeout(() => {
            // 得先获取下才可以
            cache2.get('test');

            // 验证文件为空
            readdirSync(resolve(filepath)).length.should.equal(0);

            done();
        }, 1500);
    });

    it('string check', () => {
        cache.set('test', '1');
        cache.get('test').should.equal('1');
        cache.get('test').should.be.type('string');
    });

    it('boolean check', () => {
        cache.set('true', true);
        cache.set('false', false);

        cache.get('true').should.be.type('boolean');
        cache.get('true').should.equal(true);
        cache.get('false').should.equal(false);
    });

    it('number check', () => {
        cache.set('test', 1);
        cache.set('0', 0);

        cache.get('test').should.be.type('number');
        cache.get('test').should.equal(1);
        cache.get('0').should.equal(0);
    });

    it('function check', () => {
        cache.set('test', () => {});

        (cache.get('test') === null).should.be.true();
    });

    it('undefined check', () => {
        let a;
        cache.set('test', a);

        (cache.get('test') === null).should.be.true();
    });

    it('object check', () => {
        let result;
        let json = {
            status: 'ok',
            code: 0,
            flag: true,
            array: [
                0
            ]
        };

        cache.set('test', json);

        result = cache.get('test');

        result.should.eql(json);

        result.status.should.equal(json.status);
        result.code.should.equal(json.code);
        result.flag.should.equal(json.flag);
        result.array.should.eql(json.array);

        cache.set('null', null);
        (cache.get('null') === null).should.be.true();
    });
});
<|endoftext|>


<commit_before>import "jsdom-global/register";
import React from "react";
import { expect } from "chai";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import ColorPicker from "../src";

Enzyme.configure({ adapter: new Adapter() });

describe("<ColorPicker /> full DOM rendering", () => {
  it("has 1 children", () => {
    const wrapper = mount(
      <ColorPicker
        color="#e56500"
        height={50}
        width={255}
        onColorChanged={() => {}}
      />
    );
    expect(wrapper.children()).to.have.length(1);
  });
  it("child has 1 child", () => {
    const wrapper = mount(
      <ColorPicker
        color="#e56500"
        height={50}
        width={255}
        onColorChanged={() => {}}
      />
    );
    expect(wrapper.childAt(0).children()).to.have.length(1);
  });
});

<commit_msg>Update deps<commit_after>import "jsdom-global/register";
import React from "react";
import { expect } from "chai";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import ColorPicker from "../src";

Enzyme.configure({ adapter: new Adapter() });

describe("<ColorPicker /> full DOM rendering", () => {
  it("has 1 children", () => {
    const wrapper = mount(
      <ColorPicker
        color="#e56500"
        height={50}
        width={255}
        onColorChanged={() => {}}
      />
    );
    expect(wrapper.children()).to.have.length(1);
  });
  it("child has 1 child", () => {
    const wrapper = mount(
      <ColorPicker
        color="#e56500"
        height={50}
        width={255}
        onColorChanged={() => {}}
      />
    );
    expect(wrapper.childAt(0).children()).to.have.length(1);
  });
});
<|endoftext|>


<commit_before>var Trie = require('../index.js'),
  rlp = require('rlp'),
  levelup = require('levelup'),
  Sha3 = require('sha3'),
  assert = require('assert');

describe('simple save and retrive', function() {

  var db1 = levelup('./testdb');
  var trie = new Trie(db1);
  it("save a value", function(done) {
    trie.put('test', 'one', function() {
      done();
    });
  });

  it("should get a value", function(done) {
    trie.get('test', function(err, value) {
      assert.equal(value.toString(), 'one');
      done();
    });
  });

  it("should update a value", function(done) {
    trie.put('test', 'two', function() {
      trie.get('test', function(err, value) {
        assert.equal(value.toString(), 'two');
        done();
      });
    });
  });

  it("should delete a value", function(done) {
    trie.del('test', function(stack) {
      trie.get('test', function(err, value) {
        console.log(value);
        done();
      });
    });
  });

  it("should recreate a value", function(done) {
    trie.put('test', 'one', function() {
      done();
    });
  });

  it("should get updated a value", function(done) {
    trie.get('test', function(err, value) {
      assert.equal(value.toString(), 'one');
      done();
    });
  });

  it("should create a branch here", function(done) {
    trie.put('doge', 'coin', function() {
      assert.equal('de8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc', trie.root);
      done();
    });
  });

  it("should get a value that is in a branch", function(done) {
    trie.get('doge', function(err, value) {
      assert.equal(value.toString(), 'coin');
      done();
    });
  });

  it("should delete from a branch", function(done) {
    trie.del('doge', function(err, stack) {
      trie.get('doge', function(err, value) {
        assert.equal(value, null);
        done();
      });
    });

  });

});

describe("storing longer values", function() {
  var db2 = levelup('./testdb2');
  var trie2 = new Trie(db2);

  var longString = 'this will be a really really really long value';
  var longStringRoot = "b173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3";

  it("should store a longer string", function(done) {
    trie2.put('done', longString, function(err, value) {
      trie2.put('doge', 'coin', function(err, value) {
        assert.equal(longStringRoot, trie2.root);
        done();
      });
    });
  });

  it("should retreive a longer value", function(done) {
    trie2.get('done', function(err, value) {
      assert.equal(value.toString(), longString);
      done();
    });
  });

  it('should when being modiefied delete the old value', function(done) {
    trie2.put('done', "test", function() {
      done();
    });
  });
});

describe("testing Extentions and branches", function() {
  var db3 = levelup('./testdb3');
  var trie3 = new Trie(db3);

  it("should store a value", function(done) {
    trie3.put('doge', 'coin', function() {
      done();
    });
  });

  it("should create extention to store this value", function(done) {
    trie3.put('do', 'verb', function() {
      assert.equal('f803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9', trie3.root);
      done();
    });
  });

  it('should store this value under the extention ', function(done) {
    trie3.put('done', 'finished', function() {
      assert.equal('409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb', trie3.root);
      done();
    });
  });

});

describe("testing Extentions and branches - reverse", function() {
  var db5 = levelup('./testdb5');
  var trie3 = new Trie(db5);

  it("should create extention to store this value", function(done) {
    trie3.put('do', 'verb', function() {
      done();
    });
  });

  it("should store a value", function(done) {
    trie3.put('doge', 'coin', function() {
      done();
    });
  });

  it('should store this value under the extention ', function(done) {
    trie3.put('done', 'finished', function() {
      assert.equal('409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb', trie3.root);
      done();
    });
  });
});

describe('testing deletions cases', function() {

  var db6 = levelup('./testdb6');
  var trie3 = new Trie(db6);

  it.skip("should delete from a branch->branch-branch", function(done) {
    trie3.put(new Buffer([11, 11, 11]), 'first', function() {
      //create the top branch
      trie3.put(new Buffer([12, 22, 22]), 'create the first branch', function() {
        //crete the middle branch
        trie3.put(new Buffer([12, 33, 33]), 'create the middle branch', function() {
          trie3.put(new Buffer([12, 34, 44]), 'create the last branch', function() {
            //delete the middle branch
            trie3.del(new Buffer([12, 22, 22]), function() {
              trie3.get(new Buffer([12, 22, 22]), function(err, val) {
                assert.equal(null, val);
                done();
              });
            });
          });
        });
      });
    });
  });

  it("should delete from a branch->branch-extention", function(done) {
    trie3.put(new Buffer([11, 11, 11]), 'first', function() {
      //create the top branch
      trie3.put(new Buffer([12, 22, 22]), 'create the first branch', function() {
        //crete the middle branch
        trie3.put(new Buffer([12, 33, 33]), 'create the middle branch', function() {
          trie3.put(new Buffer([12, 33, 44]), 'create the last branch', function() {
            //delete the middle branch
            trie3.del(new Buffer([12, 22, 22]), function() {
              trie3.get(new Buffer([12, 22, 22]), function(err, val) {
                assert.equal(null, val);
                done();
              });
            });
          });
        });
      });
    });
  });

});

describe("it should create the genesis state root from ethereum", function() {

  var db4 = levelup('./testdb4'),
    trie4 = new Trie(db4),
    g = new Buffer('8a40bfaa73256b60764c1bf40675a99083efb075', 'hex'),
    j = new Buffer('e6716f9544a56c530d868e4bfbacb172315bdead', 'hex'),
    v = new Buffer('1e12515ce3e0f817a4ddef9ca55788a1d66bd2df', 'hex'),
    a = new Buffer('1a26338f0d905e295fccb71fa9ea849ffa12aaf4', 'hex'),
    hash = new Sha3.SHA3Hash(256),
    stateRoot = new Buffer(32);

  stateRoot.fill(0);
  var startAmount = new Buffer(26);
  startAmount.fill(0);
  startAmount[0] = 1;
  var account = [startAmount, 0, stateRoot, new Buffer(hash.digest('hex'), 'hex')];
  rlpAccount = rlp.encode(account);
  cppRlp = 'f85e9a010000000000000000000000000000000000000000000000000080a00000000000000000000000000000000000000000000000000000000000000000a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';

  var genesisStateRoot = "2f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d";
  assert.equal(cppRlp, rlpAccount.toString('hex'));
  //console.log(rlpAccount.toString('hex'));

  it("shall match the root given unto us by the Master Coder Gav", function(done) {
    trie4.put(g, rlpAccount, function() {
      trie4.put(j, rlpAccount, function() {
        trie4.put(v, rlpAccount, function() {
          trie4.put(a, rlpAccount, function() {
            assert.equal(trie4.root, genesisStateRoot);
            done();
          });
        });
      });
    });
  });
});
<commit_msg>updated tests<commit_after>var Trie = require('../index.js'),
  rlp = require('rlp'),
  levelup = require('levelup'),
  Sha3 = require('sha3'),
  assert = require('assert');

describe('simple save and retrive', function() {
  var db1 = levelup('./testdb');
  var trie = new Trie(db1);
  it("save a value", function(done) {
    trie.put('test', 'one', function() {
      done();
    });
  });

  it("should get a value", function(done) {
    trie.get('test', function(err, value) {
      assert.equal(value.toString(), 'one');
      done();
    });
  });

  it("should update a value", function(done) {
    trie.put('test', 'two', function() {
      trie.get('test', function(err, value) {
        assert.equal(value.toString(), 'two');
        done();
      });
    });
  });

  it("should delete a value", function(done) {
    trie.del('test', function(stack) {
      trie.get('test', function(err, value) {
        console.log(value);
        done();
      });
    });
  });

  it("should recreate a value", function(done) {
    trie.put('test', 'one', function() {
      done();
    });
  });

  it("should get updated a value", function(done) {
    trie.get('test', function(err, value) {
      assert.equal(value.toString(), 'one');
      done();
    });
  });

  it("should create a branch here", function(done) {
    trie.put('doge', 'coin', function() {
      assert.equal('de8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc', trie.root);
      done();
    });
  });

  it("should get a value that is in a branch", function(done) {
    trie.get('doge', function(err, value) {
      assert.equal(value.toString(), 'coin');
      done();
    });
  });

  it("should delete from a branch", function(done) {
    trie.del('doge', function(err, stack) {
      trie.get('doge', function(err, value) {
        assert.equal(value, null);
        done();
      });
    });

  });

});

describe("storing longer values", function() {
  var db2 = levelup('./testdb2');
  var trie2 = new Trie(db2);

  var longString = 'this will be a really really really long value';
  var longStringRoot = "b173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3";

  it("should store a longer string", function(done) {
    trie2.put('done', longString, function(err, value) {
      trie2.put('doge', 'coin', function(err, value) {
        assert.equal(longStringRoot, trie2.root);
        done();
      });
    });
  });

  it("should retreive a longer value", function(done) {
    trie2.get('done', function(err, value) {
      assert.equal(value.toString(), longString);
      done();
    });
  });

  it('should when being modiefied delete the old value', function(done) {
    trie2.put('done', "test", function() {
      done();
    });
  });
});

describe("testing Extentions and branches", function() {
  var db3 = levelup('./testdb3');
  var trie3 = new Trie(db3);

  it("should store a value", function(done) {
    trie3.put('doge', 'coin', function() {
      done();
    });
  });

  it("should create extention to store this value", function(done) {
    trie3.put('do', 'verb', function() {
      assert.equal('f803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9', trie3.root);
      done();
    });
  });

  it('should store this value under the extention ', function(done) {
    trie3.put('done', 'finished', function() {
      assert.equal('409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb', trie3.root);
      done();
    });
  });

});

describe("testing Extentions and branches - reverse", function() {
  var db5 = levelup('./testdb5');
  var trie3 = new Trie(db5);

  it("should create extention to store this value", function(done) {
    trie3.put('do', 'verb', function() {
      done();
    });
  });

  it("should store a value", function(done) {
    trie3.put('doge', 'coin', function() {
      done();
    });
  });

  it('should store this value under the extention ', function(done) {
    trie3.put('done', 'finished', function() {
      assert.equal('409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb', trie3.root);
      done();
    });
  });
});

describe('testing deletions cases', function() {

  var db6 = levelup('./testdb6');
  var trie3 = new Trie(db6);

  it("should delete from a branch->branch-branch", function(done) {
    trie3.put(new Buffer([11, 11, 11]), 'first', function() {
      //create the top branch
      trie3.put(new Buffer([12, 22, 22]), 'create the first branch', function() {
        //crete the middle branch
        trie3.put(new Buffer([12, 33, 33]), 'create the middle branch', function() {
          trie3.put(new Buffer([12, 34, 44]), 'create the last branch', function() {
            //delete the middle branch
            trie3.del(new Buffer([12, 22, 22]), function() {
              trie3.get(new Buffer([12, 22, 22]), function(err, val) {
                assert.equal(null, val);
                done();
              });
            });
          });
        });
      });
    });
  });

  it("should delete from a branch->branch-extention", function(done) {
    trie3.put(new Buffer([11, 11, 11]), 'first', function() {
      //create the top branch
      trie3.put(new Buffer([12, 22, 22]), 'create the first branch', function() {
        //crete the middle branch
        trie3.put(new Buffer([12, 33, 33]), 'create the middle branch', function() {
          trie3.put(new Buffer([12, 33, 44]), 'create the last branch', function() {
            //delete the middle branch
            trie3.del(new Buffer([12, 22, 22]), function() {
              trie3.get(new Buffer([12, 22, 22]), function(err, val) {
                assert.equal(null, val);
                done();
              });
            });
          });
        });
      });
    });
  });

});

describe("it should create the genesis state root from ethereum", function() {

  var db4 = levelup('./testdb4'),
    trie4 = new Trie(db4),
    g = new Buffer('8a40bfaa73256b60764c1bf40675a99083efb075', 'hex'),
    j = new Buffer('e6716f9544a56c530d868e4bfbacb172315bdead', 'hex'),
    v = new Buffer('1e12515ce3e0f817a4ddef9ca55788a1d66bd2df', 'hex'),
    a = new Buffer('1a26338f0d905e295fccb71fa9ea849ffa12aaf4', 'hex'),
    hash = new Sha3.SHA3Hash(256),
    stateRoot = new Buffer(32);

  stateRoot.fill(0);
  var startAmount = new Buffer(26);
  startAmount.fill(0);
  startAmount[0] = 1;
  var account = [startAmount, 0, stateRoot, new Buffer(hash.digest('hex'), 'hex')];
  rlpAccount = rlp.encode(account);
  cppRlp = 'f85e9a010000000000000000000000000000000000000000000000000080a00000000000000000000000000000000000000000000000000000000000000000a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';

  var genesisStateRoot = "2f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d";
  assert.equal(cppRlp, rlpAccount.toString('hex'));
  //console.log(rlpAccount.toString('hex'));

  it("shall match the root given unto us by the Master Coder Gav", function(done) {
    trie4.put(g, rlpAccount, function() {
      trie4.put(j, rlpAccount, function() {
        trie4.put(v, rlpAccount, function() {
          trie4.put(a, rlpAccount, function() {
            assert.equal(trie4.root, genesisStateRoot);
            done();
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var Mocha = require('mocha'),
    fs = require('fs');

var runAcceptanceTests = function(callback){
	console.log("Running acceptance tests...");
	var acceptance = new Mocha({timeout: 60000 });

	fs.readdirSync('./test/acceptance/')
		.filter(function(file){ return file.substr(-3) === '.js';})
		.forEach(function(file){ acceptance.addFile('./test/acceptance/' + file); });

	acceptance.run(callback);
};

var runUnitTests = function(callback){
	console.log("Running unit tests...");
	var unit = new Mocha({timeout: 60000 });

	fs.readdirSync('./test/unit/')
		.filter(function(file){ return file.substr(-3) === '.js';})
		.forEach(function(file){ unit.addFile('./test/unit/' + file); });

	unit.run(callback);
};

runUnitTests(function(failures){
	if(failures)
		process.exit(failures);
	else
		runAcceptanceTests(process.exit);
});<commit_msg>Removed timeout for unit tests<commit_after>var Mocha = require('mocha'),
    fs = require('fs');

var runAcceptanceTests = function(callback){
	console.log("Running acceptance tests...");
	var acceptance = new Mocha({timeout: 60000 });

	fs.readdirSync('./test/acceptance/')
		.filter(function(file){ return file.substr(-3) === '.js';})
		.forEach(function(file){ acceptance.addFile('./test/acceptance/' + file); });

	acceptance.run(callback);
};

var runUnitTests = function(callback){
	console.log("Running unit tests...");
	var unit = new Mocha();

	fs.readdirSync('./test/unit/')
		.filter(function(file){ return file.substr(-3) === '.js';})
		.forEach(function(file){ unit.addFile('./test/unit/' + file); });

	unit.run(callback);
};

runUnitTests(function(failures){
	if(failures)
		process.exit(failures);
	else
		runAcceptanceTests(process.exit);
});<|endoftext|>


<commit_before>(function (){
"use strict";
/*jslint browser: true*/
/*global $, L*/

/**
 * A JavaScript library for using Danish Defence Center for Operational Oceanography's (FCOO)
 * Web Map Service layers without hassle.
 */
L.TileLayer.WMS.Impact = L.TileLayer.WMS.Fcoo.extend({
    //baseUrl: "http://webmap-dev01.fcoo.dk:8080/{dataset}.wms",
    baseUrl: location.protocol + "//{s}.fcoo.dk/webmap/impact/{dataset}.wms",

    onAdd: function(map) {
        L.TileLayer.WMS.prototype.onAdd.call(this, map);
        this._map = map;
        // Create or get LegendControl if it already exists
        this._legendControl = this._getLegendControl();
        // Add this layer legend to the LegendControl
        this._legendId = this._legendControl.addLegend(this, this.legendParams);
        // Add foreground layer if specified
        if (this.options.foreground !== null) {
            this.options.foreground.addTo(map);
        }
    },

    /*
     * Make an impact layer control instead of the default legend control.
     */
    _getLegendControl: function() {
        if (typeof this._map._fcoo_impactlegendcontrol == 'undefined' || !this._map._fcoo_impactlegendcontrol) {
            this._map._fcoo_impactlegendcontrol = new L.Control.Impact({
                position: this.legendParams.position,
                language: this.options.language
            });
            this._map.addControl(this._map._fcoo_impactlegendcontrol);
        }
        return this._map._fcoo_impactlegendcontrol;
    }
});

L.Control.Impact = L.Control.extend({
    options: {
        position: "bottomleft"
    },

    initialize: function(options) {
        L.Util.setOptions(this, options);
        this._container = L.DomUtil.create('div', 'fcoo-legend-container');
        //this._container.style.display = 'none';
        this._legendCounter = 0;
        this._legendContainer = [];
        this._legendType = 'impact';
        L.DomEvent.disableClickPropagation(this._container);
    },

    onAdd: function(map) {
        this._map = map;
        return this._container;
    },

    //addLegend: function(layer, legendParameters, legendImagePath, legendAttribution) {
    addLegend: function(layer, options) {
        var param;
        var legendId = this._legendCounter++;
        var name = options.name;
        if (layer._name_en !== undefined) {
            name = layer._name_en;
        }
        var legendLayer = new L.Control.Impact.LegendLayer(this._map, this._container, {
            name: name,
            layer: layer,
            attribution: options.attribution
        });
        for (param in options.parameters) {
            var paramOptions = $.extend({
                shortname: param,
                layer: layer
            },
            options.parameters[param]);
            legendLayer.addParameter(paramOptions);
        }
        this._legendContainer[legendId] = legendLayer;
        this._redrawLegend();
        this._container.style.display = 'block';
        return legendId;
    },

    removeLegend: function(legendId) {
        if (typeof this._legendContainer[legendId] != 'undefined') {
            delete this._legendContainer[legendId];
        }
        // reset counter if no legend is in collection
        if (this._legendContainer.length === 0) {
            this._legendCounter = 0;
            this._container.style.display = 'none';
        }
        this._map.off('legendupdate', this._redrawLegend, this);
        this._redrawLegend();

    },

    getUrlSettings: function() {
        /* Converts settings to URL params. */
        var params = [];
        for (var idx in this._legendContainer) {
            var llayer = this._legendContainer[idx];
            var name = llayer.options.name;
            for (var jdx in llayer._parameterContainer) {
                var param = llayer._parameterContainer[jdx];
                var isEnabled = param.options.enabled;
                if (isEnabled) {
                    var shortname = param.options.shortname;
                    params[params.length] = name + '.' + shortname;
                }
            }
        }
        return params;
    },

    _redrawLegend: function() {
        this._container.innerHTML = ''; // clear container
        for (var idx in this._legendContainer) {
            var legendLayer = this._legendContainer[idx];
            legendLayer._redrawLegendLayer(this._container, this.options.position);
        }
    }
});
L.Control.Impact.LegendParameter = L.Control.extend({
    options: {
        shortname: null,
        longname:  null,
        units: null,
        layer: null,
        baseexpr: 'a*x+b',
        enabled: true,
        sliderOptions: {},
    },

    initialize: function(map, options) {
        L.Util.setOptions(this, options);
        this._map = map;
    },

    _getExpression: function() {
        // Find y = a*x + b params
        var values = this.options.sliderOptions.values;
        var a = 80.0 / (Math.abs(values[1]) - Math.abs(values[0]));
        var b = 90.0 - a*Math.abs(values[1]);
        if (b < 0) {
            b = -b;
            b = '-' + b;
        } else {
            b = '+' + b;
        }
        var expr = this.options.baseexpr;
        if (this.options.enabled) {
            if (values[1] != values[0]) {
                expr = expr.replace('a', a).replace('+b', b)
                           .replace('x', this.options.shortname);
            } else {
                // Special handling of case where slider values equal
                if (values[0] >= 0) {
                    expr = '50*sign(' + this.options.shortname + '-' +
                           Math.abs(values[0]) +') + 50';
                } else {
                    expr = '50*sign(' + Math.abs(values[0]) + '-' +
                           this.options.shortname +') + 50';
                }
            }
        } else {
            //expr = expr.replace('a*x+b', '0*' + this.options.shortname);
            expr = expr.replace('a*x+b', '');
        }
        return expr;
    },

    _redrawLegendParameter: function(container, containerName) {
        var myParam = this; // Used in closure below
        var myMap = this._map; // Used in closure below

        // Initialize slider text
        var opr1,
            opr2;
        var sname = this.options.shortname;
        var lname = this.options.longname;
        var units = this.options.units;
        var slideroptions = this.options.sliderOptions;
        var values = slideroptions.values;
        if (values[0] > 0) {
            opr1 = '<';
            opr2 = '>';
        } else {
            opr1 = '>';
            opr2 = '<';
        }

        // Add slider for selecting parameters
        var slider_container = L.DomUtil.create('div', 'fcoo-legend-slider');
        var slider_info = L.DomUtil.create('p', 'fcoo-legend-slider-info', slider_container);
        var slider_check = $('<input type="checkbox" id="fcoo-legend-slider-enabled-' +
                             containerName + '_' + sname +
                             '" name="fcoo-legend-slider-enabled-' +
                             containerName + '_' + sname +
                             '" class="fcoo-legend-slider-enabled">');
        slider_check.attr('checked', this.options.enabled);
        $(slider_info).append(slider_check);

        slider_info.innerHTML += lname + ": ";
        var $slider_info_green = $('');
        var $slider_info_red = $('');
        $(slider_info).append($slider_info_green);
        $(slider_info).append($slider_info_red);
        var slider_div = $(L.DomUtil.create('div',
            'fcoo-legend-slider-div ui-slider-handle leaflet-control', slider_container));
        slider_div.attr("id", "fcoo-legend-slider-div-" +
                        containerName + "_" + sname);

        var slider_green = $('

');
        $slider_info_green.html(opr1 + ' ' + Math.abs(values[0]) + " " + units);
        $slider_info_red.html(opr2 + ' ' + Math.abs(values[1]) + " " + units);

        var baseoptions = {
            /*jshint unused: true*/
            slide: function(e, ui) {
            /*jshint unused: false*/
                if (ui.values[0] > 0) {
                    opr1 = '<';
                    opr2 = '>';
                } else {
                    opr1 = '>';
                    opr2 = '<';
                }
                $slider_info_green.html(opr1 + ' ' + Math.abs(ui.values[0]) + " " + units);
                $slider_info_red.html(opr2 + ' ' + Math.abs(ui.values[1]) + " " + units);
                // Update green part of slider
                slider_green.css('width', 100*(ui.values[0] -
                    slider_div.slider("option", "min"))/
                   (slider_div.slider("option", "max") -
                    slider_div.slider("option", "min")) +'%');
            },
            change: function(e, ui) {
                myParam.options.sliderOptions.values = ui.values;
                myMap.fire('legendupdate');
            }
        };
        var my_slideroptions = $.extend(baseoptions, slideroptions);
        slider_div.slider(my_slideroptions).append(slider_green);
        slider_green.css('width', 100*(slider_div.slider("values", 0) -
                                       slider_div.slider("option", "min")) /
                                      (slider_div.slider("option", "max") -
                                       slider_div.slider("option", "min")) +
                                       '%');

        $(container).append(slider_container);

        // Make it possible to enable/disable parameter
        $('body').on('click', '#fcoo-legend-slider-enabled-' + containerName + '_' + sname, function () {
            myParam.options.enabled = !myParam.options.enabled;
            myMap.fire('legendupdate');
        });

    }

});

L.Control.Impact.LegendLayer = L.Control.extend({
    options: {
        name: null,
        attribution: null,
        layer: null,
    },

    initialize: function(map, container, options) {
        L.Util.setOptions(this, options);
        this._map = map;
        this._container = container;
        this._parameterCounter = 0;
        this._parameterContainer = [];
        this._map.on('legendupdate', this._updateExpression, this);
    },

    getUrlSettings: function() {
        /* Converts settings to URL params. */
        var values = [];
        var name = this.options.name;
        for (var jdx in this._parameterContainer) {
            var param = this._parameterContainer[jdx];
            var isEnabled = param.options.enabled;
            var shortname = param.options.shortname;
            values[values.length] = name + '.' + shortname + '(' +
                param.options.sliderOptions.values[0] + '_' +
                param.options.sliderOptions.values[1] + '_' +
                isEnabled + ')';
        }
        return values;
    },

    addParameter: function(param_options) {
        var parameterId = this._parameterCounter++;
        this._parameterContainer[parameterId] =
            new L.Control.Impact.LegendParameter(this._map, param_options);
    },

    _updateExpression: function() {
        var expr = '';
        for (var idx in this._parameterContainer) {
            var paramExpr = this._parameterContainer[idx]._getExpression();
            if (expr === '') {
                expr = paramExpr;
            } else if (paramExpr !== '') {
                expr = 'fmax(' + expr + ',' + paramExpr + ')';
            }
        }
        // Only update if at least one parameter is enabled
        if (expr !== '') {
            expr = 'fmin(100,fmax(0,' + expr + '))';
            this.options.layer.setParams({expr: expr}, false, false);
        }
    },

    removeParameter: function(parameterId) {
        if (typeof this._parameterContainer[parameterId] != 'undefined') {
            delete this._parameterContainer[parameterId];
        }
        // reset counter if no parameter is in collection
        if (this._legendContainer.length === 0) {
            this._legendCounter = 0;
            this._container.style.display = 'none';
        }
    },

    _redrawLegendLayer: function() {
        var isLeft = this.options.position.indexOf('left') !== -1;
        var cssFloat = isLeft ? 'left' : 'right';
        var attribution = this.options.attribution;
        var item = L.DomUtil.create('div', 'fcoo-legend-item leaflet-control');
        item.style.cssFloat = cssFloat;
        if (isLeft) {
            item.style.marginRight = '10px';
        } else {
            item.style.marginLeft = '10px';
        }
        var title = L.DomUtil.create('p', 'fcoo-legend-item-title', item);
        var name = this.options.name;
        title.innerHTML = name;

        for (var jdx in this._parameterContainer) {
            var legendParam = this._parameterContainer[jdx];
            legendParam._redrawLegendParameter(item, name);
        }

        if (attribution !== null) {
            L.DomUtil.create('br', '', item);
            var attrelem = L.DomUtil.create('div', '', item);
            attrelem.innerHTML = attribution;
        }
        $(this._container).append(item);

        // Update the layer itself
        this._updateExpression();
    }
});

})();
<commit_msg>fixed issue with no click enabled<commit_after>(function (){
"use strict";
/*jslint browser: true*/
/*global $, L*/

/**
 * A JavaScript library for using Danish Defence Center for Operational Oceanography's (FCOO)
 * Web Map Service layers without hassle.
 */
L.TileLayer.WMS.Impact = L.TileLayer.WMS.Fcoo.extend({
    //baseUrl: "http://webmap-dev01.fcoo.dk:8080/{dataset}.wms",
    baseUrl: location.protocol + "//{s}.fcoo.dk/webmap/impact/{dataset}.wms",

    onAdd: function(map) {
        L.TileLayer.WMS.prototype.onAdd.call(this, map);
        this._map = map;
        // Create or get LegendControl if it already exists
        this._legendControl = this._getLegendControl();
        // Add this layer legend to the LegendControl
        this._legendId = this._legendControl.addLegend(this, this.legendParams);
        // Add foreground layer if specified
        if (this.options.foreground !== null) {
            this.options.foreground.addTo(map);
        }
    },

    /*
     * Make an impact layer control instead of the default legend control.
     */
    _getLegendControl: function() {
        if (typeof this._map._fcoo_impactlegendcontrol == 'undefined' || !this._map._fcoo_impactlegendcontrol) {
            this._map._fcoo_impactlegendcontrol = new L.Control.Impact({
                position: this.legendParams.position,
                language: this.options.language
            });
            this._map.addControl(this._map._fcoo_impactlegendcontrol);
        }
        return this._map._fcoo_impactlegendcontrol;
    }
});

L.Control.Impact = L.Control.extend({
    options: {
        position: "bottomleft"
    },

    initialize: function(options) {
        L.Util.setOptions(this, options);
        this._container = L.DomUtil.create('div', 'fcoo-legend-container');
        //this._container.style.display = 'none';
        this._legendCounter = 0;
        this._legendContainer = [];
        this._legendType = 'impact';
        L.DomEvent.disableClickPropagation(this._container);
    },

    onAdd: function(map) {
        this._map = map;
        return this._container;
    },

    //addLegend: function(layer, legendParameters, legendImagePath, legendAttribution) {
    addLegend: function(layer, options) {
        var param;
        var legendId = this._legendCounter++;
        var name = options.name;
        if (layer._name_en !== undefined) {
            name = layer._name_en;
        }
        var legendLayer = new L.Control.Impact.LegendLayer(this._map, this._container, {
            name: name,
            layer: layer,
            attribution: options.attribution
        });
        for (param in options.parameters) {
            var paramOptions = $.extend({
                shortname: param,
                layer: layer
            },
            options.parameters[param]);
            legendLayer.addParameter(paramOptions);
        }
        this._legendContainer[legendId] = legendLayer;
        this._redrawLegend();
        this._container.style.display = 'block';
        return legendId;
    },

    removeLegend: function(legendId) {
        if (typeof this._legendContainer[legendId] != 'undefined') {
            delete this._legendContainer[legendId];
        }
        // reset counter if no legend is in collection
        if (this._legendContainer.length === 0) {
            this._legendCounter = 0;
            this._container.style.display = 'none';
        }
        this._map.off('legendupdate', this._redrawLegend, this);
        this._redrawLegend();

    },

    getUrlSettings: function() {
        /* Converts settings to URL params. */
        var params = [];
        for (var idx in this._legendContainer) {
            var llayer = this._legendContainer[idx];
            var name = llayer.options.name;
            for (var jdx in llayer._parameterContainer) {
                var param = llayer._parameterContainer[jdx];
                var isEnabled = param.options.enabled;
                if (isEnabled) {
                    var shortname = param.options.shortname;
                    params[params.length] = name + '.' + shortname;
                }
            }
        }
        return params;
    },

    _redrawLegend: function() {
        this._container.innerHTML = ''; // clear container
        for (var idx in this._legendContainer) {
            var legendLayer = this._legendContainer[idx];
            legendLayer._redrawLegendLayer(this._container, this.options.position);
        }
    }
});
L.Control.Impact.LegendParameter = L.Control.extend({
    options: {
        shortname: null,
        longname:  null,
        units: null,
        layer: null,
        baseexpr: 'a*x+b',
        enabled: true,
        sliderOptions: {},
    },

    initialize: function(map, options) {
        L.Util.setOptions(this, options);
        this._map = map;
    },

    _getExpression: function() {
        // Find y = a*x + b params
        var values = this.options.sliderOptions.values;
        var a = 80.0 / (Math.abs(values[1]) - Math.abs(values[0]));
        var b = 90.0 - a*Math.abs(values[1]);
        if (b < 0) {
            b = -b;
            b = '-' + b;
        } else {
            b = '+' + b;
        }
        var expr = this.options.baseexpr;
        if (this.options.enabled) {
            if (values[1] != values[0]) {
                expr = expr.replace('a', a).replace('+b', b)
                           .replace('x', this.options.shortname);
            } else {
                // Special handling of case where slider values equal
                if (values[0] >= 0) {
                    expr = '50*sign(' + this.options.shortname + '-' +
                           Math.abs(values[0]) +') + 50';
                } else {
                    expr = '50*sign(' + Math.abs(values[0]) + '-' +
                           this.options.shortname +') + 50';
                }
            }
        } else {
            //expr = expr.replace('a*x+b', '0*' + this.options.shortname);
            expr = expr.replace('a*x+b', '');
        }
        return expr;
    },

    _redrawLegendParameter: function(container, containerName) {
        var myParam = this; // Used in closure below
        var myMap = this._map; // Used in closure below

        // Initialize slider text
        var opr1,
            opr2;
        var sname = this.options.shortname;
        var lname = this.options.longname;
        var units = this.options.units;
        var slideroptions = this.options.sliderOptions;
        var values = slideroptions.values;
        if (values[0] > 0) {
            opr1 = '<';
            opr2 = '>';
        } else {
            opr1 = '>';
            opr2 = '<';
        }

        // Add slider for selecting parameters
        var slider_container = L.DomUtil.create('div', 'fcoo-legend-slider');
        var slider_info = L.DomUtil.create('p', 'fcoo-legend-slider-info', slider_container);
        var containerNameSafe = containerName.replace(/ /g, '_');
        var slider_check = $('<input type="checkbox" id="fcoo-legend-slider-enabled-' +
                             containerNameSafe + '_' + sname +
                             '" name="fcoo-legend-slider-enabled-' +
                             containerNameSafe + '_' + sname +
                             '" class="fcoo-legend-slider-enabled">');
        slider_check.attr('checked', this.options.enabled);
        $(slider_info).append(slider_check);

        slider_info.innerHTML += lname + ": ";
        var $slider_info_green = $('');
        var $slider_info_red = $('');
        $(slider_info).append($slider_info_green);
        $(slider_info).append($slider_info_red);
        var slider_div = $(L.DomUtil.create('div',
            'fcoo-legend-slider-div ui-slider-handle leaflet-control', slider_container));
        slider_div.attr("id", "fcoo-legend-slider-div-" +
                        containerNameSafe + "_" + sname);

        var slider_green = $('

');
        $slider_info_green.html(opr1 + ' ' + Math.abs(values[0]) + " " + units);
        $slider_info_red.html(opr2 + ' ' + Math.abs(values[1]) + " " + units);

        var baseoptions = {
            /*jshint unused: true*/
            slide: function(e, ui) {
            /*jshint unused: false*/
                if (ui.values[0] > 0) {
                    opr1 = '<';
                    opr2 = '>';
                } else {
                    opr1 = '>';
                    opr2 = '<';
                }
                $slider_info_green.html(opr1 + ' ' + Math.abs(ui.values[0]) + " " + units);
                $slider_info_red.html(opr2 + ' ' + Math.abs(ui.values[1]) + " " + units);
                // Update green part of slider
                slider_green.css('width', 100*(ui.values[0] -
                    slider_div.slider("option", "min"))/
                   (slider_div.slider("option", "max") -
                    slider_div.slider("option", "min")) +'%');
            },
            change: function(e, ui) {
                myParam.options.sliderOptions.values = ui.values;
                myMap.fire('legendupdate');
            }
        };
        var my_slideroptions = $.extend(baseoptions, slideroptions);
        slider_div.slider(my_slideroptions).append(slider_green);
        slider_green.css('width', 100*(slider_div.slider("values", 0) -
                                       slider_div.slider("option", "min")) /
                                      (slider_div.slider("option", "max") -
                                       slider_div.slider("option", "min")) +
                                       '%');

        $(container).append(slider_container);

        // Make it possible to enable/disable parameter
        $('body').on('click', '#fcoo-legend-slider-enabled-' + containerNameSafe + '_' + sname, function () {
            myParam.options.enabled = !myParam.options.enabled;
            myMap.fire('legendupdate');
        });

    }

});

L.Control.Impact.LegendLayer = L.Control.extend({
    options: {
        name: null,
        attribution: null,
        layer: null,
    },

    initialize: function(map, container, options) {
        L.Util.setOptions(this, options);
        this._map = map;
        this._container = container;
        this._parameterCounter = 0;
        this._parameterContainer = [];
        this._map.on('legendupdate', this._updateExpression, this);
    },

    getUrlSettings: function() {
        /* Converts settings to URL params. */
        var values = [];
        var name = this.options.name;
        for (var jdx in this._parameterContainer) {
            var param = this._parameterContainer[jdx];
            var isEnabled = param.options.enabled;
            var shortname = param.options.shortname;
            values[values.length] = name + '.' + shortname + '(' +
                param.options.sliderOptions.values[0] + '_' +
                param.options.sliderOptions.values[1] + '_' +
                isEnabled + ')';
        }
        return values;
    },

    addParameter: function(param_options) {
        var parameterId = this._parameterCounter++;
        this._parameterContainer[parameterId] =
            new L.Control.Impact.LegendParameter(this._map, param_options);
    },

    _updateExpression: function() {
        var expr = '';
        for (var idx in this._parameterContainer) {
            var paramExpr = this._parameterContainer[idx]._getExpression();
            if (expr === '') {
                expr = paramExpr;
            } else if (paramExpr !== '') {
                expr = 'fmax(' + expr + ',' + paramExpr + ')';
            }
        }
        // Only update if at least one parameter is enabled
        if (expr !== '') {
            expr = 'fmin(100,fmax(0,' + expr + '))';
            this.options.layer.setParams({expr: expr}, false, false);
        }
    },

    removeParameter: function(parameterId) {
        if (typeof this._parameterContainer[parameterId] != 'undefined') {
            delete this._parameterContainer[parameterId];
        }
        // reset counter if no parameter is in collection
        if (this._legendContainer.length === 0) {
            this._legendCounter = 0;
            this._container.style.display = 'none';
        }
    },

    _redrawLegendLayer: function() {
        var isLeft = this.options.position.indexOf('left') !== -1;
        var cssFloat = isLeft ? 'left' : 'right';
        var attribution = this.options.attribution;
        var item = L.DomUtil.create('div', 'fcoo-legend-item leaflet-control');
        item.style.cssFloat = cssFloat;
        if (isLeft) {
            item.style.marginRight = '10px';
        } else {
            item.style.marginLeft = '10px';
        }
        var title = L.DomUtil.create('p', 'fcoo-legend-item-title', item);
        var name = this.options.name;
        title.innerHTML = name;

        for (var jdx in this._parameterContainer) {
            var legendParam = this._parameterContainer[jdx];
            legendParam._redrawLegendParameter(item, name);
        }

        if (attribution !== null) {
            L.DomUtil.create('br', '', item);
            var attrelem = L.DomUtil.create('div', '', item);
            attrelem.innerHTML = attribution;
        }
        $(this._container).append(item);

        // Update the layer itself
        this._updateExpression();
    }
});

})();
<|endoftext|>


<commit_before>/* global suite: false, test: false */
var assert = require('assert');
var request = require('supertest');

var app = require('../');
var appConfig = app.get('config');

suite('OPTIONS /', function () {
  test('return CORS headers', function (done) {
    request(app)
      .options('/')
      .expect('Access-Control-Allow-Origin', '*')
      .expect('Access-Control-Allow-Headers', 'X-Requested-With')
      .expect('Access-Control-Allow-Methods', 'GET')
      .expect('Access-Control-Max-Age', '86400')
      .expect(200, done);
  });
});

suite('GET /shorten', function () {
  test('checks for valid URL format', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2F')
      .expect(400, done);
  });

  test('checks for valid protocol', function (done) {
    request(app)
      .get('/shorten/ftp%3A%2F%2Fwww.test.de%2Ffoo%2Fbar%2Fbaz')
      .expect(403, done);
  });

  test('refuses to shorten too short URLs', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Ffoo.bar')
      .expect(403, done);
  });

  test('refuses request hashes when forbidden', function (done) {
    var requestHash = 'test';
    appConfig.hash.allowRequest = false;
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' + requestHash)
      .expect(403)
      .end(function (err, res) {
        appConfig.hash.allowRequest = true;
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('refuses bad request hashes', function (done) {
    var requestHash = 'this%20is%20a%20malformed%20hash';
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' + requestHash)
      .expect(400, done);
  });

  test('refuses forbidden request hashes', function (done) {
    var requestHash = 'shorten';
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' + requestHash)
      .expect(400, done);
  });

  test('refuses URL with hostname on blacklist', function (done) {
    appConfig.urlLimit.hostnameBlacklist = ['a-bad-host.name'];
    request(app)
      .get('/shorten/http%3A%2F%2Fa-bad-host.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath')
      .expect(403)
      .end(function (err, res) {
        appConfig.urlLimit.hostnameBlacklist = [];
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('refuses URL with hostname not on whitelist', function (done) {
    appConfig.urlLimit.hostnameWhitelist = ['a-known-good-host.name'];
    request(app)
      .get('/shorten/http%3A%2F%2Fanother-bad-host.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath')
      .expect(403)
      .end(function (err, res) {
        appConfig.urlLimit.hostnameWhitelist = [];
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('performs shortening', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          assert(appConfig.hash._regex.test(res.body.hash));
          assert.strictEqual(res.body.longUrl,
            'http://a-very-long-domain.name/with/an/even/longer/path');
          assert.strictEqual(res.body.url, appConfig.hash.urlPrefix +
            res.body.hash);
          return done();
        }
      });
  });

  test('performs normalization during shortening', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          var hashCanonicalUrl = res.body.hash;
          request(app)
            .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%3A80' +
                '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%23')
            .expect(200)
            .expect('Content-Type', /json/)
            .end(function (err, res) {
              if (err) {
                return done(err);
              } else {
                assert.strictEqual(hashCanonicalUrl, res.body.hash);
                request(app)
                  .get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
                      '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%3F')
                  .expect(200)
                  .expect('Content-Type', /json/)
                  .end(function (err, res) {
                    if (err) {
                      return done(err);
                    } else {
                      assert.strictEqual(hashCanonicalUrl, res.body.hash);
                      return done();
                    }
                  });
              }
            });
        }
      });
  });

  test('accepts request hashes when allowed', function (done) {
    var requestHash = 'test';
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' + requestHash)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          assert.strictEqual(requestHash, res.body.hash);
          return done();
        }
      });
  });

  test('returns text/plain (on demand)', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(new RegExp('^' + appConfig.hash.urlPrefix))
      .expect(200, done);
  });

  test('returns qrcode (on demand)', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath?format=qrcode')
      .expect('Content-Type', /image\/png/)
      .expect('Content-Length', /[0-9]{3,4}/)
      .expect(200, done);
  });
});

suite('GET|HEAD /[hash]', function () {
  var hash;

  test('GET returns 404 for unknown hash', function (done) {
    request(app)
      .get('/unkno')
      .expect(404, done);
  });

  test('GET returns permanent redirect for known hash', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request(app)
            .get('/' + hash)
            .expect('Location', 'http://a-very-long-domain.name/with/an/even' +
                '/longer/path')
            .expect(301, done);
        }
      });
  });

  test('HEAD returns 404 for unknown hash', function (done) {
    request(app)
      .head('/unkno')
      .expect(404, done);
  });

  test('HEAD returns permanent redirect for known hash', function (done) {
    request(app)
      .head('/' + hash)
      .expect('Location', 'http://a-very-long-domain.name/with/an/even' +
          '/longer/path')
      .expect(301, done);
  });
});

suite('GET /expand', function () {
  var hash;

  test('returns 404 for unknown hash', function (done) {
    request(app)
      .get('/expand/unkno')
      .expect(404, done);
  });

  test('returns long URL and hash for known hash', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request(app)
            .get('/expand/' + hash)
            .expect('Content-Type', /json/)
            .expect(200)
            .end(function (err, res) {
              if (err) {
                return done(err);
              } else {
                assert.strictEqual('http://a-very-long-domain.name/' +
                    'with/an/even/longer/path', res.body.longUrl);
                assert.strictEqual(hash, res.body.hash);
                return done();
              }
            });
        }
      });
  });

  test('returns long URL in text/plain (on demand)', function (done) {
    request(app)
      .get('/expand/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect('http://a-very-long-domain.name/with/an/even/longer/path')
      .expect(200, done);
  });

});

suite('GET /stats', function () {
  var hash;

  test('returns 404 for unknown hash', function (done) {
    request(app)
      .get('/stats/unkno')
      .expect(404, done);
  });

  test('returns stats for known hash', function (done) {
    request(app)
      .get('/shorten/http%3A%2F%2Fa-very-long-domain.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request(app)
            .get('/stats/' + hash)
            .expect('Content-Type', /json/)
            .expect(200, done);
        }
      });
  });

  test('returns clicks in text/plain (on demand)', function (done) {
    request(app)
      .get('/stats/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(/\d+/)
      .expect(200, done);
  });

  test.skip('returns actually incremented clicks', function (done) {
    this.slow(4075);
    this.timeout(5000);
    request(app)
      .get('/stats/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(200)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          var clicks = parseInt(res.text, 10);
          setTimeout(function () {
            request(app)
              .get('/' + hash)
              .expect(301)
              .end(function (err, res) {
                request(app)
                  .get('/stats/' + hash + '?format=txt')
                  .expect(200)
                  .expect('' + (clicks + 1), done);
              });
          }, 4000);
        }
      });
  });
});
<commit_msg>Use short superagent test syntax<commit_after>/* global suite: false, test: false */
var assert = require('assert');
var request = require('supertest');

var app = require('../');
var appConfig = app.get('config');

request = request(app);

suite('OPTIONS /', function () {
  test('return CORS headers', function (done) {
    request.options('/')
      .expect('Access-Control-Allow-Origin', '*')
      .expect('Access-Control-Allow-Headers', 'X-Requested-With')
      .expect('Access-Control-Allow-Methods', 'GET')
      .expect('Access-Control-Max-Age', '86400')
      .expect(200, done);
  });
});

suite('GET /shorten', function () {
  test('checks for valid URL format', function (done) {
    request.get('/shorten/http%3A%2F%2F')
      .expect(400, done);
  });

  test('checks for valid protocol', function (done) {
    request.get('/shorten/ftp%3A%2F%2Fwww.test.de%2Ffoo%2Fbar%2Fbaz')
      .expect(403, done);
  });

  test('refuses to shorten too short URLs', function (done) {
    request.get('/shorten/http%3A%2F%2Ffoo.bar')
      .expect(403, done);
  });

  test('refuses request hashes when forbidden', function (done) {
    var requestHash = 'test';
    appConfig.hash.allowRequest = false;
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' +
        requestHash)
      .expect(403)
      .end(function (err, res) {
        appConfig.hash.allowRequest = true;
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('refuses bad request hashes', function (done) {
    var requestHash = 'this%20is%20a%20malformed%20hash';
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' +
        requestHash)
      .expect(400, done);
  });

  test('refuses forbidden request hashes', function (done) {
    var requestHash = 'shorten';
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' +
        requestHash)
      .expect(400, done);
  });

  test('refuses URL with hostname on blacklist', function (done) {
    appConfig.urlLimit.hostnameBlacklist = ['a-bad-host.name'];
    request.get('/shorten/http%3A%2F%2Fa-bad-host.name%2Fwith%2Fan%2Feven' +
        '%2Flonger%2Fpath')
      .expect(403)
      .end(function (err, res) {
        appConfig.urlLimit.hostnameBlacklist = [];
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('refuses URL with hostname not on whitelist', function (done) {
    appConfig.urlLimit.hostnameWhitelist = ['a-known-good-host.name'];
    request.get('/shorten/http%3A%2F%2Fanother-bad-host.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath')
      .expect(403)
      .end(function (err, res) {
        appConfig.urlLimit.hostnameWhitelist = [];
        if (err) {
          return done(err);
        } else {
          return done();
        }
      });
  });

  test('performs shortening', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          assert(appConfig.hash._regex.test(res.body.hash));
          assert.strictEqual(res.body.longUrl,
            'http://a-very-long-domain.name/with/an/even/longer/path');
          assert.strictEqual(res.body.url, appConfig.hash.urlPrefix +
            res.body.hash);
          return done();
        }
      });
  });

  test('performs normalization during shortening', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          var hashCanonicalUrl = res.body.hash;
          request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name%3A80' +
                '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%23')
            .expect(200)
            .expect('Content-Type', /json/)
            .end(function (err, res) {
              if (err) {
                return done(err);
              } else {
                assert.strictEqual(hashCanonicalUrl, res.body.hash);
                request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
                      '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%3F')
                  .expect(200)
                  .expect('Content-Type', /json/)
                  .end(function (err, res) {
                    if (err) {
                      return done(err);
                    } else {
                      assert.strictEqual(hashCanonicalUrl, res.body.hash);
                      return done();
                    }
                  });
              }
            });
        }
      });
  });

  test('accepts request hashes when allowed', function (done) {
    var requestHash = 'test';
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%2Fand%2Fa%2Frequest%2Fhash?hash=' +
        requestHash)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          assert.strictEqual(requestHash, res.body.hash);
          return done();
        }
      });
  });

  test('returns text/plain (on demand)', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(new RegExp('^' + appConfig.hash.urlPrefix))
      .expect(200, done);
  });

  test('returns qrcode (on demand)', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath?format=qrcode')
      .expect('Content-Type', /image\/png/)
      .expect('Content-Length', /[0-9]{3,4}/)
      .expect(200, done);
  });
});

suite('GET|HEAD /[hash]', function () {
  var hash;

  test('GET returns 404 for unknown hash', function (done) {
    request.get('/unkno')
      .expect(404, done);
  });

  test('GET returns permanent redirect for known hash', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request.get('/' + hash)
            .expect('Location', 'http://a-very-long-domain.name/with/an/even' +
                '/longer/path')
            .expect(301, done);
        }
      });
  });

  test('HEAD returns 404 for unknown hash', function (done) {
    request.head('/unkno')
      .expect(404, done);
  });

  test('HEAD returns permanent redirect for known hash', function (done) {
    request.head('/' + hash)
      .expect('Location', 'http://a-very-long-domain.name/with/an/even' +
          '/longer/path')
      .expect(301, done);
  });
});

suite('GET /expand', function () {
  var hash;

  test('returns 404 for unknown hash', function (done) {
    request.get('/expand/unkno')
      .expect(404, done);
  });

  test('returns long URL and hash for known hash', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request.get('/expand/' + hash)
            .expect('Content-Type', /json/)
            .expect(200)
            .end(function (err, res) {
              if (err) {
                return done(err);
              } else {
                assert.strictEqual('http://a-very-long-domain.name/' +
                    'with/an/even/longer/path', res.body.longUrl);
                assert.strictEqual(hash, res.body.hash);
                return done();
              }
            });
        }
      });
  });

  test('returns long URL in text/plain (on demand)', function (done) {
    request.get('/expand/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect('http://a-very-long-domain.name/with/an/even/longer/path')
      .expect(200, done);
  });

});

suite('GET /stats', function () {
  var hash;

  test('returns 404 for unknown hash', function (done) {
    request.get('/stats/unkno')
      .expect(404, done);
  });

  test('returns stats for known hash', function (done) {
    request.get('/shorten/http%3A%2F%2Fa-very-long-domain.name' +
        '%2Fwith%2Fan%2Feven%2Flonger%2Fpath%3F')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          hash = res.body.hash;
          request.get('/stats/' + hash)
            .expect('Content-Type', /json/)
            .expect(200, done);
        }
      });
  });

  test('returns clicks in text/plain (on demand)', function (done) {
    request.get('/stats/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(/\d+/)
      .expect(200, done);
  });

  test.skip('returns actually incremented clicks', function (done) {
    this.slow(4075);
    this.timeout(5000);
    request.get('/stats/' + hash + '?format=txt')
      .expect('Content-Type', /text\/plain/)
      .expect(200)
      .end(function (err, res) {
        if (err) {
          return done(err);
        } else {
          var clicks = parseInt(res.text, 10);
          setTimeout(function () {
            request.get('/' + hash)
              .expect(301)
              .end(function (err, res) {
                request.get('/stats/' + hash + '?format=txt')
                  .expect(200)
                  .expect('' + (clicks + 1), done);
              });
          }, 4000);
        }
      });
  });
});
<|endoftext|>


<commit_before>var chai = require('chai'),
	should = chai.should(),
	expect = chai.expect,
	assert = chai.assert,
	mq = require('../lib');

var CONNECTION = 'mongodb://localhost:27017/mubsub_example';

describe("# ", function() {

	it('should be able to create a connection', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.close();
			done();
		})
	});

	it('should be able to create a queue', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);
				connection.close();
				done();
			});
		});
	});

	it('should be able to create a subscription', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);

				var sub = queue.subscribe('event', true, function(message) {

				});

				should.exist(sub);

				connection.close();
				done();
			});
		});
	});

	it('should be able to publish and receive a message', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
			done();
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);

				var sub = queue.subscribe('event', true, function(message) {
					expect(message).to.equal('hello');
					done();
				});

				should.exist(sub);

				queue.publish('event', 'hello');
			});
		});
	});
});
<commit_msg>Test 10 messages<commit_after>var chai = require('chai'),
	should = chai.should(),
	expect = chai.expect,
	assert = chai.assert,
	mq = require('../lib');

var CONNECTION = 'mongodb://localhost:27017/mubsub_example';

describe("# ", function() {

	it('should be able to create a connection', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.close();
			done();
		})
	});

	it('should be able to create a queue', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);
				connection.close();
				done();
			});
		});
	});

	it('should be able to create a subscription', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);

				var sub = queue.subscribe('event', true, function(message) {

				});

				should.exist(sub);

				connection.close();
				done();
			});
		});
	});

	it('should be able to publish and receive a message', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
			done();
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);

				var sub = queue.subscribe('event', true, function(message) {
					expect(message).to.equal('hello');
					connection.close();
					done();
				});

				should.exist(sub);

				queue.publish('event', 'hello');
			});
		});
	});

	it('should be able to publish and receive messages', function(done) {
		var connection = mq.createConnection(CONNECTION);

		connection.on('error', function(err) {
			should.not.exist(err);
			done();
		});

		connection.on('ready', function() {
			connection.queue('test', function(err, queue) {
				should.not.exist(err);
				should.exist(queue);

				var messages = 10;
				var received = 0;

				var sub = queue.subscribe('event', true, function(message) {
					expect(message).to.equal('hello');
					expect(received).to.be.below(messages);
					received++;
					if (received === messages) {
						connection.close();
						done();
					}
				});

				should.exist(sub);

				for (var sent = 0; sent < messages; sent++) {
					queue.publish('event', 'hello');
				}
			});
		});
	});
});
<|endoftext|>