<commit_before>import assert from 'power-assert';
import sinon  from 'sinon';
import Cmy    from '../src/cmy';
import Cmyk   from '../src/cmyk';
import Hsl    from '../src/hsl';
import Hsv    from '../src/hsv';

describe('Hsv', () => {

  describe('.constructor(h, s, v)', () => {

    it('should create an instance', () => {
      let hsv = new Hsv(60, 0.1, 0.1);
      assert(hsv !== null);
      assert.deepEqual(hsv.values(), [60, 0.1, 0.1]);
    });

  });

  describe('.prototype.clone()', () => {

    it('should create an instance', () => {
      let source = new Hsv(60, 0.1, 0.1);
      let cloned = source.clone();
      assert(cloned !== null);
      assert(cloned !== source);
      assert(cloned instanceof Hsv);
      assert.deepEqual(cloned.entries(), source.entries());
    });

  });

  describe('.prototype.cmy()', () => {

    it('should convert color space from HSV to CMY', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let cmy = hsv.cmy();
      assert(cmy !== null);
      assert(cmy instanceof Cmy);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'cmy');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let cmy = hsv.cmy();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.cmyk()', () => {

    it('should convert color space from HSV to CMYK', () => {
      let hsv  = new Hsv(60, 0.5, 0.5);
      let cmyk = hsv.cmyk();
      assert(cmyk !== null);
      assert(cmyk instanceof Cmyk);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'cmyk');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let cmyk = hsv.cmyk();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.hsl()', () => {

    it('should convert color space from HSV to HSL', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let hsl = hsv.hsl();
      assert(hsl !== null);
      assert(hsl instanceof Hsl);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'hsl');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let hsl = hsv.hsl();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.hsv()', () => {

    it('should return self', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      assert(hsv.hsv() === hsv);
    });

  });

});
<commit_msg>Added a test suite for Hsv.prototype.rgb()<commit_after>import assert from 'power-assert';
import sinon  from 'sinon';
import Cmy    from '../src/cmy';
import Cmyk   from '../src/cmyk';
import Hsl    from '../src/hsl';
import Hsv    from '../src/hsv';
import Rgb    from '../src/rgb';

describe('Hsv', () => {

  describe('.constructor(h, s, v)', () => {

    it('should create an instance', () => {
      let hsv = new Hsv(60, 0.1, 0.1);
      assert(hsv !== null);
      assert.deepEqual(hsv.values(), [60, 0.1, 0.1]);
    });

  });

  describe('.prototype.clone()', () => {

    it('should create an instance', () => {
      let source = new Hsv(60, 0.1, 0.1);
      let cloned = source.clone();
      assert(cloned !== null);
      assert(cloned !== source);
      assert(cloned instanceof Hsv);
      assert.deepEqual(cloned.entries(), source.entries());
    });

  });

  describe('.prototype.cmy()', () => {

    it('should convert color space from HSV to CMY', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let cmy = hsv.cmy();
      assert(cmy !== null);
      assert(cmy instanceof Cmy);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'cmy');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let cmy = hsv.cmy();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.cmyk()', () => {

    it('should convert color space from HSV to CMYK', () => {
      let hsv  = new Hsv(60, 0.5, 0.5);
      let cmyk = hsv.cmyk();
      assert(cmyk !== null);
      assert(cmyk instanceof Cmyk);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'cmyk');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let cmyk = hsv.cmyk();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.hsl()', () => {

    it('should convert color space from HSV to HSL', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let hsl = hsv.hsl();
      assert(hsl !== null);
      assert(hsl instanceof Hsl);
    });

    it('should delegate a color space conversion process to Rgb', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      let rgb = hsv.rgb();
      let spy = sinon.spy(rgb, 'hsl');
      sinon.stub(hsv, 'rgb').returns(rgb);
      let hsl = hsv.hsl();
      assert(spy.callCount === 1);
    });

  });

  describe('.prototype.hsv()', () => {

    it('should return self', () => {
      let hsv = new Hsv(60, 0.5, 0.5);
      assert(hsv.hsv() === hsv);
    });

  });

  describe('.prototype.hsl()', () => {

    it('should convert color space from HSV to RGB when hue is less equal than 60', () => {
      let hsv = new Hsv(0, 0.5, 0.5);
      let rgb = hsv.rgb();
      assert(rgb !== null);
      assert(rgb instanceof Rgb);
    });

    it('should convert color space from HSV to RGB when hue is greater than 60', () => {
      let hsv = new Hsv(61, 0.5, 0.5);
      let rgb = hsv.rgb();
      assert(rgb !== null);
      assert(rgb instanceof Rgb);
    });

    it('should convert color space from HSV to RGB when hue is greater than 120', () => {
      let hsv = new Hsv(121, 0.5, 0.5);
      let rgb = hsv.rgb();
      assert(rgb !== null);
      assert(rgb instanceof Rgb);
    });

  });

});
<|endoftext|>


<commit_before>/*!
    Copyright 2012 Rustici Software

    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.
*/
(function () {
    var session = null;

    module("State Statics");

    test(
        "State.fromJSON",
        function () {
            var raw = {},
                string,
                result
            ;

            result = TinCan.State.fromJSON(JSON.stringify(raw));
            ok(result instanceof TinCan.State, "returns TinCan.State");
        }
    );
}());
<commit_msg>Simple State object test coverage<commit_after>/*!
    Copyright 2012 Rustici Software

    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.
*/
(function () {
    var session = null,
        commonId = "testState",
        commonContentString = "test content";

    module("State Statics");

    test(
        "State.fromJSON",
        function () {
            var raw = {},
                string,
                result
            ;

            result = TinCan.State.fromJSON(JSON.stringify(raw));
            ok(result instanceof TinCan.State, "returns TinCan.State");
        }
    );

    module("State Instance");

    test(
        "state Object",
        function () {
            var obj = new TinCan.State (),
                nullProps = [
                    "id",
                    "contents",
                    "etag"
                ],
                i
            ;

            ok(obj instanceof TinCan.State, "object is TinCan.State");

            for (i = 0; i < nullProps.length; i += 1) {
                ok(obj.hasOwnProperty(nullProps[i]), "object has property: " + nullProps[i]);
                strictEqual(obj[nullProps[i]], null, "object property initial value: " + nullProps[i]);
            }

            ok(obj.hasOwnProperty("updated"), "object has property: updated");
            strictEqual(obj.updated, false, "object property initial value: updated");

            strictEqual(obj.LOG_SRC, "State", "object property LOG_SRC initial value");
        }
    );

    test(
        "state variants",
        function () {
            var set = [
                    {
                        name: "basic properties: string content",
                        instanceConfig: {
                            id: commonId,
                            contents: commonContentString
                        },
                        checkProps: {
                            id: commonId,
                            contents: commonContentString
                        }
                    }
                ],
                i,
                obj,
                result
            ;

            for (i = 0; i < set.length; i += 1) {
                row = set[i];
                obj = new TinCan.State (row.instanceConfig);

                ok(obj instanceof TinCan.State, "object is TinCan.State (" + row.name + ")");
                if (typeof row.checkProps !== "undefined") {
                    for (key in row.checkProps) {
                        deepEqual(obj[key], row.checkProps[key], "object property initial value: " + key + " (" + row.name + ")");
                    }
                }
            }
        }
    );
}());
<|endoftext|>


<commit_before>'use strict';

var Xmpp   = require('../../index').Xmpp
  , should = require('should')
  , events = require('events')
  , ltx    = require('ltx')

/* jshint -W030 */
describe('FTW', function() {

    var ftw, socket

    before(function() {
        socket = new events.EventEmitter()
        ftw = new Xmpp(socket)
    })

    describe('Returns JID parts', function() {

        beforeEach(function() {
            ftw.fullJid = {
                user: 'marty',
                domain: 'mcfly',
                resource: 'thefuture'
            }
        })

        it('Returns full JID', function() {
            ftw.getJidType('full').should.equal(
                ftw.fullJid.user + '@' +
                ftw.fullJid.domain + '/' +
                ftw.fullJid.resource
            )
        })

        it('Returns bare JID', function() {
            ftw.getJidType('bare').should.equal(
                ftw.fullJid.user + '@' +
                ftw.fullJid.domain
            )
        })

        it('Returns domain', function() {
            ftw.getJidType('domain').should.equal(
                ftw.fullJid.domain
            )
        })

        it('Returns undefined for unknown JID part type', function() {
            should.not.exist(ftw.getJidType('all'))
        })

    })

    describe.only('Tracking IDs', function() {

        it('Should accept an ID and capture', function(done) {
            var stanza = ltx.parse('<iq id="1" />')
            ftw.trackId('1', function(payload) {
                payload.should.eql(stanza)
                done()
            })
            ftw.catchTracked(stanza).should.be.true
        })

        it('Should return false if untracked ID', function() {
            var stanza = ltx.parse('<iq id="2" />')
            ftw.trackId('1', function() {})
            ftw.catchTracked(stanza).should.be.false
        })

        it.skip('Should return false if no ID attribute', function() {

        })

        it.skip('Should accept a stanza and capture', function() {

        })

        it.skip('Should append an ID if none provided', function() {
            // REALLY ?
            // No! This is added in the base class
            // What do I do if no ID attribute? Throw exception?
        })

    })

})
<commit_msg>Passed test for stanza with no id attribute<commit_after>'use strict';

var Xmpp   = require('../../index').Xmpp
  , should = require('should')
  , events = require('events')
  , ltx    = require('ltx')

/* jshint -W030 */
describe('FTW', function() {

    var ftw, socket

    before(function() {
        socket = new events.EventEmitter()
        ftw = new Xmpp(socket)
    })

    describe('Returns JID parts', function() {

        beforeEach(function() {
            ftw.fullJid = {
                user: 'marty',
                domain: 'mcfly',
                resource: 'thefuture'
            }
        })

        it('Returns full JID', function() {
            ftw.getJidType('full').should.equal(
                ftw.fullJid.user + '@' +
                ftw.fullJid.domain + '/' +
                ftw.fullJid.resource
            )
        })

        it('Returns bare JID', function() {
            ftw.getJidType('bare').should.equal(
                ftw.fullJid.user + '@' +
                ftw.fullJid.domain
            )
        })

        it('Returns domain', function() {
            ftw.getJidType('domain').should.equal(
                ftw.fullJid.domain
            )
        })

        it('Returns undefined for unknown JID part type', function() {
            should.not.exist(ftw.getJidType('all'))
        })

    })

    describe.only('Tracking IDs', function() {

        it('Should accept an ID and capture', function(done) {
            var stanza = ltx.parse('<iq id="1" />')
            ftw.trackId('1', function(payload) {
                payload.should.eql(stanza)
                done()
            })
            ftw.catchTracked(stanza).should.be.true
        })

        it('Should return false if untracked ID', function() {
            var stanza = ltx.parse('<iq id="2" />')
            ftw.trackId('1', function() {})
            ftw.catchTracked(stanza).should.be.false
        })

        it('Should return false if no ID attribute', function() {
            var stanza = ltx.parse('<iq />')
            ftw.trackId('1', function() {})
            ftw.catchTracked(stanza).should.be.false
        })

        it.skip('Should accept a stanza and capture', function() {

        })

        it.skip('Should append an ID if none provided', function() {
            // REALLY ?
            // No! This is added in the base class
            // What do I do if no ID attribute? Throw exception?
        })

    })

})
<|endoftext|>


<commit_before>/* eslint-env mocha */

import chai from 'chai'
import chaiBytes from 'chai-bytes'
import dirtyChai from 'dirty-chai'

import types from '../src/std'
import { hash } from '../src/crypto'
import { isExonumType } from '../src/lowlevel/common'

import samples from './data/listView.json'

const expect = chai
  .use(chaiBytes)
  .use(dirtyChai)
  .expect

const ListView = types.ListView

describe('ListView', () => {
  const StrListView = ListView('Str')

  describe('factory', () => {
    it('should create type', () => {
      expect(StrListView).to.satisfy(isExonumType)
      expect(StrListView.meta().factoryName).to.equal('ListView')
      expect(StrListView.meta().element).to.equal(types.Str)
    })
  })

  describe('constructor', () => {
    it('should parse list views', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.count()).to.equal(2)
      expect(view.get(0)).to.equal('foo')
      expect(view.get(1)).to.equal('bar')
      expect(view.has(0)).to.be.true()
      expect(view.has(2)).to.be.false()
    })

    it('should not parse list view with redefined entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '0', value: 'bar' }
        ],
        proof: []
      })).to.throw(/Redefined entry in list view proof/i)
    })

    it('should not parse list view with redefined proof entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 1, hash: '0000000000000000000000000000000000000000000000000000000000000000' },
          { height: 1, index: 1, hash: '1000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)
    })

    it('should not parse list view with entries colliding with proof entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 1, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 2, index: 0, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 10, index: 0, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Entry in list view proof past tree root.*height 10/)
    })

    it('should not parse list view with insufficient information to construct root hash', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '2', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '3', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '1', value: 'bar' },
          { key: '2', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '1000', value: 'bar' },
          { key: '1001', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)
    })

    it('should not parse list view with entries in proof conflicting with discovered stub', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '4', value: 'bar' }
        ],
        proof: [
          { height: 3, index: 0, hash: hash(new Uint8Array(10)) },
          { height: 3, index: 2, hash: hash(new Uint8Array(20)) }
        ]
      })).to.throw(/Unexpected entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '4', value: 'bar' },
          { key: '5', value: 'foo' }
        ],
        proof: [
          { height: 3, index: 0, hash: hash(new Uint8Array(10)) },
          { height: 3, index: 3, hash: hash(new Uint8Array(20)) }
        ]
      })).to.throw(/Unexpected entry in list view proof/i)
    })
  })

  describe('hash', () => {
    it('should calculate hash correctly for a single-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(types.Str.from('foo')))
    })

    it('should calculate hash correctly for a 2-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(types.Str.from('foo')),
        hash(types.Str.from('bar'))
      ))
    })

    it('should calculate hash correctly for a 3-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '2', value: 'bazz' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(
          hash(types.Str.from('foo')),
          hash(types.Str.from('bar'))
        ),
        hash(hash(types.Str.from('bazz')))
      ))
    })

    it('should calculate hash correctly for a 4-node tree with a single entry in proof', () => {
      const view = StrListView.from({
        entries: [
          { key: '2', value: 'bazz' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 0, hash: hash(types.Str.from('foo')) },
          { height: 1, index: 3, hash: hash(types.Str.from('foobar')) }
        ]
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(
          hash(types.Str.from('foo')),
          hash(types.Str.from('bar'))
        ),
        hash(
          hash(types.Str.from('bazz')),
          hash(types.Str.from('foobar'))
        )
      ))
    })

    it('should calculate hash correctly for a 5-node tree with a full stub path', () => {
      const h1to4 = hash(
        hash(
          hash(types.Str.from('item0')),
          hash(types.Str.from('item1'))
        ),
        hash(
          hash(types.Str.from('item2')),
          hash(types.Str.from('item3'))
        )
      )
      const rootHash = hash(
        h1to4,
        hash(hash(hash(types.Str.from('item4'))))
      )

      const view = StrListView.from({
        entries: [
          { key: '4', value: 'item4' }
        ],
        proof: [
          { height: 3, index: 0, hash: h1to4 }
        ]
      })

      expect(view.hash()).to.equalBytes(rootHash)
    })
  })

  function testValidSample (sampleName) {
    describe(`on sample ${sampleName}`, () => {
      const sample = samples[sampleName]
      const expected = sample.expected
      const json = sample.data
      const elementLength = expected.elementLength || expected.elements[0].length
      const LView = ListView({ fixedBuffer: elementLength })
      let lst

      it(`should parse valid list view from sample`, () => {
        lst = new LView(json)
        expect(lst.keySeq().first()).to.equal(expected.rangeStart)
        expect(lst.keySeq().last()).to.equal(expected.rangeEnd - 1)
        expect(lst.keySeq().count()).to.equal(expected.rangeEnd - expected.rangeStart)
      })

      if (expected.elements) {
        it('should correctly determine elements', () => {
          let i = 0
          lst.valueSeq().forEach(val => {
            expect(val).to.equalBytes(expected.elements[i++])
          })
        })
      }

      it('should calculate correct root hash', () => {
        expect(lst.hash()).to.equalBytes(expected.rootHash)
      })
    })
  }

  function testInvalidSample (sampleName, expectedError) {
    it(`should fail on sample ${sampleName}`, () => {
      const sample = samples[sampleName]
      const elementLength = sample.expected.elementLength
      const json = sample.data

      const LView = ListView({ fixedBuffer: elementLength })

      expect(() => new LView(json)).to.throw(expectedError)
    })
  }

  testValidSample('valid-10')
  testValidSample('valid-short')
  testValidSample('valid-full')
  testValidSample('valid-many-elements')

  testInvalidSample('invalid-stub-placement', /Entry in list view proof past tree root/i)
})
<commit_msg>Test for `ListView.getOriginal()`<commit_after>/* eslint-env mocha */

import chai from 'chai'
import chaiBytes from 'chai-bytes'
import dirtyChai from 'dirty-chai'

import types from '../src/std'
import { hash } from '../src/crypto'
import { isExonumType, isExonumObject } from '../src/lowlevel/common'

import samples from './data/listView.json'

const expect = chai
  .use(chaiBytes)
  .use(dirtyChai)
  .expect

const ListView = types.ListView

describe('ListView', () => {
  const StrListView = ListView('Str')

  describe('factory', () => {
    it('should create type', () => {
      expect(StrListView).to.satisfy(isExonumType)
      expect(StrListView.meta().factoryName).to.equal('ListView')
      expect(StrListView.meta().element).to.equal(types.Str)
    })
  })

  describe('constructor', () => {
    it('should parse list views', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.count()).to.equal(2)
      expect(view.get(0)).to.equal('foo')
      expect(view.get(1)).to.equal('bar')
      expect(view.getOriginal(0)).to.satisfy(isExonumObject)
      expect(view.getOriginal(1).toJSON()).to.equal('bar')
      expect(view.has(0)).to.be.true()
      expect(view.has(2)).to.be.false()
    })

    it('should not parse list view with redefined entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '0', value: 'bar' }
        ],
        proof: []
      })).to.throw(/Redefined entry in list view proof/i)
    })

    it('should not parse list view with redefined proof entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 1, hash: '0000000000000000000000000000000000000000000000000000000000000000' },
          { height: 1, index: 1, hash: '1000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)
    })

    it('should not parse list view with entries colliding with proof entries', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 1, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 2, index: 0, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Redefined entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 10, index: 0, hash: '0000000000000000000000000000000000000000000000000000000000000000' }
        ]
      })).to.throw(/Entry in list view proof past tree root.*height 10/)
    })

    it('should not parse list view with insufficient information to construct root hash', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '2', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '3', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '1', value: 'bar' },
          { key: '2', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '1000', value: 'bar' },
          { key: '1001', value: 'bar' }
        ],
        proof: [ ]
      })).to.throw(/Missing entry in list view proof/i)
    })

    it('should not parse list view with entries in proof conflicting with discovered stub', () => {
      expect(() => StrListView.from({
        entries: [
          { key: '4', value: 'bar' }
        ],
        proof: [
          { height: 3, index: 0, hash: hash(new Uint8Array(10)) },
          { height: 3, index: 2, hash: hash(new Uint8Array(20)) }
        ]
      })).to.throw(/Unexpected entry in list view proof/i)

      expect(() => StrListView.from({
        entries: [
          { key: '4', value: 'bar' },
          { key: '5', value: 'foo' }
        ],
        proof: [
          { height: 3, index: 0, hash: hash(new Uint8Array(10)) },
          { height: 3, index: 3, hash: hash(new Uint8Array(20)) }
        ]
      })).to.throw(/Unexpected entry in list view proof/i)
    })
  })

  describe('hash', () => {
    it('should calculate hash correctly for a single-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(types.Str.from('foo')))
    })

    it('should calculate hash correctly for a 2-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(types.Str.from('foo')),
        hash(types.Str.from('bar'))
      ))
    })

    it('should calculate hash correctly for a 3-node tree', () => {
      const view = StrListView.from({
        entries: [
          { key: '0', value: 'foo' },
          { key: '2', value: 'bazz' },
          { key: '1', value: 'bar' }
        ],
        proof: []
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(
          hash(types.Str.from('foo')),
          hash(types.Str.from('bar'))
        ),
        hash(hash(types.Str.from('bazz')))
      ))
    })

    it('should calculate hash correctly for a 4-node tree with a single entry in proof', () => {
      const view = StrListView.from({
        entries: [
          { key: '2', value: 'bazz' },
          { key: '1', value: 'bar' }
        ],
        proof: [
          { height: 1, index: 0, hash: hash(types.Str.from('foo')) },
          { height: 1, index: 3, hash: hash(types.Str.from('foobar')) }
        ]
      })

      expect(view.hash()).to.equalBytes(hash(
        hash(
          hash(types.Str.from('foo')),
          hash(types.Str.from('bar'))
        ),
        hash(
          hash(types.Str.from('bazz')),
          hash(types.Str.from('foobar'))
        )
      ))
    })

    it('should calculate hash correctly for a 5-node tree with a full stub path', () => {
      const h1to4 = hash(
        hash(
          hash(types.Str.from('item0')),
          hash(types.Str.from('item1'))
        ),
        hash(
          hash(types.Str.from('item2')),
          hash(types.Str.from('item3'))
        )
      )
      const rootHash = hash(
        h1to4,
        hash(hash(hash(types.Str.from('item4'))))
      )

      const view = StrListView.from({
        entries: [
          { key: '4', value: 'item4' }
        ],
        proof: [
          { height: 3, index: 0, hash: h1to4 }
        ]
      })

      expect(view.hash()).to.equalBytes(rootHash)
    })
  })

  function testValidSample (sampleName) {
    describe(`on sample ${sampleName}`, () => {
      const sample = samples[sampleName]
      const expected = sample.expected
      const json = sample.data
      const elementLength = expected.elementLength || expected.elements[0].length
      const LView = ListView({ fixedBuffer: elementLength })
      let lst

      it(`should parse valid list view from sample`, () => {
        lst = new LView(json)
        expect(lst.keySeq().first()).to.equal(expected.rangeStart)
        expect(lst.keySeq().last()).to.equal(expected.rangeEnd - 1)
        expect(lst.keySeq().count()).to.equal(expected.rangeEnd - expected.rangeStart)
      })

      if (expected.elements) {
        it('should correctly determine elements', () => {
          let i = 0
          lst.valueSeq().forEach(val => {
            expect(val).to.equalBytes(expected.elements[i++])
          })
        })
      }

      it('should calculate correct root hash', () => {
        expect(lst.hash()).to.equalBytes(expected.rootHash)
      })
    })
  }

  function testInvalidSample (sampleName, expectedError) {
    it(`should fail on sample ${sampleName}`, () => {
      const sample = samples[sampleName]
      const elementLength = sample.expected.elementLength
      const json = sample.data

      const LView = ListView({ fixedBuffer: elementLength })

      expect(() => new LView(json)).to.throw(expectedError)
    })
  }

  testValidSample('valid-10')
  testValidSample('valid-short')
  testValidSample('valid-full')
  testValidSample('valid-many-elements')

  testInvalidSample('invalid-stub-placement', /Entry in list view proof past tree root/i)
})
<|endoftext|>


<commit_before>var MemoryStore = require('../memory-store')
var Log = require('../log')

function createLog () {
  return new Log({
    nodeId: 'test',
    store: new MemoryStore()
  })
}

function checkActions (log, expected) {
  var actions = log.store.created.map(function (entry) {
    return entry[0]
  })
  expect(actions).toEqual(expected)
}

function checkEntries (log, expected) {
  var entries = log.store.created.map(function (entry) {
    return [entry[0], entry[1]]
  })
  expect(entries).toEqual(expected)
}

function logWith (entries) {
  var log = createLog()
  return Promise.all(entries.map(function (entry) {
    if (entry.length) {
      return log.add(entry[0], entry[1])
    } else {
      return log.add(entry)
    }
  })).then(function () {
    return log
  })
}

it('requires node ID', function () {
  expect(function () {
    new Log()
  }).toThrowError(/node ID/)
})

it('requires store', function () {
  expect(function () {
    new Log({ nodeId: 'test' })
  }).toThrowError(/Logux store/)
})

it('requires type for action', function () {
  var log = createLog()
  expect(function () {
    log.add({ a: 1 })
  }).toThrowError(/type/)
})

it('sends new entries to listeners', function () {
  var log = createLog()
  var actions1 = []
  var actions2 = []

  return log.add({ type: 'a' }).then(function () {
    log.on('add', function (action, meta) {
      expect(typeof meta).toEqual('object')
      actions1.push(action)
    })

    log.on('add', function (action) {
      actions2.push(action)
    })

    expect(actions1).toEqual([])
    expect(actions2).toEqual([])

    return log.add({ type: 'b' })
  }).then(function () {
    return log.add({ type: 'c' })
  }).then(function () {
    expect(actions1).toEqual([{ type: 'b' }, { type: 'c' }])
    expect(actions2).toEqual(actions1)
  })
})

it('supports one-time listeners', function () {
  var log = createLog()

  var actions = []
  log.once('add', function (action) {
    actions.push(action)
  })

  return log.add({ type: 'b' }).then(function () {
    return log.add({ type: 'c' })
  }).then(function () {
    expect(actions).toEqual([{ type: 'b' }])
  })
})

it('unsubscribes listeners', function () {
  var log = createLog()

  var actions = []
  var unsubscribe = log.on('add', function (action) {
    actions.push(action)
  })

  return log.add({ type: 'a' }).then(function () {
    unsubscribe()
    return log.add({ type: 'b' })
  }).then(function () {
    expect(actions).toEqual([{ type: 'a' }])
  })
})

it('ignore existed ID', function () {
  var log = createLog()

  var added = []
  log.on('add', function (action) {
    added.push(action)
  })

  return log.add({ type: 'a' }, { id: [0] }).then(function (result1) {
    expect(typeof result1).toEqual('object')
    return log.add({ type: 'b' }, { id: [0] })
  }).then(function (result2) {
    expect(result2).toBeFalsy()
    checkActions(log, [{ type: 'a' }])
    expect(added).toEqual([{ type: 'a' }])
  })
})

it('iterates through added entries', function () {
  return logWith([
    [{ type: 'a' }, { id: [3] }],
    [{ type: 'b' }, { id: [2] }],
    [{ type: 'c' }, { id: [1] }]
  ]).then(function (log) {
    var entries = []
    return log.each(function (action, meta) {
      entries.push([action, meta])
    }).then(function () {
      expect(entries).toEqual([
        [{ type: 'a' }, { id: [3], time: 3, added: 1 }],
        [{ type: 'b' }, { id: [2], time: 2, added: 2 }],
        [{ type: 'c' }, { id: [1], time: 1, added: 3 }]
      ])
    })
  })
})

it('iterates by added order', function () {
  return logWith([
    [{ type: 'a' }, { id: [3] }],
    [{ type: 'b' }, { id: [2] }],
    [{ type: 'c' }, { id: [1] }]
  ]).then(function (log) {
    var actions = []
    return log.each({ order: 'added' }, function (action) {
      actions.push(action)
    }).then(function () {
      expect(actions).toEqual([
        { type: 'c' },
        { type: 'b' },
        { type: 'a' }
      ])
    })
  })
})

it('disables iteration on false', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    var actions = []
    return log.each(function (action) {
      actions.push(action)
      return false
    }).then(function () {
      expect(actions).toEqual([{ type: 'b' }])
    })
  })
})

it('supports multi-pages stores', function () {
  var store = {
    get: function () {
      return Promise.resolve({
        entries: [['a', 'a']],
        next: function () {
          return Promise.resolve({ entries: [['b', 'b']] })
        }
      })
    }
  }
  var log = new Log({ nodeId: 'test', store: store })

  var actions = []
  return log.each(function (action) {
    actions.push(action)
  }).then(function () {
    expect(actions).toEqual(['a', 'b'])
  })
})

it('keeps existed ID', function () {
  return logWith([
    [{ type: 'timed' }, { id: [100] }]
  ]).then(function (log) {
    checkEntries(log, [
      [{ type: 'timed' }, { id: [100], time: 100, added: 1 }]
    ])
  })
})

it('keeps existed ID and time', function () {
  return logWith([
    [{ type: 'timed' }, { id: [100], time: 1 }]
  ]).then(function (log) {
    checkEntries(log, [
      [{ type: 'timed' }, { id: [100], time: 1, added: 1 }]
    ])
  })
})

it('sets ID and time for timeless entries', function () {
  var log = createLog()
  return log.add({ type: 'timeless' }).then(function (meta) {
    expect(meta).toEqual(log.store.created[0][1])
    expect(meta.added).toEqual(1)
    expect(typeof meta.time).toEqual('number')
    expect(meta.id.length).toEqual(3)
    expect(meta.id[0]).toEqual(meta.time)
    expect(meta.id[1]).toEqual('test')
    expect(meta.id[2]).toEqual(0)
  })
})

it('cleans entries', function () {
  return logWith([
    { type: 'a' }
  ]).then(function (log) {
    return log.clean().then(function () {
      checkEntries(log, [])
    })
  })
})

it('keeps entries from cleaning', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    log.keep(function (action) {
      return action.type === 'b'
    })
    return log.clean().then(function () {
      checkActions(log, [{ type: 'b' }])
    })
  })
})

it('removes keeper', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    var unkeep = log.keep(function (action) {
      return action.type === 'b'
    })
    return log.clean().then(function () {
      checkActions(log, [{ type: 'b' }])
      unkeep()
      return log.clean()
    }).then(function () {
      checkActions(log, [])
    })
  })
})

it('does not fall on multiple unkeep call', function () {
  var log = createLog()
  var unkeep = log.keep(function () { })
  unkeep()
  unkeep()
})
<commit_msg>Add ID uniqueness test<commit_after>var MemoryStore = require('../memory-store')
var Log = require('../log')

function createLog () {
  return new Log({
    nodeId: 'test',
    store: new MemoryStore()
  })
}

function checkActions (log, expected) {
  var actions = log.store.created.map(function (entry) {
    return entry[0]
  })
  expect(actions).toEqual(expected)
}

function checkEntries (log, expected) {
  var entries = log.store.created.map(function (entry) {
    return [entry[0], entry[1]]
  })
  expect(entries).toEqual(expected)
}

function logWith (entries) {
  var log = createLog()
  return Promise.all(entries.map(function (entry) {
    if (entry.length) {
      return log.add(entry[0], entry[1])
    } else {
      return log.add(entry)
    }
  })).then(function () {
    return log
  })
}

it('requires node ID', function () {
  expect(function () {
    new Log()
  }).toThrowError(/node ID/)
})

it('requires store', function () {
  expect(function () {
    new Log({ nodeId: 'test' })
  }).toThrowError(/Logux store/)
})

it('requires type for action', function () {
  var log = createLog()
  expect(function () {
    log.add({ a: 1 })
  }).toThrowError(/type/)
})

it('sends new entries to listeners', function () {
  var log = createLog()
  var actions1 = []
  var actions2 = []

  return log.add({ type: 'a' }).then(function () {
    log.on('add', function (action, meta) {
      expect(typeof meta).toEqual('object')
      actions1.push(action)
    })

    log.on('add', function (action) {
      actions2.push(action)
    })

    expect(actions1).toEqual([])
    expect(actions2).toEqual([])

    return log.add({ type: 'b' })
  }).then(function () {
    return log.add({ type: 'c' })
  }).then(function () {
    expect(actions1).toEqual([{ type: 'b' }, { type: 'c' }])
    expect(actions2).toEqual(actions1)
  })
})

it('supports one-time listeners', function () {
  var log = createLog()

  var actions = []
  log.once('add', function (action) {
    actions.push(action)
  })

  return log.add({ type: 'b' }).then(function () {
    return log.add({ type: 'c' })
  }).then(function () {
    expect(actions).toEqual([{ type: 'b' }])
  })
})

it('unsubscribes listeners', function () {
  var log = createLog()

  var actions = []
  var unsubscribe = log.on('add', function (action) {
    actions.push(action)
  })

  return log.add({ type: 'a' }).then(function () {
    unsubscribe()
    return log.add({ type: 'b' })
  }).then(function () {
    expect(actions).toEqual([{ type: 'a' }])
  })
})

it('ignore existed ID', function () {
  var log = createLog()

  var added = []
  log.on('add', function (action) {
    added.push(action)
  })

  return log.add({ type: 'a' }, { id: [0] }).then(function (result1) {
    expect(typeof result1).toEqual('object')
    return log.add({ type: 'b' }, { id: [0] })
  }).then(function (result2) {
    expect(result2).toBeFalsy()
    checkActions(log, [{ type: 'a' }])
    expect(added).toEqual([{ type: 'a' }])
  })
})

it('iterates through added entries', function () {
  return logWith([
    [{ type: 'a' }, { id: [3] }],
    [{ type: 'b' }, { id: [2] }],
    [{ type: 'c' }, { id: [1] }]
  ]).then(function (log) {
    var entries = []
    return log.each(function (action, meta) {
      entries.push([action, meta])
    }).then(function () {
      expect(entries).toEqual([
        [{ type: 'a' }, { id: [3], time: 3, added: 1 }],
        [{ type: 'b' }, { id: [2], time: 2, added: 2 }],
        [{ type: 'c' }, { id: [1], time: 1, added: 3 }]
      ])
    })
  })
})

it('iterates by added order', function () {
  return logWith([
    [{ type: 'a' }, { id: [3] }],
    [{ type: 'b' }, { id: [2] }],
    [{ type: 'c' }, { id: [1] }]
  ]).then(function (log) {
    var actions = []
    return log.each({ order: 'added' }, function (action) {
      actions.push(action)
    }).then(function () {
      expect(actions).toEqual([
        { type: 'c' },
        { type: 'b' },
        { type: 'a' }
      ])
    })
  })
})

it('disables iteration on false', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    var actions = []
    return log.each(function (action) {
      actions.push(action)
      return false
    }).then(function () {
      expect(actions).toEqual([{ type: 'b' }])
    })
  })
})

it('supports multi-pages stores', function () {
  var store = {
    get: function () {
      return Promise.resolve({
        entries: [['a', 'a']],
        next: function () {
          return Promise.resolve({ entries: [['b', 'b']] })
        }
      })
    }
  }
  var log = new Log({ nodeId: 'test', store: store })

  var actions = []
  return log.each(function (action) {
    actions.push(action)
  }).then(function () {
    expect(actions).toEqual(['a', 'b'])
  })
})

it('keeps existed ID', function () {
  return logWith([
    [{ type: 'timed' }, { id: [100] }]
  ]).then(function (log) {
    checkEntries(log, [
      [{ type: 'timed' }, { id: [100], time: 100, added: 1 }]
    ])
  })
})

it('keeps existed ID and time', function () {
  return logWith([
    [{ type: 'timed' }, { id: [100], time: 1 }]
  ]).then(function (log) {
    checkEntries(log, [
      [{ type: 'timed' }, { id: [100], time: 1, added: 1 }]
    ])
  })
})

it('sets ID and time for timeless entries', function () {
  var log = createLog()
  return log.add({ type: 'timeless' }).then(function (meta) {
    expect(meta).toEqual(log.store.created[0][1])
    expect(meta.added).toEqual(1)
    expect(typeof meta.time).toEqual('number')
    expect(meta.id.length).toEqual(3)
    expect(meta.id[0]).toEqual(meta.time)
    expect(meta.id[1]).toEqual('test')
    expect(meta.id[2]).toEqual(0)
  })
})

it('generates unique ID', function () {
  var log = createLog()
  var used = []
  for (var i = 0; i < 100; i++) {
    var id = log.generateId()
    expect(used).not.toContainEqual(id)
    used.push(id)
  }
})

it('cleans entries', function () {
  return logWith([
    { type: 'a' }
  ]).then(function (log) {
    return log.clean().then(function () {
      checkEntries(log, [])
    })
  })
})

it('keeps entries from cleaning', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    log.keep(function (action) {
      return action.type === 'b'
    })
    return log.clean().then(function () {
      checkActions(log, [{ type: 'b' }])
    })
  })
})

it('removes keeper', function () {
  return logWith([
    { type: 'a' },
    { type: 'b' }
  ]).then(function (log) {
    var unkeep = log.keep(function (action) {
      return action.type === 'b'
    })
    return log.clean().then(function () {
      checkActions(log, [{ type: 'b' }])
      unkeep()
      return log.clean()
    }).then(function () {
      checkActions(log, [])
    })
  })
})

it('does not fall on multiple unkeep call', function () {
  var log = createLog()
  var unkeep = log.keep(function () { })
  unkeep()
  unkeep()
})
<|endoftext|>


<commit_before>const spawn = require('cross-spawn');
const path = require('path');

const s = `\\${path.sep}`;
const pattern = process.argv[2] === 'e2e'
  ? `test${s}e2e${s}.+\\.spec\\.js`
  : `test${s}(?!e2e${s})[^${s}]+${s}.+\\.spec\\.js$`;

spawn.sync(path.normalize('./node_modules/.bin/jest'), [pattern], { stdio: 'inherit' });
<commit_msg>Make runTests.js exit non-zero when tests fail (#997)<commit_after>const spawn = require('cross-spawn');
const path = require('path');

const s = `\\${path.sep}`;
const pattern = process.argv[2] === 'e2e'
  ? `test${s}e2e${s}.+\\.spec\\.js`
  : `test${s}(?!e2e${s})[^${s}]+${s}.+\\.spec\\.js$`;

const result = spawn.sync(path.normalize('./node_modules/.bin/jest'), [pattern], { stdio: 'inherit' });

process.exit(result.status);
<|endoftext|>


<commit_before>var path = require('path');

var tap = require('tap'),
    supertest = require('supertest'),
    rimraf = require('rimraf');

var cdn = require('../').app;

tap.test('singular bundles build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/concat-stream@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/concat-stream@latest doesn\'t explode');
      t.end();
    })
  ;
});

tap.test('singular bundles are cached the second time', function (t) {
  supertest(cdn)
    .get('/standalone/concat-stream@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/concat-stream@latest doesn\'t explode');
      t.end();
    })
  ;
});

/*
tap.test('singular bundles with subfiles build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/jsonml-stringify%2Fdom@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/jsonml-stringify%2Fdom@latest doesn\'t explode');
      t.end();
    })
  ;
});

tap.test('singular bundles of standalone core modules build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/events')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/events doesn\'t explode');
      t.end();
    })
  ;
});
*/

tap.test('teardown', function (t) {
  rimraf('./cdn.db', function (err) {
    t.error(err, 'removed the database');
    t.end();
    setTimeout(function () {
      process.stderr.write('# killing this because supertest is hanging\n');
      process.exit(0);
    }, 2000);
  });
});
<commit_msg>Uncomment fixed test<commit_after>var path = require('path');

var tap = require('tap'),
    supertest = require('supertest'),
    rimraf = require('rimraf');

var cdn = require('../').app;

tap.test('singular bundles build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/concat-stream@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/concat-stream@latest doesn\'t explode');
      t.end();
    })
  ;
});

tap.test('singular bundles are cached the second time', function (t) {
  supertest(cdn)
    .get('/standalone/concat-stream@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/concat-stream@latest doesn\'t explode');
      t.end();
    })
  ;
});

/*
tap.test('singular bundles with subfiles build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/jsonml-stringify%2Fdom@latest')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/jsonml-stringify%2Fdom@latest doesn\'t explode');
      t.end();
    })
  ;
});
*/

tap.test('singular bundles of standalone core modules build the first time', function (t) {
  supertest(cdn)
    .get('/standalone/events')
    .expect('Content-Type', 'text/javascript')
    .expect(200)
    .end(function (err, res) {
      t.error(err, 'requesting /standalone/events doesn\'t explode');
      t.end();
    })
  ;
});

tap.test('teardown', function (t) {
  rimraf('./cdn.db', function (err) {
    t.error(err, 'removed the database');
    t.end();
    setTimeout(function () {
      process.stderr.write('# killing this because supertest is hanging\n');
      process.exit(0);
    }, 2000);
  });
});
<|endoftext|>


<commit_before>var should = require('chai').should(),
    synonyms = require('../service/synonyms');

describe('Synonyms', function() {

    it('should be defined', function() {
        should.exist(synonyms);
    });

});

describe('Synonyms._extractKeywords', function() {

    it('should be defined', function() {
        should.exist(synonyms._extractKeywords);
    });

    it('should remove whitespace', function() {
        var keywords = synonyms._extractKeywords('a test string\n');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove parentheses and words in them', function() {
        var keywords = synonyms._extractKeywords('ateststring(testing)');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove empty square brackets', function() {
        var keywords = synonyms._extractKeywords('ateststring[]');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove hyphens', function() {
        var keywords = synonyms._extractKeywords('a-test-string');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should split words on commas', function() {
        var keywords = synonyms._extractKeywords('a,test,string');
        keywords.should.have.length(3);
        keywords[0].should.equal('a');
        keywords[1].should.equal('test');
        keywords[2].should.equal('string');
    });

    it('should replace semicolons with commas', function() {
        var keywords = synonyms._extractKeywords('a;test;string');
        keywords.should.have.length(3);
        keywords[0].should.equal('a');
        keywords[1].should.equal('test');
        keywords[2].should.equal('string');
    });

});

describe('Synonyms._parseSynonymsXML', function() {

    it('should be defined', function() {
        should.exist(synonyms._parseSynonymsXML);
    });

    it('should error on non-object', function() {
        var result = synonyms._parseSynonymsXML('not xml');
        result.should.have.property('error');
    });

    it('should error on an invalid object', function() {
        var result = synonyms._parseSynonymsXML({test: 'test'});
        result.should.have.property('error');
    });

    it('should return a properly formatted array of objects from a mock valid input', function() {
        var validInput = {
            entry_list : {
                entry : [
                    {
                        fl : 'noun',
                        sens : [
                            {
                                mc : ['test meaning'],
                                rel : ['words,separated,by,commas'],
                                syn : ['more,commas,separated,values']
                            }
                        ]
                    }
                ]
            }
        };

        var result = synonyms._parseSynonymsXML(validInput);

        result.should.have.length(1);
        result[0].should.have.property('wordType', 'noun');
        result[0].should.have.property('senses');
        result[0].senses.should.have.length(1);
        result[0].senses[0].should.have.property('meaning', 'test meaning');
        result[0].senses[0].should.have.property('words');
        result[0].senses[0].words.should.have.length(8);

    });

});

describe('Synonyms._synonymsList', function() {

    it('should be defined', function() {
        should.exist(synonyms._synonymsList);
    });

    it('should parse a properly formatted object and dedupe words', function() {
        var testSynonyms = [
            {
                wordType : 'noun',
                senses : [
                    {
                        meaning : 'A test meaning',
                        words : [
                            'test',
                            'guard',
                            'sentinel'
                        ]
                    }
                ]
            },
            {
                wordType : 'verb',
                senses : [
                    {
                        meaning : 'Another meaning',
                        words : [
                            'test',
                            'annoy',
                            'try'
                        ]
                    }
                ]
            }
        ];
        var result = synonyms._synonymsList(testSynonyms);
        result.should.have.length(5);
    })
});

describe('Synonyms.getSynonyms', function() {

    it('should be defined', function() {
        should.exist(synonyms.getSynonyms);
    });

    it('should resolve empty when given a non-existent word', function(done) {

        synonyms.getSynonyms('testtest')
            .then(function(result) {
                result.should.be.an('array').with.length(0);
                done();
            })
            .error(function(error) {
                should.not.exist(error);
                done();
            });

    });

    it('should resolve when given a legitimate word', function(done) {

        synonyms.getSynonyms('test')
            .then(function(result) {
                should.exist(result);
                //Kind of a brittle test. It will break when they add a new word. How often does that happen?
                result.should.be.an('array').with.length(72);
                done();
            })
            .error(function(error) {
                should.not.exist(error);
                done();
            });

    });
});<commit_msg>Fix failing test now that a lookup returns the searched word<commit_after>var should = require('chai').should(),
    synonyms = require('../service/synonyms');

describe('Synonyms', function() {

    it('should be defined', function() {
        should.exist(synonyms);
    });

});

describe('Synonyms._extractKeywords', function() {

    it('should be defined', function() {
        should.exist(synonyms._extractKeywords);
    });

    it('should remove whitespace', function() {
        var keywords = synonyms._extractKeywords('a test string\n');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove parentheses and words in them', function() {
        var keywords = synonyms._extractKeywords('ateststring(testing)');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove empty square brackets', function() {
        var keywords = synonyms._extractKeywords('ateststring[]');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should remove hyphens', function() {
        var keywords = synonyms._extractKeywords('a-test-string');
        keywords.should.have.length(1);
        keywords[0].should.equal('ateststring');
    });

    it('should split words on commas', function() {
        var keywords = synonyms._extractKeywords('a,test,string');
        keywords.should.have.length(3);
        keywords[0].should.equal('a');
        keywords[1].should.equal('test');
        keywords[2].should.equal('string');
    });

    it('should replace semicolons with commas', function() {
        var keywords = synonyms._extractKeywords('a;test;string');
        keywords.should.have.length(3);
        keywords[0].should.equal('a');
        keywords[1].should.equal('test');
        keywords[2].should.equal('string');
    });

});

describe('Synonyms._parseSynonymsXML', function() {

    it('should be defined', function() {
        should.exist(synonyms._parseSynonymsXML);
    });

    it('should error on non-object', function() {
        var result = synonyms._parseSynonymsXML('not xml');
        result.should.have.property('error');
    });

    it('should error on an invalid object', function() {
        var result = synonyms._parseSynonymsXML({test: 'test'});
        result.should.have.property('error');
    });

    it('should return a properly formatted array of objects from a mock valid input', function() {
        var validInput = {
            entry_list : {
                entry : [
                    {
                        fl : 'noun',
                        sens : [
                            {
                                mc : ['test meaning'],
                                rel : ['words,separated,by,commas'],
                                syn : ['more,commas,separated,values']
                            }
                        ]
                    }
                ]
            }
        };

        var result = synonyms._parseSynonymsXML(validInput);

        result.should.have.length(1);
        result[0].should.have.property('wordType', 'noun');
        result[0].should.have.property('senses');
        result[0].senses.should.have.length(1);
        result[0].senses[0].should.have.property('meaning', 'test meaning');
        result[0].senses[0].should.have.property('words');
        result[0].senses[0].words.should.have.length(8);

    });

});

describe('Synonyms._synonymsList', function() {

    it('should be defined', function() {
        should.exist(synonyms._synonymsList);
    });

    it('should parse a properly formatted object and dedupe words', function() {
        var testSynonyms = [
            {
                wordType : 'noun',
                senses : [
                    {
                        meaning : 'A test meaning',
                        words : [
                            'test',
                            'guard',
                            'sentinel'
                        ]
                    }
                ]
            },
            {
                wordType : 'verb',
                senses : [
                    {
                        meaning : 'Another meaning',
                        words : [
                            'test',
                            'annoy',
                            'try'
                        ]
                    }
                ]
            }
        ];
        var result = synonyms._synonymsList(testSynonyms);
        result.should.have.length(5);
    })
});

describe('Synonyms.getSynonyms', function() {

    it('should be defined', function() {
        should.exist(synonyms.getSynonyms);
    });

    it('should resolve empty when given a non-existent word', function(done) {

        synonyms.getSynonyms('testtest')
            .then(function(result) {
                result.should.be.an('array').with.length(1);
                done();
            })
            .error(function(error) {
                should.not.exist(error);
                done();
            });

    });

    it('should resolve when given a legitimate word', function(done) {

        synonyms.getSynonyms('test')
            .then(function(result) {
                should.exist(result);
                //Kind of a brittle test. It will break when they add a new word. How often does that happen?
                result.should.be.an('array').with.length(72);
                done();
            })
            .error(function(error) {
                should.not.exist(error);
                done();
            });

    });
});<|endoftext|>


<commit_before>/* global describe, beforeEach, it*/

const path = require('path');
const fse = require('fs-extra');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');

const deps = [
    [helpers.createDummyGenerator(), 'jhipster:modules']
];

describe('JHipster generator db-helper', () => {
    describe('simple test', () => {
        beforeEach((done) => {
            helpers
                .run(path.join(__dirname, '../generators/app'))
                .inTmpDir((dir) => {
                    fse.copySync(path.join(__dirname, '../test/templates/default'), dir);
                })
                .withOptions({
                    testmode: true
                })
                .withPrompts({
                    message: 'simple message to say hello'
                })
                .withGenerators(deps)
                .on('end', done);
        });
        /*
        it('generate dummy.txt file', () => {
            assert.file([
                'dummy.txt'
            ]);
        });

        it('find no occurrences of org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy', () => {
            //
        });
        it('find no occurrences of org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy', () => {
            //
        });
        */
    });
});
<commit_msg>Prepare unit tests<commit_after>/* global describe, beforeEach, it*/

const path = require('path');
const fse = require('fs-extra');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');

const deps = [
    [helpers.createDummyGenerator(), 'jhipster:modules']
];

describe('JHipster generator db-helper', () => {
    describe('simple test', () => {
        beforeEach((done) => {
            helpers
                .run(path.join(__dirname, '../generators/app'))
                .inTmpDir((dir) => {
                    fse.copySync(path.join(__dirname, '../test/templates/default'), dir);
                })
                .withOptions({
                    testmode: true
                })
                .withPrompts({
                    message: 'simple message to say hello'
                })
                .withGenerators(deps)
                .on('end', done);
        });
        /*
        it('find no occurrences of org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy', () => {
            assert.fileContent(file, /org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy/);
        });
        it('find no occurrences of org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy', () => {
            assert.fileContent(file, /org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy/);
        });
        */
    });
});
<|endoftext|>


<commit_before>
var chai = require('chai')
  , expect = chai.expect
  , should = chai.should()
  , path = require('path')
  , _ = require('underscore')
	, FRESHResume = require('../src/core/fresh-resume')
  , FCMD = require( '../src/hackmycmd')
  , validator = require('is-my-json-valid')
  , COLORS = require('colors');

chai.config.includeStack = false;

describe('Testing CLI interface', function () {

    var _sheet;

    function logMsg() {

    }

    COLORS.setTheme({
      title: ['white','bold'],
      info: process.platform === 'win32' ? 'gray' : ['white','dim'],
      infoBold: ['white','dim'],
      warn: 'yellow',
      error: 'red',
      guide: 'yellow',
      status: 'gray',//['white','dim'],
      useful: 'green',
    });

    var opts = {
      //theme: 'compact',
      format: 'FRESH',
      prettify: true,
      silent: true
    };

    var opts2 = {
      format: 'JRS',
      prettify: true,
      silent: true
    };

    run( 'new', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
    run( 'new', ['test/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
    run( 'new', ['test/sandbox/new-1.json', 'test/sandbox/new-2.json', 'test/sandbox/new-3.json'], [], opts, ' (multiple FRESH resumes)' );
    run( 'new', ['test/sandbox/new-jrs-1.json', 'test/sandbox/new-jrs-2.json', 'test/sandbox/new-jrs-3.json'], [], opts, ' (multiple JRS resumes)' );
    run( 'new', ['test/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
    fail( 'new', [], [], opts, " (when a filename isn't specified)" );

    run( 'validate', ['node_modules/jane-q-fullstacker/resume/jane-resume.json'], [], opts, ' (FRESH format)' );
    run( 'validate', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );

    function run( verb, src, dst, opts, msg ) {
      msg = msg || '.';
      it( 'The ' + verb.toUpperCase() + ' command should SUCCEED' + msg, function () {
        function runIt() {
          FCMD.verbs[verb]( src, dst, opts, opts.silent ? logMsg : null );
        }
        runIt.should.not.Throw();
      });
    }

    function fail( verb, src, dst, opts, msg ) {
      msg = msg || '.';
      it( 'The ' + verb.toUpperCase() + ' command should FAIL' + msg, function () {
        function runIt() {
          FCMD.verbs[verb]( src, dst, opts, logMsg );
        }
        runIt.should.Throw();
      });
    }

});
<commit_msg>Add additional validate tests.<commit_after>
var chai = require('chai')
  , expect = chai.expect
  , should = chai.should()
  , path = require('path')
  , _ = require('underscore')
	, FRESHResume = require('../src/core/fresh-resume')
  , FCMD = require( '../src/hackmycmd')
  , validator = require('is-my-json-valid')
  , COLORS = require('colors');

chai.config.includeStack = false;

describe('Testing CLI interface', function () {

    var _sheet;

    function logMsg() {

    }

    COLORS.setTheme({
      title: ['white','bold'],
      info: process.platform === 'win32' ? 'gray' : ['white','dim'],
      infoBold: ['white','dim'],
      warn: 'yellow',
      error: 'red',
      guide: 'yellow',
      status: 'gray',//['white','dim'],
      useful: 'green',
    });

    var opts = {
      //theme: 'compact',
      format: 'FRESH',
      prettify: true,
      silent: true
    };

    var opts2 = {
      format: 'JRS',
      prettify: true,
      silent: true
    };

    run( 'new', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
    run( 'new', ['test/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
    run( 'new', ['test/sandbox/new-1.json', 'test/sandbox/new-2.json', 'test/sandbox/new-3.json'], [], opts, ' (multiple FRESH resumes)' );
    run( 'new', ['test/sandbox/new-jrs-1.json', 'test/sandbox/new-jrs-2.json', 'test/sandbox/new-jrs-3.json'], [], opts, ' (multiple JRS resumes)' );
    fail( 'new', [], [], opts, " (when a filename isn't specified)" );

    run( 'validate', ['node_modules/jane-q-fullstacker/resume/jane-resume.json'], [], opts, ' (jane-q-fullstacker|FRESH)' );
    run( 'validate', ['node_modules/johnny-trouble-resume/src/johnny-trouble.fresh.json'], [], opts, ' (johnny-trouble|FRESH)' );
    run( 'validate', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (new-fresh-resume|FRESH)' );
    run( 'validate', ['test/sandbox/resumes/jrs-0.0.0/ruchard-hendriks.json'], [], opts2, ' (richard-hendriks.json|JRS)' );
    run( 'validate', ['test/sandbox/resumes/jrs-0.0.0/jane-incomplete.json'], [], opts2, ' (jane-incomplete.json|JRS)' );
    run( 'validate', ['test/sandbox/new-1.json','test/sandbox/new-jrs-resume.json','test/sandbox/new-1.json', 'test/sandbox/new-2.json', 'test/sandbox/new-3.json'], [], opts, ' (5|BOTH)' );

    function run( verb, src, dst, opts, msg ) {
      msg = msg || '.';
      it( 'The ' + verb.toUpperCase() + ' command should SUCCEED' + msg, function () {
        function runIt() {
          FCMD.verbs[verb]( src, dst, opts, opts.silent ? logMsg : null );
        }
        runIt.should.not.Throw();
      });
    }

    function fail( verb, src, dst, opts, msg ) {
      msg = msg || '.';
      it( 'The ' + verb.toUpperCase() + ' command should FAIL' + msg, function () {
        function runIt() {
          FCMD.verbs[verb]( src, dst, opts, logMsg );
        }
        runIt.should.Throw();
      });
    }

});
<|endoftext|>


<commit_before>module('jss');

test('Adding and removing sheets', function () {
    strictEqual(jss._getSheet(jss), null, 'Default jss sheet is null at first');

    var newSheet = jss._addSheet(jss);
    ok(typeof newSheet == 'object' && newSheet !== null, 'Add new sheet');

    var defSheet = jss._getSheet(jss);
    ok(typeof defSheet == 'object' && defSheet !== null, 'Default jss sheet added');

    jss._removeSheet(jss);
    strictEqual(jss._getSheet(jss), null, 'Default jss sheet removed');
});

test('Add CSS to the default jss sheet', function () {
    // Shorthand for adding a rule to the default jss sheet
    jss('.special', {
        'color': 'red'
    });
    equal($('.special').css('color'), 'red', 'Add color red');

    // Equivalent, expanded syntax
    jss('.special', jss).add('background-color', '#aaa');
    equal($('.special').css('background-color'), '#aaa', 'Add background-color');

    // .set() only works if the rule exists
    jss('#no', jss).set('color', 'yellow');
    equal($('#no').css('color'), 'red', "Element's color hasn't changed");

    jss('#yes', jss).add();
    jss('#yes', jss).set('color', 'yellow');
    equal($('#yes').css('color'), 'yellow', "Element's color has changed");

    // Cleanup
    jss._removeSheet(jss);
});

test('Switching stylesheets', function () {
    // To be determined...
});<commit_msg>Added tests for the basic sheet and rule manipulation functions<commit_after>module('jss');

test('Adding and removing sheets', function () {
    var nSheets = jss._getSheets().length;

    // Add new sheet
    var newSheet = jss._addSheet();
    equal(jss._getSheets().length, nSheets + 1, 'New sheet added');

    // Remove new sheet
    jss._removeSheet(newSheet);
    equal(jss._getSheets().length, nSheets, 'New sheet removed');
});

test('Adding and removing rules', function () {
    // Setup
    var sheet = jss._addSheet();
    var i;

    equal(jss._getRules(sheet).length, 0, 'New sheet has no rules');

    // Add a rule
    var rule = jss._addRule(sheet, '.someRule');
    ok(!!rule.style, 'Rule has a style property');
    equal(jss._getRules(sheet).length, 1, 'New rule added');
    equal(jss._getRules(sheet, '.someRule').length, 1, 'Retrieve new rule with selector');
    equal(jss._getRules(sheet, '.someOtherRule').length, 0, 'Retrieve non-existent rule');

    // Add another rule
    var rule2 = jss._addRule(sheet, '.someOtherRule');
    equal(jss._getRules(sheet).length, 2, 'Sheet has two rules');
    equal(jss._getRules(sheet, '.someOtherRule').length, 1, 'Retrieve second rule with selector');

    // Remove rules
    var rules = jss._getRules(sheet);
    jss._removeRule(rules[0]); // Shifting reference
    equal(jss._getRules(sheet).length, 1, 'First rule removed');
    jss._removeRule(rules[0]); // Shifting reference
    equal(jss._getRules(sheet).length, 0, 'Second rule removed');
});
<|endoftext|>


<commit_before>var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var expect = chai.expect;
var mocha = require("mocha");

var api = require("../api");

chai.use(chaiAsPromised);

const RATE_LIMITED = "API rate limit exceeded. Please try again later.";

describe("api", function() {
    describe("#getRepoInfo", function() {
        it("should fail for invalid repos", function() {
            return expect(api.getRepoInfo("james9909/githuub-stupidity")).to.be.rejectedWith(Error);
        });

        it("should work on valid repos", function() {
            return api.getRepoInfo("james9909/github-stupidity").then(function(data) {
                expect(data["name"]).to.equal("github-stupidity");
                expect(data["full_name"]).to.equal("james9909/github-stupidity");
                expect(data["stargazers_count"]).to.be.a("number");
                expect(data["forks_count"]).to.be.a("number");
                expect(data["contributors"]).to.be.a("number");
            });
        });
    });

    describe("#calculateRepoStupidity", function() {
        it("should fail for invalid repos", function() {
            return expect(api.calculateRepoStupidity("james9909/githuub-stupidity")).to.be.rejectedWith(Error);
        });

        it("should work on valid repos", function() {
            return api.calculateRepoStupidity("james9909/github-stupidity").then(function(data) {
                var name = data["name"];
                var stars = data["stars"];
                var forks = data["forks"];
                var contributors = data["contributors"];
                var stupidity = data["stupidity"];
                expect(name).to.equal("james9909/github-stupidity");
                expect(stars).to.be.a("number");
                expect(forks).to.be.a("number");
                expect(contributors).to.be.a("number");
                expect(stupidity).to.be.a("number");
                expect(stupidity).to.be.finite;
                expect(stupidity).to.be.at.least(0);
            });
        });
    });

    describe("#calculateLanguageStupidity", function() {
        it("should fail for invalid languages", function() {
            return expect(api.calculateLanguageStupidity("invalidlang")).to.be.rejectedWith(Error);
        });

        it("should work on valid languages", function() {
            this.timeout(8000);
            return api.calculateLanguageStupidity("javascript").then(function(data) {
                expect(data.length).to.equal(20);
            })
        })
    })
});
<commit_msg>Fix tests to reflect data format<commit_after>var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var expect = chai.expect;
var mocha = require("mocha");

var api = require("../api");

chai.use(chaiAsPromised);

const RATE_LIMITED = "API rate limit exceeded. Please try again later.";

describe("api", function() {
    describe("#getRepoInfo", function() {
        it("should fail for invalid repos", function() {
            return expect(api.getRepoInfo("james9909/githuub-stupidity")).to.be.rejectedWith(Error);
        });

        it("should work on valid repos", function() {
            return api.getRepoInfo("james9909/github-stupidity").then(function(data) {
                expect(data["name"]).to.equal("github-stupidity");
                expect(data["full_name"]).to.equal("james9909/github-stupidity");
                expect(data["stargazers_count"]).to.be.a("number");
                expect(data["forks_count"]).to.be.a("number");
                expect(data["contributors"]).to.be.a("number");
            });
        });
    });

    describe("#calculateRepoStupidity", function() {
        it("should fail for invalid repos", function() {
            return expect(api.calculateRepoStupidity("james9909/githuub-stupidity")).to.be.rejectedWith(Error);
        });

        it("should work on valid repos", function() {
            return api.calculateRepoStupidity("james9909/github-stupidity").then(function(data) {
                var name = data["name"];
                var stars = data["stars"];
                var forks = data["forks"];
                var contributors = data["contributors"];
                var stupidity = data["stupidity"];
                expect(name).to.equal("james9909/github-stupidity");
                expect(stars).to.be.a("number");
                expect(forks).to.be.a("number");
                expect(contributors).to.be.a("number");
                expect(stupidity).to.be.a("number");
                expect(stupidity).to.be.finite;
                expect(stupidity).to.be.at.least(0);
            });
        });
    });

    describe("#calculateLanguageStupidity", function() {
        it("should fail for invalid languages", function() {
            return expect(api.calculateLanguageStupidity("invalidlang")).to.be.rejectedWith(Error);
        });

        it("should work on valid languages", function() {
            this.timeout(8000);
            return api.calculateLanguageStupidity("javascript").then(function(data) {
                expect(data.language).to.equal("javascript");
                expect(data.repos.length).to.equal(20);
            })
        })
    })
});
<|endoftext|>


<commit_before>(function($) {
	var jqueryLink = '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
		dfpLink = '//d3clqjla00sltp.cloudfront.net/programatic/jquery.dfp.min.js',
		dfpTag = {
			id: '175265624',
			unitId:'MobileKoimoi_BelowImage_300x250_Mob',
			dimention: {
				width: 300,
				height: 250
			}
		};

	var setAttributes = function(el, attrs) {
		for(var key in attrs) { if (attrs.hasOwnProperty(key)) el.setAttribute(key, attrs[key]); }
	};

	var container = $('body'),
		iframe = document.createElement('iframe'),
		width = container.width,
		scale = ((width / dfpTag.dimention.width) <= 1) ? (width / dfpTag.dimention.width) : 1,
		left = Math.round((dfpTag.dimention.width - width)/2),
		cssText = "height:"+ dfpTag.dimention.height +"px !important;left:-"+ left +"px;width:"+ dfpTag.dimention.width +"px !important; overflow:hidden; bottom:0px; border: 0px; position:relative; background: transparent; z-index: 2; -moz-transform: scale("+ scale +"); -o-transform: scale("+ scale +"); -webkit-transform: scale("+ scale +"); transform: scale("+ scale +"); max-width:initial !important;";

	setAttributes(iframe, {
		"height": dfpTag.dimention.height,
		"scrolling": "no",
		"frameBorder": 0,
		"allowtransparency": "true",
		"class": "adunit",
		"width": dfpTag.dimention.width,
		"loadStatus": 0,
		"data-width": dfpTag.dimention.width,
		"data-height": dfpTag.dimention.height,
		"style": cssText,
		"data-dimensions": dfpTag.dimention.width+'x'+dfpTag.dimention.height
	});
  	container.append(iframe);

	try{
		Debugger.log('Log : Setting html content in try block !!');
		var doc = iframe.contentDocument || iframe.contentWindow.document,
		content = '';

	    doc.open();
	    doc.write(content);
	    doc.close();
    }
    catch(e){ console.log(e); }

})($ || jQuery);
<commit_msg>Update test_dfp.js<commit_after>(function($) {
	var jqueryLink = '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
		dfpLink = '//d3clqjla00sltp.cloudfront.net/programatic/jquery.dfp.min.js',
		dfpTag = {
			id: '175265624',
			unitId:'MobileKoimoi_BelowImage_300x250_Mob',
			dimention: {
				width: 300,
				height: 250
			}
		};

	var setAttributes = function(el, attrs) {
		for(var key in attrs) { if (attrs.hasOwnProperty(key)) el.setAttribute(key, attrs[key]); }
	};

	var container = $('body'),
		iframe = document.createElement('iframe'),
		width = container.width,
		scale = ((width / dfpTag.dimention.width) <= 1) ? (width / dfpTag.dimention.width) : 1,
		left = Math.round((dfpTag.dimention.width - width)/2),
		cssText = "height:"+ dfpTag.dimention.height +"px !important;left:-"+ left +"px;width:"+ dfpTag.dimention.width +"px !important; overflow:hidden; bottom:0px; border: 0px; position:relative; background: transparent; z-index: 2; -moz-transform: scale("+ scale +"); -o-transform: scale("+ scale +"); -webkit-transform: scale("+ scale +"); transform: scale("+ scale +"); max-width:initial !important;";

	setAttributes(iframe, {
		"height": dfpTag.dimention.height,
		"scrolling": "no",
		"frameBorder": 0,
		"allowtransparency": "true",
		"class": "adunit",
		"width": dfpTag.dimention.width,
		"loadStatus": 0,
		"data-width": dfpTag.dimention.width,
		"data-height": dfpTag.dimention.height,
		"style": cssText,
		"data-dimensions": dfpTag.dimention.width+'x'+dfpTag.dimention.height
	});
  	container.append(iframe);

	try{
		console.log('Log : Setting html content in try block !!');
		var doc = iframe.contentDocument || iframe.contentWindow.document,
		content = '';

	    doc.open();
	    doc.write(content);
	    doc.close();
    }
    catch(e){ console.log(e); }

})($ || jQuery);
<|endoftext|>


<commit_before>var app = app || {};

(function ($) {
  'use strict';

  app.FirewoodsView = Backbone.View.extend({
    el: '#firewoods',
    count: 0,
    maxCount: 150,

    initialize: function () {
      this.$list = this.$('#timeline');
      this.$stack = this.$('#timeline_stack');
      this.$form = this.$('#new_firewood');
      this.$input = this.$('#contents');
      this.$title = this.$('#title');
      this.$commitBtn = this.$('#commit');
      this.$prevMt = this.$('#firewood_prev_mt');

      this.listenTo(app.firewoods, 'reset', this.addAll);
      this.listenTo(app.firewoods, 'add:prepend', this.prepend);
      this.listenTo(app.firewoods, 'add:append', this.append);
      this.listenTo(app.firewoods, 'add:stack', this.updateStackNotice);
      this.listenTo(app.firewoods, 'change:isHighlighted', this.highlightOne);

      this.listenTo(app.channel, 'ajaxSuccess', this.formClear);
      this.listenTo(app.firewoods, 'form:appendMt', this.appendMt);
      this.listenTo(app.firewoods, 'timeline:foldAll', this.foldAll);
      this.listenTo(app.firewoods, 'timeline:unFoldAll', this.unFoldAll);

      this.$('span[rel=tooltip]').tooltip();
      this.originTitle = this.$title.text();

      $(document).ajaxError(app.channel.ajaxError);
      app.channel.load();
      app.channel.setPullingTimer();
      setInterval(this.isNearBottom, 1000, this);
    },

    events: {
      'input #contents': 'update_count',
      'keyup #contents': 'update_count',
      'keydown #contents': 'keydown',
      'paste #contents': 'update_count',
      'click #timeline_stack': 'flushStack',
      'submit #new_firewood': 'submit'
    },

    keydown: function (e) {
      if (e.keyCode == window.ENTER_KEY) {
        this.submit(e);
      }
    },

    // Collection Event
    addAll: function () {
      this.$list.html('');
      app.firewoods.each(function (fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.append(view.render().el);
      }, this);
    },

    prepend: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_STACK }).reverse();
      _.each(fws, function(fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.prepend(view.render().el);
        fw.set('state', 0);
      }, this);

      return this;
    },

    append: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_LOG });
      _.each(fws, function(fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.append(view.render().el);
        fw.set('state', 0);
      }, this);

      return this;
    },

    updateStackNotice: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_STACK});
      if ( fws.length == 0 ) {
        return false;
      }

      this.$title.html(this.originTitle + ' (' + fws.length + ')');
      this.$stack
        .html('새 장작이 ' + fws.length + '개 있습니다.')
        .slideDown(200);
    },

    highlightOne: function (fw) {
      fw.trigger('highlight');
    },

    submit: function (e) {
      e.preventDefault();

      if ( !this.isFormEmpty() ) {
        this.$form.ajaxSubmit(app.channel.ajaxBasicOptions);
      } else {
        app.channel.pulling(true);
      }
      return false;
    },

    formClear: function() {
      this.$form.clearForm();
      this.$('#contents').html('');
      this.$('#img').val('');
      this.$('.fileinput-preview').html('');
      this.$('.fileinput')
        .removeClass('fileinput-exists')
        .addClass('fileinput-new');
      this.$('.fileinput-filename').html('');
      this.$prevMt.val('');
      this.$commitBtn.button('reset');

      this.update_count();
    },

    update_count: function () {
      var before = this.count;
      var now = this.maxCount - this.$input.text().length;

      if ( this.isFormEmpty() ) {
        this.$commitBtn.val('Refresh');
      } else {
        this.$commitBtn.val('Submit');
      }

      if ( now < 0 ) {
        var str = this.$input.val();
        this.$input.val(str.substr(0, this.maxCount));
        now = 0;
      }

      if ( before != now ) {
        this.count = now;
        this.$('#remaining_count').text(now);
      }
    },

    appendMt: function (names, target) {
      var mts = _.map(names, function (name) { return name; });

      this.$prevMt.val(target);
      this.$input
        .val( mts.join(' ') + ' ' + this.$input.val() )
        .focus();
    },

    flushStack: function () {
      $('.last_top').removeClass('last_top').attr('style','');
      $('.div-firewood:first').addClass('last_top').attr('style','border-top-width:3px;');

      var fws = app.firewoods.filter(function (fw) { return fw.get('state') == -1 && fw.get('img_link') != '0' });
      this.prepend();
      this.$title.html(this.originTitle);
      this.$stack.html('').slideUp(200);

      if ( window.localStorage['auto_image_open'] == '1' ) {
        _.each(fws, function (fw) { fw.trigger('unFold') });
      }
    },

    foldAll: function () {
      var fws = app.firewoods.where({ isOpened: true });
      _.each(fws, function ( fw ) { fw.trigger('fold'); });
    },

    unFoldAll: function () {
      var fws = app.firewoods.filter( function (fw) { return fw.get('img_link') !== '0' });
      _.each(fws, function ( fw ) { fw.trigger('unFold'); });
    },

    isNearBottom: function (context) {
      var $fws = $('.firewood');
      var fws = app.firewoods;
      var self = context;

      if ( fws.size() == 0 || !$fws.eq(-5).isOnScreen() || fws.logGetLock || fws.length < 50 || fws.last().get('id') < 10 ) {
        return false;
      }

      self.$list.append('

로딩중입니다.

');
      app.channel.getLogs().then(function () {
        $('#div-loading').parent().remove();
      });
    },

    isFormEmpty: function () {
      if ( this.$('div.fileinput-exists').length == 0 ) {
        var str = this.$('#contents').text();
        if ( str.length == 0 || str.search(/^\s+$/) != -1 ) {
          return true;
        }
      }
      return false;
    }
  });
})(jQuery);<commit_msg>fixed #48<commit_after>var app = app || {};

(function ($) {
  'use strict';

  app.FirewoodsView = Backbone.View.extend({
    el: '#firewoods',
    count: 0,
    maxCount: 150,

    initialize: function () {
      this.$list = this.$('#timeline');
      this.$stack = this.$('#timeline_stack');
      this.$form = this.$('#new_firewood');
      this.$input = this.$('#contents');
      this.$title = this.$('#title');
      this.$commitBtn = this.$('#commit');
      this.$prevMt = this.$('#firewood_prev_mt');

      this.listenTo(app.firewoods, 'reset', this.addAll);
      this.listenTo(app.firewoods, 'add:prepend', this.prepend);
      this.listenTo(app.firewoods, 'add:append', this.append);
      this.listenTo(app.firewoods, 'add:stack', this.updateStackNotice);
      this.listenTo(app.firewoods, 'change:isHighlighted', this.highlightOne);

      this.listenTo(app.channel, 'ajaxSuccess', this.formClear);
      this.listenTo(app.firewoods, 'form:appendMt', this.appendMt);
      this.listenTo(app.firewoods, 'timeline:foldAll', this.foldAll);
      this.listenTo(app.firewoods, 'timeline:unFoldAll', this.unFoldAll);

      this.$('span[rel=tooltip]').tooltip();
      this.originTitle = this.$title.text();

      $(document).ajaxError(app.channel.ajaxError);
      app.channel.load();
      app.channel.setPullingTimer();
      setInterval(this.isNearBottom, 1000, this);
    },

    events: {
      'input #contents': 'update_count',
      'keyup #contents': 'update_count',
      'keydown #contents': 'keydown',
      'paste #contents': 'update_count',
      'click #timeline_stack': 'flushStack',
      'submit #new_firewood': 'submit'
    },

    keydown: function (e) {
      if (e.keyCode == window.ENTER_KEY) {
        this.submit(e);
      } else {
        e.stopPropagation();
      }
    },

    // Collection Event
    addAll: function () {
      this.$list.html('');
      app.firewoods.each(function (fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.append(view.render().el);
      }, this);
    },

    prepend: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_STACK }).reverse();
      _.each(fws, function(fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.prepend(view.render().el);
        fw.set('state', 0);
      }, this);

      return this;
    },

    append: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_LOG });
      _.each(fws, function(fw) {
        var view = new app.FirewoodView({ model: fw });
        this.$list.append(view.render().el);
        fw.set('state', 0);
      }, this);

      return this;
    },

    updateStackNotice: function () {
      var fws = app.firewoods.where({ state: FW_STATE.IN_STACK});
      if ( fws.length == 0 ) {
        return false;
      }

      this.$title.html(this.originTitle + ' (' + fws.length + ')');
      this.$stack
        .html('새 장작이 ' + fws.length + '개 있습니다.')
        .slideDown(200);
    },

    highlightOne: function (fw) {
      fw.trigger('highlight');
    },

    submit: function (e) {
      e.preventDefault();

      if ( !this.isFormEmpty() ) {
        this.$form.ajaxSubmit(app.channel.ajaxBasicOptions);
      } else {
        app.channel.pulling(true);
      }
      return false;
    },

    formClear: function() {
      this.$form.clearForm();
      this.$('#contents').html('');
      this.$('#img').val('');
      this.$('.fileinput-preview').html('');
      this.$('.fileinput')
        .removeClass('fileinput-exists')
        .addClass('fileinput-new');
      this.$('.fileinput-filename').html('');
      this.$prevMt.val('');
      this.$commitBtn.button('reset');

      this.update_count();
    },

    update_count: function () {
      var before = this.count;
      var now = this.maxCount - this.$input.text().length;

      if ( this.isFormEmpty() ) {
        this.$commitBtn.val('Refresh');
      } else {
        this.$commitBtn.val('Submit');
      }

      if ( now < 0 ) {
        var str = this.$input.val();
        this.$input.val(str.substr(0, this.maxCount));
        now = 0;
      }

      if ( before != now ) {
        this.count = now;
        this.$('#remaining_count').text(now);
      }
    },

    appendMt: function (names, target) {
      var mts = _.map(names, function (name) { return name; });

      this.$prevMt.val(target);
      this.$input
        .val( mts.join(' ') + ' ' + this.$input.val() )
        .focus();
    },

    flushStack: function () {
      $('.last_top').removeClass('last_top').attr('style','');
      $('.div-firewood:first').addClass('last_top').attr('style','border-top-width:3px;');

      var fws = app.firewoods.filter(function (fw) { return fw.get('state') == -1 && fw.get('img_link') != '0' });
      this.prepend();
      this.$title.html(this.originTitle);
      this.$stack.html('').slideUp(200);

      if ( window.localStorage['auto_image_open'] == '1' ) {
        _.each(fws, function (fw) { fw.trigger('unFold') });
      }
    },

    foldAll: function () {
      var fws = app.firewoods.where({ isOpened: true });
      _.each(fws, function ( fw ) { fw.trigger('fold'); });
    },

    unFoldAll: function () {
      var fws = app.firewoods.filter( function (fw) { return fw.get('img_link') !== '0' });
      _.each(fws, function ( fw ) { fw.trigger('unFold'); });
    },

    isNearBottom: function (context) {
      var $fws = $('.firewood');
      var fws = app.firewoods;
      var self = context;

      if ( fws.size() == 0 || !$fws.eq(-5).isOnScreen() || fws.logGetLock || fws.length < 50 || fws.last().get('id') < 10 ) {
        return false;
      }

      self.$list.append('

로딩중입니다.

');
      app.channel.getLogs().then(function () {
        $('#div-loading').parent().remove();
      });
    },

    isFormEmpty: function () {
      if ( this.$('div.fileinput-exists').length == 0 ) {
        var str = this.$('#contents').text();
        if ( str.length == 0 || str.search(/^\s+$/) != -1 ) {
          return true;
        }
      }
      return false;
    }
  });
})(jQuery);<|endoftext|>