<commit_before>'use strict';
var util = require('util');
var chai = require('chai');
chai.should();
var expect = chai.expect;
var supertest = require('supertest');
var cuid = require('cuid');

var Q = require('q');
var http = require('http');

// We will use it to store expected values
var swsReqResStats = require('../lib/swsReqResStats');
var swsUtil = require('../lib/swsUtil');

var debug = require('debug')('swstest:baseline');

var swsTestFixture = require('./testfixture');
var swsTestUtils = require('./testutils');

// duration of method test - number of requests
var method_test_duration = 25;
if( process.env.SWS_METHOD_TEST_DURATION){
    method_test_duration = parseInt(process.env.SWS_METHOD_TEST_DURATION);
}

var expected_method_values = {};

function sendTestRequestsOnce(iteration, deferred){

    if(iteration<=0){
        deferred.resolve();
        return;
    }

    //var methods = ['get','post','put','delete','head','options'];
    var methods = ['GET','POST','PUT','DELETE','OPTIONS'];

    // Generate random number of requests each iteration
    var reqcntr = 0;

    methods.forEach(function(method) {

        if(!(method in expected_method_values) ) {
            expected_method_values[method] = new swsReqResStats();
        }
        var methodCurrent = expected_method_values[method];

        var numReq = swsTestUtils.getRandomArbitrary(0,5);
        for(var i=0;i<numReq;i++) {

            reqcntr++;

            var randomcode = swsTestUtils.getRandomHttpStatusCode();
            var hdr = {
                code: randomcode,
                message: swsTestUtils.getHttpStatusMessage(randomcode),
                delay: swsTestUtils.getRandomArbitrary(0, 100),
                payloadsize: swsTestUtils.getRandomArbitrary(10, 200)
            };
            var xswsResHdr = JSON.stringify(hdr);

            debug('>>>>> %s %s x-sws-res:%s', method, swsTestFixture.SWS_TEST_MOCK_API, xswsResHdr);

            const options = {
                hostname: swsTestFixture.SWS_TEST_DEFAULT_HOST, //'localhost'
                port: swsTestFixture.SWS_TEST_DEFAULT_PORT, //3030,
                path: swsTestFixture.SWS_TEST_MOCK_API,
                method: method,
                headers: {
                    'x-sws-res': xswsResHdr
                }
            };
            var body = null;
            if ((method === 'post') || (method === 'put')) {
                var reqPayloadSize = swsTestUtils.getRandomArbitrary(10, 200);
                var str = '';
                for (var i = 0; i < reqPayloadSize; i++) str += 'r';
                body = JSON.stringify([str]);
                options.headers["Content-Type"] = "application/json";
                options.headers["Content-Length"] = Buffer.byteLength(body);
            }

            // Store in expected values
            methodCurrent.requests++;
            methodCurrent[swsUtil.getStatusCodeClass(randomcode)]++;
            if(swsUtil.isError(randomcode)) methodCurrent.errors++;
            var req_clen = ( body!==null ? Buffer.byteLength(body) : 0 );
            methodCurrent.total_req_clength += req_clen;
            var res_clen = hdr.payloadsize;
            methodCurrent.total_res_clength += res_clen;
            if( req_clen > methodCurrent.max_req_clength ) methodCurrent.max_req_clength = req_clen;
            if( res_clen > methodCurrent.max_res_clength ) methodCurrent.max_res_clength = res_clen;
            methodCurrent.avg_req_clength = Math.floor(methodCurrent.total_req_clength / methodCurrent.requests);
            methodCurrent.avg_res_clength = Math.floor(methodCurrent.total_res_clength / methodCurrent.requests);

            const req = http.request(options, function (res) {
                reqcntr--;
                if (reqcntr <= 0) {
                    sendTestRequestsOnce(iteration - 1, deferred);
                }
            });
            body !== null ? req.end(body) : req.end();
        }
    });

}

function generateTestRequests(){
    var deferred = Q.defer();
    sendTestRequestsOnce( method_test_duration, deferred );
    return deferred.promise;
}

setImmediate(function() {

    describe('Method statistics test', function () {

        this.timeout(40000);

        var appTimelineTest = null;
        var apiTimelineTest = null;

        var timelineStatsInitial = null;
        var timelineStatsCurrent = null;

        var methodStatsInitial = null;
        var methodStatsCurrent = null;

        var client_error_id = cuid();
        var server_error_id = cuid();

        // 1 second
        var timeline_bucket_duration = 1000;

        describe('Initialize', function () {
            it('should initialize example app', function (done) {
                supertest(swsTestFixture.SWS_TEST_DEFAULT_URL).get(swsTestFixture.SWS_TEST_STATS_API)
                    .expect(200)
                    .end(function (err, res) {
                        if (err) {
                            process.env.SWS_TEST_TIMEBUCKET = timeline_bucket_duration;
                            appTimelineTest = require('../examples/testapp/testapp');
                            apiTimelineTest = supertest('http://localhost:' + appTimelineTest.app.get('port'));
                            setTimeout(done, 500);
                        } else {
                            apiTimelineTest = supertest(swsTestFixture.SWS_TEST_DEFAULT_URL);
                            done();
                        }
                    });
            });
            it('should collect initial statistics values', function (done) {
                apiTimelineTest.get(swsTestFixture.SWS_TEST_STATS_API)
                    .query({fields: 'method'})
                    .expect(200)
                    .end(function (err, res) {
                        if (err) return done(err);

                        res.body.should.not.be.empty;
                        res.body.should.have.property('method');
                        methodStatsInitial = res.body.method;
                        done();
                    });
            });
        });

        describe('Send Test Requests', function () {

            it('should send random number of test requests '+method_test_duration+' times', function (done) {
                generateTestRequests()
                    .then(function(){
                        debug('generateRandomRequests - finished!');
                        done();
                    })
            });

        });

        // Get API Stats, and check that number of requests / responses is correctly calculated
        describe('Check Statistics', function () {

            it('should return collected statistics', function (done) {
                apiTimelineTest.get(swsTestFixture.SWS_TEST_STATS_API)
                    .query({fields: 'method'})
                    .expect(200)
                    .end(function (err, res) {
                        if (err) return done(err);

                        res.body.should.not.be.empty;
                        res.body.should.have.property('method');
                        methodStatsCurrent = res.body.method;
                        done();
                    });
            });

            it('should have correct values of method statistics', function (done) {

                for( var method in expected_method_values) {
                    debug('Comparing[%s]: Expected %s Actual:%s', method, JSON.stringify(expected_method_values[method]),JSON.stringify(methodStatsCurrent[method]) );
                    methodStatsCurrent.should.have.property(method);
                    var adjustedStats = swsTestUtils.getRRStatsDiff(methodStatsInitial[method],methodStatsCurrent[method]);

                    (expected_method_values[method].requests).should.be.equal(adjustedStats.requests);
                    (expected_method_values[method].errors).should.be.equal(adjustedStats.errors);
                    (expected_method_values[method].success).should.be.equal(adjustedStats.success);
                    (expected_method_values[method].redirect).should.be.equal(adjustedStats.redirect);
                    (expected_method_values[method].client_error).should.be.equal(adjustedStats.client_error);
                    (expected_method_values[method].server_error).should.be.equal(adjustedStats.server_error);
                    (expected_method_values[method].total_req_clength).should.be.equal(adjustedStats.total_req_clength);
                    (expected_method_values[method].total_res_clength).should.be.equal(adjustedStats.total_res_clength);
                    (methodStatsCurrent[method].avg_req_clength).should.be.equal(Math.floor(methodStatsCurrent[method].total_req_clength/methodStatsCurrent[method].requests));
                    (methodStatsCurrent[method].avg_res_clength).should.be.equal(Math.floor(methodStatsCurrent[method].total_res_clength/methodStatsCurrent[method].responses));
                }

                done();
            });

        });

    });

    run();

});

<commit_msg>Coverage<commit_after>'use strict';
var util = require('util');
var chai = require('chai');
chai.should();
var expect = chai.expect;
var supertest = require('supertest');
var cuid = require('cuid');

var Q = require('q');
var http = require('http');

// We will use it to store expected values
var swsReqResStats = require('../lib/swsReqResStats');
var swsUtil = require('../lib/swsUtil');

var debug = require('debug')('swstest:baseline');

var swsTestFixture = require('./testfixture');
var swsTestUtils = require('./testutils');

// duration of method test - number of requests
var method_test_duration = 50;
if( process.env.SWS_METHOD_TEST_DURATION){
    method_test_duration = parseInt(process.env.SWS_METHOD_TEST_DURATION);
}

var expected_method_values = {};

function sendTestRequestsOnce(iteration, deferred){

    if(iteration<=0){
        deferred.resolve();
        return;
    }

    //var methods = ['get','post','put','delete','head','options'];
    var methods = ['GET','POST','PUT','DELETE','OPTIONS'];

    // Generate random number of requests each iteration
    var reqcntr = 0;

    methods.forEach(function(method) {

        if(!(method in expected_method_values) ) {
            expected_method_values[method] = new swsReqResStats();
        }
        var methodCurrent = expected_method_values[method];

        var numReq = swsTestUtils.getRandomArbitrary(0,5);
        for(var i=0;i<numReq;i++) {

            reqcntr++;

            var randomcode = swsTestUtils.getRandomHttpStatusCode();
            var hdr = {
                code: randomcode,
                message: swsTestUtils.getHttpStatusMessage(randomcode),
                delay: swsTestUtils.getRandomArbitrary(0, 100),
                payloadsize: swsTestUtils.getRandomArbitrary(10, 200)
            };
            var xswsResHdr = JSON.stringify(hdr);

            debug('>>>>> %s %s x-sws-res:%s', method, swsTestFixture.SWS_TEST_MOCK_API, xswsResHdr);

            const options = {
                hostname: swsTestFixture.SWS_TEST_DEFAULT_HOST, //'localhost'
                port: swsTestFixture.SWS_TEST_DEFAULT_PORT, //3030,
                path: swsTestFixture.SWS_TEST_MOCK_API,
                method: method,
                headers: {
                    'x-sws-res': xswsResHdr
                }
            };
            var body = null;
            if ((method === 'post') || (method === 'put')) {
                var reqPayloadSize = swsTestUtils.getRandomArbitrary(10, 200);
                var str = '';
                for (var i = 0; i < reqPayloadSize; i++) str += 'r';
                body = JSON.stringify([str]);
                options.headers["Content-Type"] = "application/json";
                options.headers["Content-Length"] = Buffer.byteLength(body);
            }

            // Store in expected values
            methodCurrent.requests++;
            methodCurrent[swsUtil.getStatusCodeClass(randomcode)]++;
            if(swsUtil.isError(randomcode)) methodCurrent.errors++;
            var req_clen = ( body!==null ? Buffer.byteLength(body) : 0 );
            methodCurrent.total_req_clength += req_clen;
            var res_clen = hdr.payloadsize;
            methodCurrent.total_res_clength += res_clen;
            if( req_clen > methodCurrent.max_req_clength ) methodCurrent.max_req_clength = req_clen;
            if( res_clen > methodCurrent.max_res_clength ) methodCurrent.max_res_clength = res_clen;
            methodCurrent.avg_req_clength = Math.floor(methodCurrent.total_req_clength / methodCurrent.requests);
            methodCurrent.avg_res_clength = Math.floor(methodCurrent.total_res_clength / methodCurrent.requests);

            const req = http.request(options, function (res) {
                reqcntr--;
                if (reqcntr <= 0) {
                    sendTestRequestsOnce(iteration - 1, deferred);
                }
            });
            body !== null ? req.end(body) : req.end();
        }
    });

}

function generateTestRequests(){
    var deferred = Q.defer();
    sendTestRequestsOnce( method_test_duration, deferred );
    return deferred.promise;
}

setImmediate(function() {

    describe('Method statistics test', function () {

        this.timeout(60000);

        var appTimelineTest = null;
        var apiTimelineTest = null;

        var timelineStatsInitial = null;
        var timelineStatsCurrent = null;

        var methodStatsInitial = null;
        var methodStatsCurrent = null;

        var client_error_id = cuid();
        var server_error_id = cuid();

        // 1 second
        var timeline_bucket_duration = 1000;

        describe('Initialize', function () {
            it('should initialize example app', function (done) {
                supertest(swsTestFixture.SWS_TEST_DEFAULT_URL).get(swsTestFixture.SWS_TEST_STATS_API)
                    .expect(200)
                    .end(function (err, res) {
                        if (err) {
                            process.env.SWS_TEST_TIMEBUCKET = timeline_bucket_duration;
                            appTimelineTest = require('../examples/testapp/testapp');
                            apiTimelineTest = supertest('http://localhost:' + appTimelineTest.app.get('port'));
                            setTimeout(done, 500);
                        } else {
                            apiTimelineTest = supertest(swsTestFixture.SWS_TEST_DEFAULT_URL);
                            done();
                        }
                    });
            });
            it('should collect initial statistics values', function (done) {
                apiTimelineTest.get(swsTestFixture.SWS_TEST_STATS_API)
                    .query({fields: 'method'})
                    .expect(200)
                    .end(function (err, res) {
                        if (err) return done(err);

                        res.body.should.not.be.empty;
                        res.body.should.have.property('method');
                        methodStatsInitial = res.body.method;
                        done();
                    });
            });
        });

        describe('Send Test Requests', function () {

            it('should send random number of test requests '+method_test_duration+' times', function (done) {
                generateTestRequests()
                    .then(function(){
                        debug('generateRandomRequests - finished!');
                        done();
                    })
            });

        });

        // Get API Stats, and check that number of requests / responses is correctly calculated
        describe('Check Statistics', function () {

            it('should return collected statistics', function (done) {
                apiTimelineTest.get(swsTestFixture.SWS_TEST_STATS_API)
                    .query({fields: 'method'})
                    .expect(200)
                    .end(function (err, res) {
                        if (err) return done(err);

                        res.body.should.not.be.empty;
                        res.body.should.have.property('method');
                        methodStatsCurrent = res.body.method;
                        done();
                    });
            });

            it('should have correct values of method statistics', function (done) {

                for( var method in expected_method_values) {
                    debug('Comparing[%s]: Expected %s Actual:%s', method, JSON.stringify(expected_method_values[method]),JSON.stringify(methodStatsCurrent[method]) );
                    methodStatsCurrent.should.have.property(method);
                    var adjustedStats = swsTestUtils.getRRStatsDiff(methodStatsInitial[method],methodStatsCurrent[method]);

                    (expected_method_values[method].requests).should.be.equal(adjustedStats.requests);
                    (expected_method_values[method].errors).should.be.equal(adjustedStats.errors);
                    (expected_method_values[method].success).should.be.equal(adjustedStats.success);
                    (expected_method_values[method].redirect).should.be.equal(adjustedStats.redirect);
                    (expected_method_values[method].client_error).should.be.equal(adjustedStats.client_error);
                    (expected_method_values[method].server_error).should.be.equal(adjustedStats.server_error);
                    (expected_method_values[method].total_req_clength).should.be.equal(adjustedStats.total_req_clength);
                    (expected_method_values[method].total_res_clength).should.be.equal(adjustedStats.total_res_clength);
                    (methodStatsCurrent[method].avg_req_clength).should.be.equal(Math.floor(methodStatsCurrent[method].total_req_clength/methodStatsCurrent[method].requests));
                    (methodStatsCurrent[method].avg_res_clength).should.be.equal(Math.floor(methodStatsCurrent[method].total_res_clength/methodStatsCurrent[method].responses));
                }

                done();
            });

        });

    });

    run();

});

<|endoftext|>


<commit_before>import React from 'react';
import { findDOMNode } from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import Column from '../src/Column';

describe('Column', () => {

  it('Should output a null', () => {
    const instance = ReactTestUtils.renderIntoDocument(
      <Column />
    );

    const instanceDom = findDOMNode(instance);
    assert.equal(instanceDom, null);
  });

});
<commit_msg>Update tests<commit_after>import React from 'react';
import { findDOMNode } from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import Column from '../src/Column';

describe('Column', () => {
  it('Should output a null', () => {
    const instance = ReactTestUtils.renderIntoDocument(<Column />);

    const instanceDom = findDOMNode(instance);
    assert.equal(instanceDom, null);
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fileSys = require('fs'),
    format = '.mp3',
    files_organized = 0,
    folders_created = 0;

fileSys.readdir(process.cwd(), function (err, files) {

  // if error then shout out!
  if (err) { console.log(err); return false; }

  // find files only.
  for(idx in files){

    // get the file name.
    var file = files[idx];

    // if not a directory.
    if(!fileSys.lstatSync(file).isDirectory()){

      // get the position of the extension (format)
      var format_pos = file.lastIndexOf(format);

      // if extension found
      if(format_pos > 0){

        // get the artist
        var dash = file.lastIndexOf('-'),
        artist = file.substring(0, format_pos).substring(0,dash).trim();

        // check if the folder exists
        if(!fileSys.existsSync(artist)){
          fileSys.mkdirSync(artist);
          folders_created++;
        }

        // move the file
        fileSys.renameSync(file, artist+'/'+file);
        files_organized++;

      } // if format_pos

    } // if .isDirectory()

  } // for idx in files

  console.log('Tololoche has organized ' + files_organized + ' files and created ' + folders_created + ' folders.');

}); // eof readdir<commit_msg>Fix: Files without dash (-) character make tololoche crash<commit_after>#!/usr/bin/env node

var fileSys = require('fs'),
    format = '.mp3',
    files_organized = 0,
    files_ignored = 0,
    folders_created = 0;

fileSys.readdir(process.cwd(), function (err, files) {

  // if error then shout out!
  if (err) { console.log(err); return false; }

  // find files only.
  for(idx in files){

    // get the file name.
    var file = files[idx];

    // if not a directory.
    if(!fileSys.lstatSync(file).isDirectory()){

      // get the position of the extension (format)
      var format_pos = file.lastIndexOf(format);

      // if extension found
      if(format_pos > 0){

        // get the artist
        var dash = file.indexOf('-'),
        artist = file.substring(0, format_pos).substring(0,dash).trim();

        if(artist.length){

          // check if the folder exists
          if(!fileSys.existsSync(artist)){
            fileSys.mkdirSync(artist);
            folders_created++;
          }

          // move the file
          fileSys.renameSync(file, artist+'/'+file);
          files_organized++;

        }else{

          files_ignored++;

        }

      } // if format_pos

    } // if .isDirectory()

  } // for idx in files

  console.log('Tololoche has organized ' + files_organized + ' files, ignored '+files_ignored+' and created ' + folders_created + ' folders.');

}); // eof readdir<|endoftext|>


<commit_before>var PotOfEther = artifacts.require("./PotOfEther.sol");

contract("PotOfEther", accounts => {
  describe("createPot", () => {
    it("fail when buyIn == 0", async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot("banana", {
          from: accounts[0],
          value: 0
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty buyIn but didn't fail");
    });

    it("fail when name.length == 0", async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot("", {
          from: accounts[0],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty name but didn't fail");
    });

    it("fail when name already exists", async () => {
      var instance = await PotOfEther.new();

      await instance.createPot("banana", {
        from: accounts[0],
        value: 1000
      });

      try {
        await instance.createPot("banana", {
          from: accounts[0],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }

      assert(false, "two pots with same name but didn't fail");
    });

    it("emit LogPotCreated event", async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot("banana", {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[0].args.name, "banana");
      assert.equal(result.logs[0].args.buyIn.valueOf(), 1000);
      assert.equal(result.logs[0].args.firstPlayer, accounts[0]);
    });

    it("emit LogPotJoin event", async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot("banana", {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[1].args.name, "banana");
      assert.equal(result.logs[1].args.newPlayer, accounts[0]);
    });
  })

  describe("joinPot", () => {
    it("fail when pot doesn't exists", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      try {
        await instance.joinPot(name, { from: accounts[0], value: 0 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot doesn't exists but didn't fail");
    });

    it("fail when pot is closed", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      await instance.createPot(name, { from: accounts[0], value: 1000 });
      await instance.joinPot(name, { from: accounts[1], value: 1000 });
      await instance.joinPot(name, { from: accounts[2], value: 1000 });

      var i = 1;
      while (true) {
        // now we create dummy transactions,
        // closePot needs to wait 2 blocks after last player has joined
        await instance.createPot("dummy" + i, { from: accounts[0], value: 1000 });
        i++;

        if (await instance.canClosePot.call(name) === true) {
          break;
        }
      }

      await instance.closePot(name);

      try {
        await instance.joinPot(name, {
          from: accounts[3],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot is closed but join didn't fail");
    });

    it("fail when pot is full", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      await instance.createPot(name, { from: accounts[0], value: 1000 });
      await instance.joinPot(name, { from: accounts[1], value: 1000 });
      await instance.joinPot(name, { from: accounts[2], value: 1000 });

      try {
        await instance.joinPot(name, { from: accounts[3], value: 1000 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot is full but join didn't fail");
    });
  })
});

<commit_msg>test wrong buyIn<commit_after>var PotOfEther = artifacts.require("./PotOfEther.sol");

contract("PotOfEther", accounts => {
  describe("createPot", () => {
    it("fail when buyIn == 0", async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot("banana", { from: accounts[0], value: 0 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty buyIn but didn't fail");
    });

    it("fail when name.length == 0", async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot("", { from: accounts[0], value: 1000 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty name but didn't fail");
    });

    it("fail when name already exists", async () => {
      var instance = await PotOfEther.new();

      await instance.createPot("banana", { from: accounts[0], value: 1000 });

      try {
        await instance.createPot("banana", { from: accounts[0], value: 1000 });
      } catch (err) {
        assert(true);
        return;
      }

      assert(false, "two pots with same name but didn't fail");
    });

    it("emit LogPotCreated event", async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot("banana", { from: accounts[0], value: 1000 });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[0].args.name, "banana");
      assert.equal(result.logs[0].args.buyIn.valueOf(), 1000);
      assert.equal(result.logs[0].args.firstPlayer, accounts[0]);
    });

    it("emit LogPotJoin event", async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot("banana", { from: accounts[0], value: 1000 });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[1].args.name, "banana");
      assert.equal(result.logs[1].args.newPlayer, accounts[0]);
    });
  })

  describe("joinPot", () => {
    it("fail when pot doesn't exists", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      try {
        await instance.joinPot(name, { from: accounts[0], value: 0 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot doesn't exists but didn't fail");
    });

    it("fail when pot is closed", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      await instance.createPot(name, { from: accounts[0], value: 1000 });
      await instance.joinPot(name, { from: accounts[1], value: 1000 });
      await instance.joinPot(name, { from: accounts[2], value: 1000 });

      var i = 1;
      while (true) {
        // now we create dummy transactions,
        // closePot needs to wait 2 blocks after last player has joined
        await instance.createPot(`dummy-${i}`, { from: accounts[0], value: 1000 });
        i++;

        if (await instance.canClosePot.call(name) === true) {
          break;
        }
      }

      await instance.closePot(name);

      try {
        await instance.joinPot(name, {
          from: accounts[3],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot is closed but join didn't fail");
    });

    it("fail when pot is full", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      await instance.createPot(name, { from: accounts[0], value: 1000 });
      await instance.joinPot(name, { from: accounts[1], value: 1000 });
      await instance.joinPot(name, { from: accounts[2], value: 1000 });

      try {
        await instance.joinPot(name, { from: accounts[3], value: 1000 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "pot is full but join didn't fail");
    });

    it("fail when wrong buyIn", async () => {
      var instance = await PotOfEther.new();
      const name = "banana";

      await instance.createPot(name, { from: accounts[0], value: 1000 });

      try {
        await instance.joinPot(name, { from: accounts[1], value: 1001 });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "join with wrong buyIn didn't fail");
    });
  })
});

<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http');

describe('app.router', function(){
  describe('methods supported', function(){
    express.methods.forEach(function(method){
      it('should include ' + method, function(done){
        var app = express();
        var calls = [];

        app[method]('/foo', function(req, res){
          res.end(method);
        });

        request(app)
        [method]('/foo')
        .expect(method, done);
      })
    });
  })

  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe('when given a regexp', function(){
    it('should match the pathname only', function(done){
      var app = express();

      app.get(/^\/user\/[0-9]+$/, function(req, res){
        res.end('user');
      });

      request(app)
      .get('/user/12?foo=bar')
      .expect('user', done);
    })

    it('should populate req.params with the captures', function(done){
      var app = express();

      app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function(req, res){
        var id = req.params.shift()
          , op = req.params.shift();
        res.end(op + 'ing user ' + id);
      });

      request(app)
      .get('/user/10/edit')
      .expect('editing user 10', done);
    })
  })

  describe('case sensitivity', function(){
    it('should be disabled by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/USER')
      .expect('tj', done);
    })

    describe('when "case sensitive routing" is enabled', function(){
      it('should match identical casing', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/uSer')
        .expect('tj', done);
      })

      it('should not match otherwise', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })
    })
  })

  describe('trailing slashes', function(){
    it('should be optional by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/user/')
      .expect('tj', done);
    })

    describe('when "strict routing" is enabled', function(){
      it('should match trailing slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect('tj', done);
      })

      it('should match no slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect('tj', done);
      })

      it('should fail when omitting the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })

      it('should fail when adding the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect(404, done);
      })
    })
  })

  it('should allow escaped regexp', function(done){
    var app = express();

    app.get('/user/\\d+', function(req, res){
      res.end('woot');
    });

    request(app)
    .get('/user/10')
    .end(function(res){
      res.statusCode.should.equal(200);
      request(app)
      .get('/user/tj')
      .expect(404, done);
    });
  })

  it('should allow literal "."', function(done){
    var app = express();

    app.get('/api/users/:from..:to', function(req, res){
      var from = req.params.from
        , to = req.params.to;

      res.end('users from ' + from + ' to ' + to);
    });

    request(app)
    .get('/api/users/1..50')
    .expect('users from 1 to 50', done);
  })

  describe('*', function(){
    it('should denote a greedy capture group', function(done){
      var app = express();

      app.get('/user/*.json', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/user/tj.json')
      .expect('tj', done);
    })

    it('should work with several', function(done){
      var app = express();

      app.get('/api/*.*', function(req, res){
        var resource = req.params.shift()
          , format = req.params.shift();
        res.end(resource + ' as ' + format);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0 as json', done);
    })

    it('should allow naming', function(done){
      var app = express();

      app.get('/api/:resource(*)', function(req, res){
        var resource = req.params.resource;
        res.end(resource);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0.json', done);
    })

    it('should span multiple segments', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/javascripts/jquery.js')
      .expect('javascripts/jquery.js', done);
    })

    it('should be optional', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/')
      .expect('', done);
    })

    it('should require a preceeding /', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file')
      .expect(404, done);
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should match a single segment only', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect(404, done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe('.:name', function(){
    it('should denote a format', function(done){
      var app = express();

      app.get('/:name.:format', function(req, res){
        res.end(req.params.name + ' as ' + req.params.format);
      });

      request(app)
      .get('/foo.json')
      .expect('foo as json', function(){
        request(app)
        .get('/foo')
        .expect(404, done);
      });
    })
  })

  describe('.:name?', function(){
    it('should denote an optional format', function(done){
      var app = express();

      app.get('/:name.:format?', function(req, res){
        res.end(req.params.name + ' as ' + (req.params.format || 'html'));
      });

      request(app)
      .get('/foo')
      .expect('foo as html', function(){
        request(app)
        .get('/foo.json')
        .expect('foo as json', done);
      });
    })
  })
})
<commit_msg>fixed head<commit_after>
var express = require('../')
  , request = require('./support/http');

describe('app.router', function(){
  describe('methods supported', function(){
    express.methods.forEach(function(method){
      it('should include ' + method, function(done){
        var app = express();
        var calls = [];

        app[method]('/foo', function(req, res){
          res.end(method);
        });

        request(app)
        [method]('/foo')
        .expect('head' == method ? '' : method, done);
      })
    });
  })

  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe('when given a regexp', function(){
    it('should match the pathname only', function(done){
      var app = express();

      app.get(/^\/user\/[0-9]+$/, function(req, res){
        res.end('user');
      });

      request(app)
      .get('/user/12?foo=bar')
      .expect('user', done);
    })

    it('should populate req.params with the captures', function(done){
      var app = express();

      app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function(req, res){
        var id = req.params.shift()
          , op = req.params.shift();
        res.end(op + 'ing user ' + id);
      });

      request(app)
      .get('/user/10/edit')
      .expect('editing user 10', done);
    })
  })

  describe('case sensitivity', function(){
    it('should be disabled by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/USER')
      .expect('tj', done);
    })

    describe('when "case sensitive routing" is enabled', function(){
      it('should match identical casing', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/uSer')
        .expect('tj', done);
      })

      it('should not match otherwise', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })
    })
  })

  describe('trailing slashes', function(){
    it('should be optional by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/user/')
      .expect('tj', done);
    })

    describe('when "strict routing" is enabled', function(){
      it('should match trailing slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect('tj', done);
      })

      it('should match no slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect('tj', done);
      })

      it('should fail when omitting the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })

      it('should fail when adding the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect(404, done);
      })
    })
  })

  it('should allow escaped regexp', function(done){
    var app = express();

    app.get('/user/\\d+', function(req, res){
      res.end('woot');
    });

    request(app)
    .get('/user/10')
    .end(function(res){
      res.statusCode.should.equal(200);
      request(app)
      .get('/user/tj')
      .expect(404, done);
    });
  })

  it('should allow literal "."', function(done){
    var app = express();

    app.get('/api/users/:from..:to', function(req, res){
      var from = req.params.from
        , to = req.params.to;

      res.end('users from ' + from + ' to ' + to);
    });

    request(app)
    .get('/api/users/1..50')
    .expect('users from 1 to 50', done);
  })

  describe('*', function(){
    it('should denote a greedy capture group', function(done){
      var app = express();

      app.get('/user/*.json', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/user/tj.json')
      .expect('tj', done);
    })

    it('should work with several', function(done){
      var app = express();

      app.get('/api/*.*', function(req, res){
        var resource = req.params.shift()
          , format = req.params.shift();
        res.end(resource + ' as ' + format);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0 as json', done);
    })

    it('should allow naming', function(done){
      var app = express();

      app.get('/api/:resource(*)', function(req, res){
        var resource = req.params.resource;
        res.end(resource);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0.json', done);
    })

    it('should span multiple segments', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/javascripts/jquery.js')
      .expect('javascripts/jquery.js', done);
    })

    it('should be optional', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/')
      .expect('', done);
    })

    it('should require a preceeding /', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file')
      .expect(404, done);
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should match a single segment only', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect(404, done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe('.:name', function(){
    it('should denote a format', function(done){
      var app = express();

      app.get('/:name.:format', function(req, res){
        res.end(req.params.name + ' as ' + req.params.format);
      });

      request(app)
      .get('/foo.json')
      .expect('foo as json', function(){
        request(app)
        .get('/foo')
        .expect(404, done);
      });
    })
  })

  describe('.:name?', function(){
    it('should denote an optional format', function(done){
      var app = express();

      app.get('/:name.:format?', function(req, res){
        res.end(req.params.name + ' as ' + (req.params.format || 'html'));
      });

      request(app)
      .get('/foo')
      .expect('foo as html', function(){
        request(app)
        .get('/foo.json')
        .expect('foo as json', done);
      });
    })
  })
})
<|endoftext|>


<commit_before>var _ = require('underscore'),
    Backbone = require('backbone'),
    should = require("chai").should(),
    Attributes = require('../backbone.attributes');

describe('Backbone.Attributes', function() {
  it('exports as Backbone.Attributes', function() {
    Attributes.should.equal(Backbone.Attributes);
  });

  it('works with plain objects', function() {
    var obj = _.defaults({}, Attributes);

    obj.on('change:name', function(ctx, name) {
      ctx.should.equal(obj);
      this.should.equal(obj);
      name.should.equal('Curly');
    });
    obj.set('name', 'Curly');
  });

  it('creates attributes per object', function() {
    var a = _.defaults({}, Attributes),
        b = _.defaults({}, Attributes);

    a.set('name', 'Curly');
    should.not.exist(b.get('name'));
    a.attributes.should.not.equal(b.attributes);
  });

  it('respects exiting attributes and defaults', function() {
    var obj = {
      attributes: {
        name: 'Moe'
      },
      defaults: {
        name: 'Shemp',
        profession: 'entertainer'
      }
    };
    _.defaults(obj, Attributes);

    obj.get('name').should.equal('Moe');
    obj.get('profession').should.equal('entertainer');
    obj.on('change:name', function(ctx, name) {
      name.should.equal('Curly');
      name.should.equal(this.get('name'));
    });
    obj.set('name', 'Curly');

    obj.defaults.title = 'Stooge';
    should.not.exist(obj.get('title'));
  });

  it('does not collide with Backbone.Collection methods', function() {
    var col = _.defaults(new Backbone.Collection, Attributes);

    col.get.should.equal(Backbone.Collection.prototype.get);
    col.set.should.equal(Backbone.Collection.prototype.set);

    col.on('change:name', function(ctx, name) {
      ctx.should.equal(col);
      name.should.equal('Curly');
      name.should.equal(this.getAttribute('name'));
    });
    col.setAttribute('name', 'Curly');
    col.setAttributes('name', 'Curly');
    col.getAttribute('name').should.equal('Curly');
  });

  it('updates object methods to originals after wrapper called', function() {
    var obj = _.defaults({}, Attributes);
    obj.get.should.not.equal(Backbone.Model.prototype.get);
    obj.get.should.equal(Attributes.get);
    obj.get('foo');
    obj.get.should.equal(Backbone.Model.prototype.get);
  });

  it('does not overwrite existing methods after a wrapped method called', function() {
    var col = _.defaults(new Backbone.Collection, Attributes);
    col.get.should.equal(Backbone.Collection.prototype.get);
    col.clear.should.not.equal(Backbone.Model.prototype.clear);
    col.clear.should.equal(Attributes.clear);
    col.clear();
    col.clear.should.equal(Backbone.Model.prototype.clear);
    col.get.should.equal(Backbone.Collection.prototype.get);
  });

  it('accepts a validate method', function() {
    var obj = {
      validate: function(attrs) {
        if (attrs.name === 'Curly') return "Nope";
      }
    };

    _.defaults(obj, Attributes);

    obj.set({name: 'Curly'});
    obj.isValid().should.equal(false);
    obj.validationError.should.equal("Nope");

    obj.set({name: 'Moe'});
    obj.isValid().should.equal(true);
  });
});

<commit_msg>few more tests<commit_after>var _ = require('underscore'),
    Backbone = require('backbone'),
    should = require("chai").should(),
    Attributes = require('../backbone.attributes');

describe('Backbone.Attributes', function() {
  it('exports as Backbone.Attributes', function() {
    Attributes.should.equal(Backbone.Attributes);
  });

  it('works with plain objects', function() {
    var obj = _.defaults({}, Attributes);

    obj.on('change:name', function(ctx, name) {
      ctx.should.equal(obj);
      this.should.equal(obj);
      name.should.equal('Curly');
    });
    obj.set('name', 'Curly');
  });

  it('creates attributes per object', function() {
    var a = _.defaults({}, Attributes),
        b = _.defaults({}, Attributes);

    a.set('name', 'Curly');
    should.not.exist(b.get('name'));
    a.attributes.should.not.equal(b.attributes);
  });

  it('respects exiting attributes and defaults', function() {
    var obj = {
      attributes: {
        name: 'Moe'
      },
      defaults: {
        name: 'Shemp',
        profession: 'entertainer'
      }
    };
    _.defaults(obj, Attributes);

    obj.get('name').should.equal('Moe');
    obj.get('profession').should.equal('entertainer');
    obj.on('change:name', function(ctx, name) {
      name.should.equal('Curly');
      name.should.equal(this.get('name'));
    });
    obj.set('name', 'Curly');

    obj.defaults.title = 'Stooge';
    should.not.exist(obj.get('title'));
  });

  it('does not collide with Backbone.Collection methods', function() {
    var col = _.defaults(new Backbone.Collection, Attributes);

    col.get.should.equal(Backbone.Collection.prototype.get);
    col.set.should.equal(Backbone.Collection.prototype.set);

    col.on('change:name', function(ctx, name) {
      ctx.should.equal(col);
      name.should.equal('Curly');
      name.should.equal(this.getAttribute('name'));
    });
    col.setAttribute('name', 'Curly');
    col.getAttribute('name').should.equal('Curly');
    col.setAttributes('name', 'Curly');
    col.getAttribute('name').should.equal('Curly');
  });

  it('updates object methods to originals after wrapper called', function() {
    var obj = _.defaults({}, Attributes);
    obj.get.should.not.equal(Backbone.Model.prototype.get);
    obj.get.should.equal(Attributes.get);
    obj.get('foo');
    obj.get.should.equal(Backbone.Model.prototype.get);
  });

  it('does not overwrite existing methods after a wrapped method called', function() {
    var col = _.defaults(new Backbone.Collection, Attributes);
    col.get.should.equal(Backbone.Collection.prototype.get);
    col.clear.should.not.equal(Backbone.Model.prototype.clear);
    col.clear.should.equal(Attributes.clear);
    col.clear();
    col.clear.should.equal(Backbone.Model.prototype.clear);
    col.get.should.equal(Backbone.Collection.prototype.get);
  });

  it('should work with prototypes', function() {
    var Collection = Backbone.Collection.extend();
    _.defaults(Collection.prototype, Attributes)
    var col1 = new Collection, col2 = new Collection;

    col1.get.should.equal(Backbone.Collection.prototype.get);
    col1.clear.should.not.equal(Backbone.Model.prototype.clear);
    col1.clear.should.equal(Attributes.clear);
    col1.clear();
    col1.clear.should.equal(Backbone.Model.prototype.clear);
    col1.get.should.equal(Backbone.Collection.prototype.get);

    col2.get.should.equal(Backbone.Collection.prototype.get);
    col2.clear.should.not.equal(Backbone.Model.prototype.clear);
    col2.clear.should.equal(Attributes.clear);
    col2.clear();
    col2.clear.should.equal(Backbone.Model.prototype.clear);
    col2.get.should.equal(Backbone.Collection.prototype.get);
  });

  it('accepts a validate method', function() {
    var obj = {
      validate: function(attrs) {
        if (attrs.name === 'Curly') return "Nope";
      }
    };

    _.defaults(obj, Attributes);

    obj.set({name: 'Curly'});
    obj.isValid().should.equal(false);
    obj.validationError.should.equal("Nope");

    obj.set({name: 'Moe'});
    obj.isValid().should.equal(true);
  });
});

<|endoftext|>


<commit_before>/*globals describe,it*/
/*
 * brollb
 */

'use strict';
var requirejs = require('requirejs');

requirejs.config({
  baseUrl: '../src/',
  paths:{
    "logManager": "common/LogManager",
    "util/assert": "common/util/assert"
  }
});

var AutoRouter = requirejs('client/js/Widgets/DiagramDesigner/AutoRouter'),
    assert = requirejs('util/assert'),
    router;

var addBox = function(options) {
    var x = options.x,
        y = options.y,
        width = options.width || 100,
        height = options.height || 100,
        boxDef = {x1: x,
                  x2: x+width,
                  y1: y,
                  y2: y+height,
                  ConnectionInfo: [
                      {id: 'top',
                       area: [ [x+10, y+10], [x+width-10, y+10]]},
                      {id: 'bottom',
                       area: [ [x+10, y+height-10], [x+width-10, y+height-10]]}
                  ]};
    return router.addBox(boxDef);
};

var addBoxes = function(locations) {
      var boxes = [],
          i;

      for (i = locations.length; i--;) {
          boxes.push(addBox({x: locations[i][0],
                             y: locations[i][1]}));
      }

      return boxes;
};

var getBoxCount = function() {
    return Object.keys(router.router.boxes).length;
};

// Test example
describe('AutoRouter Tests',function(){

  it('should create boxes placed on graph',function(){
      router = new AutoRouter();
      addBox({x: 100,
              y: 100});

      var boxCount = Object.keys(router.router.boxes).length;
      assert(boxCount === 1);
  });

  it('should move box on graph',function(){
      router = new AutoRouter();
      var box = addBox({x: 100,
                        y: 100});

      router.move(box, {x: 300, y: 300});
  });

  it('should remove box from graph',function(){
      router = new AutoRouter();
      var box = addBox({x: 100,
                        y: 100});

      router.remove(box);
      var boxCount = Object.keys(router.router.boxes).length;
      assert(boxCount === 0);
  });

  it('should connect two boxes',function(){
      router = new AutoRouter();

      var box1 = addBox({x: 100, y: 100});
      var box2 = addBox({x: 500, y: 800});
      router.addPath({src: box1.ports, dst: box2.ports});
  });

  it('should connect multiple boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [500,800],
                       [500,300],
                       [300,300]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
      }
  });

  it('should move connected boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [500,800],
                       [500,300],
                       [300,300]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
          router.move(boxes[i], {x: 600, y: 600});
      }

  });

  it('should connect overlapping boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [110,110],
                       [120,120],
                       [130,130]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
      }

  });

  it('should connect contained boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [110,110],
                       [120,120],
                       [130,130]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
      }

  });

    it('should remove path from graph',function(){
      router = new AutoRouter();

      var box1 = addBox({x: 100, y: 100});
      var box2 = addBox({x: 500, y: 800});
      var path = router.addPath({src: box1.ports, dst: box2.ports});
      router.remove(path);
      assert(router.router.paths.length === 0);
  });

  // TODO Add this feature
  //it('should create ports outside the box',function(){
      //router = new AutoRouter();

      //var boxDef = {x1: 100,
                    //x2: 200,
                    //y1: 100,
                    //y2: 200,
                    //ConnectionInfo: [
                       //{id: 'top',
                        //area: [ [10, 10], [80, 80] ]}
                    //]};

      //router.addBox(boxDef);
  //});

});

// Tests for the autorouter
//  - basic overlapping
//  - boxes are exactly double the buffer width apart
//  - encompassed circle
//  - maze
//  - port outside the box
//  - box's connection area outside the box
//  - box connected to itself
//  - boxes directly on top of each other (connected to each other)
<commit_msg>Added more tests<commit_after>/*globals describe,it*/
/*
 * brollb
 */

'use strict';
var requirejs = require('requirejs');

requirejs.config({
  baseUrl: '../src/',
  paths:{
    "logManager": "common/LogManager",
    "util/assert": "common/util/assert"
  }
});

var AutoRouter = requirejs('client/js/Widgets/DiagramDesigner/AutoRouter'),
    assert = requirejs('util/assert'),
    router;

// Set up helpers
var connectAll = function(boxes) {
    for (var i = boxes.length; i--;) {
        for (var j = boxes.length; j--;) {
            router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
        }
    }

    router.autoroute();
};

var addBox = function(options) {
    var x = options.x,
        y = options.y,
        width = options.width || 100,
        height = options.height || 100,
        boxDef = {x1: x,
                  x2: x+width,
                  y1: y,
                  y2: y+height,
                  ConnectionInfo: [
                      {id: 'top',
                       area: [ [x+10, y+10], [x+width-10, y+10]]},
                      {id: 'bottom',
                       area: [ [x+10, y+height-10], [x+width-10, y+height-10]]}
                  ]};
    return router.addBox(boxDef);
};

var addBoxes = function(locations) {
      var boxes = [],
          i;

      for (i = locations.length; i--;) {
          boxes.push(addBox({x: locations[i][0],
                             y: locations[i][1]}));
      }

      return boxes;
};

var getBoxCount = function() {
    return Object.keys(router.router.boxes).length;
};

// Validation Helpers
var evaluateEdges = function(edges, fn) {
      var edge = edges.order_first;
      var result = false;
      while (edge && !result) {
          result = fn(edge);
          edge = edge.order_next || edge.orderNext;
      }

    return result;
};

// Test example
describe('AutoRouter Tests',function(){

  it('should create boxes placed on graph',function(){
      router = new AutoRouter();
      addBox({x: 100,
              y: 100});

      var boxCount = Object.keys(router.router.boxes).length;
      assert(boxCount === 1);
  });

  it('should move box on graph',function(){
      router = new AutoRouter();
      var box = addBox({x: 100,
                        y: 100});

      router.move(box, {x: 300, y: 300});
  });

  it('should remove box from graph',function(){
      router = new AutoRouter();
      var box = addBox({x: 100,
                        y: 100});

      router.remove(box);
      var boxCount = Object.keys(router.router.boxes).length;
      assert(boxCount === 0);
  });

  it('should detect bracket opening',function(){
      router = new AutoRouter();

      var box1 = addBox({x: 100, y: 100});
      var box2 = box1;
      connectAll([box1, box2]);

      // Check that the graph contains an edge that is bracket closing or opening
      var hasBracketOpeningOrClosing = false;
      var testFn = function(edge) {
          return edge.bracketOpening || edge.bracketOpening || edge.bracket_closing || edge.bracket_opening;
      };
      hasBracketOpeningOrClosing = evaluateEdges(router.router.horizontal, testFn) ||
                                   evaluateEdges(router.router.vertical, testFn);

      assert(hasBracketOpeningOrClosing, 'Did not detect bracket opening/closing');
  });

  it('should remove port from box',function(){
      router = new AutoRouter();
      throw new Error('Need to make this test');
  });

  it('should connect two boxes',function(){
      router = new AutoRouter();

      var box1 = addBox({x: 100, y: 100});
      var box2 = addBox({x: 500, y: 800});
      connectAll([box1, box2]);
  });

  it.only('should connect multiple boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [500,300],
                       [300,300]],
          boxes = addBoxes(locations),
          i,
          j;

      connectAll(boxes);
  });

  it('should move connected boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [500,800],
                       [500,300],
                       [300,300]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
          router.move(boxes[i], {x: 600, y: 600});
      }

  });

  it('should connect overlapping boxes',function(){
      router = new AutoRouter();
      var locations = [[100,100],
                       [110,110],
                       [120,120],
                       [130,130]],
          boxes = addBoxes(locations),
          i,
          j;

      for (i = boxes.length; i--;) {
          for (j = boxes.length; j--;) {
              router.addPath({src: boxes[i].ports, dst: boxes[j].ports});
          }
      }

  });

  it('should connect contained boxes',function(){
      router = new AutoRouter();
      var width = 900,
          height = 900,
          locations = [[100,100],
                       [200, 200],
                       [400, 400],
                       [4100, 4100],
                       [4200, 4200],
                       [4400, 4400]],
          boxes = [],
          i,
          j;

      // Create big boxes
      for (i = locations.length; i--;) {
          boxes.push(addBox({x: locations[i][0],
                             y: locations[i][1],
                             width: width,
                             height: height}));

      }

      assert(boxes[0].box.rect.getWidth() === 900);

      // Create normal sized boxes
      for (i = locations.length; i--;) {
          boxes.push(addBox({x: locations[i][0],
                             y: locations[i][1]}));
      }

      connectAll(boxes);
  });

  it('should remove path from graph',function(){
      router = new AutoRouter();

      var box1 = addBox({x: 100, y: 100});
      var box2 = addBox({x: 500, y: 800});
      var path = router.addPath({src: box1.ports, dst: box2.ports});
      router.remove(path);
      assert(router.router.paths.length === 0);
  });

  it('should create ports outside the box',function(){
      router = new AutoRouter();
      var box = addBox({x: 100, y: 100});
      var port = addBox({x: 110, y: 110, width: 30, height: 30});
      router.setComponent(box, port);
  });

  it('should connect port to parent box',function(){
      router = new AutoRouter();
      var box = addBox({x: 100, y: 100});
      var port = addBox({x: 110, y: 110, width: 30, height: 30});
      router.setComponent(box, port);
      connectAll([box, port]);
  });

  it('should connect box encircled by other boxes',function(){
      router = new AutoRouter();
      var locations = [],
          change = 90,
          min = 100,
          max = 1000,
          diff = 2000,
          x = 400,
          y = 400,
          src = addBox({x: x, y: y}),
          dst = addBox({x: x+diff, y: y+diff});

      // Encircle the src box
      for (y = min, x = min; y < max; y += change) {
          addBox({x: x, y: y});
          addBox({x: max, y: y});
      }

      for (y = min, x = min; x < max; x += change) {
          addBox({x: x, y: y});
          addBox({x: x, y: max});
      }

      connectAll([src, dst]);

      // Encircle the dst box
  });

  // TODO Add this feature
  //it('should create connection areas outside the box',function(){
      //router = new AutoRouter();

      //var boxDef = {x1: 100,
                    //x2: 200,
                    //y1: 100,
                    //y2: 200,
                    //ConnectionInfo: [
                       //{id: 'top',
                        //area: [ [10, 10], [80, 80] ]}
                    //]};

      //router.addBox(boxDef);
  //});

});

// Tests for the autorouter
//  - changing the size of boxes
//  - changing the size of ports
//  - encompassed circle
//  - maze
//  - port outside the box
//  - box's connection area outside the box
//  - box connected to itself
//  - boxes directly on top of each other (connected to each other)
<|endoftext|>


<commit_before>describe("Classes", function () {
    before(function () {
        fixture.setBase("test/fixtures");
    });

    beforeEach(function () {
        fixture.load('basic_elements.html');
        this.el = document.getElementById("id1");
        this.$el = $(this.el);
        this.el2 = document.getElementById("id2");
        this.$el2 = $(this.el2);
    });

    afterEach(function () {
        fixture.cleanup();
    });

    describe("addClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.addClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.addClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.addClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.addClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not create an empty class attribute with an empty string", function () {
            this.$el.addClass("");

            expect(this.el).to.not.have.attribute("class");
        });

        it("should add the class name to the element", function () {
            var className = "test1";
            this.$el.addClass(className);

            expect(this.el).to.have.class(className);
        });

        it("should trim whitespace from the class name", function () {
            var className = "test1";
            this.$el.addClass(" " + className + " ");

            expect(this.el).to.have.class(className);
        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList),
                newClassName = "new1";
            this.$el2.addClass(newClassName);

            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
            expect(this.el2).to.have.class(newClassName);
        });

        it("should add space-separated class names to the element", function () {
            var className1 = "new1",
                className2 = "new2";
            this.$el.addClass(className1 + " " + className2);

            expect(this.el).to.have.class(className1);
            expect(this.el).to.have.class(className2);
        });

        it("shouldn't add an already existing class name", function () {
            var className = "new1";
            this.el.className = className;
            this.$el.addClass(className);

            expect(this.el.className).to.equal(className);
        });

        it("shouldn't add duplicate class names in one call", function () {
            var className = "new1";
            this.$el.addClass(className + " " + className);

            expect(this.el.className).to.equal(className);
        });

        it("should add class names to all elements", function () {
            var $els = $$("#id1, #id2"),
                className = "new1";
            $els.addClass(className);

            expect(this.el).to.have.class(className);
            expect(this.el).to.have.class(className);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.addClass("new1");

            expect(returnValue).to.equal(this.$el);
        });
    });

    describe("removeClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.removeClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not remove class attribute", function () {
            var className = "new1";
            this.el.classList.add(className);
            this.$el.removeClass(className);

            expect(this.el).to.have.attribute("class");
        });

        it("should remove the class name from the element", function () {
            var className = "new1";
            this.el.classList.add(className);
            this.$el.removeClass(className);

            expect(this.el).to.not.have.class(className);
        });

        it("should trim whitespace from the class name", function () {
            var className = "new1";
            this.el.classList.add(className);
            this.$el.removeClass(" " + className + " ");

            expect(this.el).to.not.have.class(className);
        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList),
                newClassNames,
                className = "new1";
            this.el2.classList.add(className);
            this.$el2.removeClass(className);

            expect(originalClassNames.length).to.equal(this.el2.classList.length);
            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }

        });

        it("should remove space-separated class names to the element", function () {
            var className1 = "new1",
                className2 = "new2";
            this.el.classList.add(className1, className2);
            this.$el.removeClass(className1 + " " + className2);

            expect(this.el).to.not.have.class(className1);
            expect(this.el).to.not.have.class(className2);
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            var className = "new1",
                duplicateNames = className + " " + className;
            this.el.classList.add(className);

            expect(calling(this.$el.removeClass).on(this.$el).with(duplicateNames)).to.not.throw(Error);
        });

        it("should remove class names from all elements", function () {
            var els = [this.el, this.el2],
                $els = $$(els),
                className = "new1";

            this.el.classList.add(className);
            this.el2.classList.add(className);
            $els.removeClass(className);

            expect(this.el).to.not.have.class(className);
            expect(this.el2).to.not.have.class(className);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.removeClass("");

            expect(returnValue).to.equal(this.$el);
        });

    });
});
<commit_msg>Tests for toggleClass()<commit_after>describe("Classes", function () {
    before(function () {
        fixture.setBase("test/fixtures");
    });

    beforeEach(function () {
        fixture.load('basic_elements.html');
        this.el = document.getElementById("id1");
        this.$el = $(this.el);
        this.el2 = document.getElementById("id2");
        this.$el2 = $(this.el2);
        this.el3 = document.getElementById("id3");
        this.$el3 = $(this.el3);
        this.newClass1 = "new1";
        this.newClass2 = "new2";
    });

    afterEach(function () {
        fixture.cleanup();
    });

    describe("addClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.addClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.addClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.addClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.addClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not create an empty class attribute with an empty string", function () {
            this.$el.addClass("");

            expect(this.el).to.not.have.attribute("class");
        });

        it("should add the class name to the element", function () {
            this.$el.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.$el.addClass(" " + this.newClass1 + " ");

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            this.$el2.addClass(this.newClass1);

            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
            expect(this.el2).to.have.class(this.newClass1);
        });

        it("should add space-separated class names to the element", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.$el.addClass(" " + this.newClass1 + "  " + this.newClass2 + "   ");

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
            expect(this.el.classList).to.have.lengthOf(2);
        });

        it("shouldn't add an already existing class name", function () {
            this.el.className = this.newClass1;
            this.$el.addClass(this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("shouldn't add duplicate class names in one call", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("should add class names to multiple elements", function () {
            var $els = $$("#id1, #id2");
            $els.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.addClass(this.newClass1);

            expect(returnValue).to.equal(this.$el);
        });
    });

    describe("removeClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.removeClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not remove class attribute", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.have.attribute("class");
        });

        it("should remove the class name from the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(" " + this.newClass1 + " ");

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should remove space-separated class names from the element", function () {
            this.el.classList.add(this.newClass1, this.newClass2);
            this.$el.removeClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.not.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);

            this.$el2.removeClass(" " + originalClassNames.join("   ") + "  ");

            expect(this.el2.classList).to.have.lengthOf(0);

        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            var newClassNames;
            this.el2.classList.add(this.newClass1);
            this.$el2.removeClass(this.newClass1);

            expect(originalClassNames.length).to.equal(this.el2.classList.length);
            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            var duplicateNames = this.newClass1 + " " + this.newClass1;
            this.el.classList.add(this.newClass1);

            expect(calling(this.$el.removeClass).on(this.$el).with(duplicateNames)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            this.el2.classList.add(this.newClass1);
            this.el3.classList.add(this.newClass1);
            $els.removeClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.removeClass("");

            expect(returnValue).to.equal(this.$el);
        });

    });

    describe("toggleClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.toggleClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should remove an existing class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1);
            expect(this.el2).to.not.have.class(this.newClass1);
        });

        it("should add a nonexistent class name", function () {
            this.$el.toggleClass(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            var whiteSpacedClass = "  " + this.newClass1 + "  ";
            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el.className).to.not.include(whiteSpacedClass);

            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should work with space-separated class names", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass("  " + this.newClass1 + "   " + this.newClass2 + "  ");

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should keep the original class names of the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);

            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(this.newClass1 + " " + this.newClass1)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.have.class(this.newClass1);
            expect(this.el3).to.have.class(this.newClass1);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });
    });

    describe("hasClass()", function () {

    });

    describe("show()", function () {

    });

    describe("hide()", function () {

    });

     describe("toggle()", function () {

    });

});

<|endoftext|>


<commit_before>var Backend = require('../../lib/backend');
var expect = require('expect.js');

describe('client query subscribe', function() {

  beforeEach(function() {
    this.backend = new Backend();
    this.connection = this.backend.connect();
  });

  it('getting twice returns the same doc', function() {
    var doc = this.connection.get('dogs', 'fido');
    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).equal(doc2);
  });

  it('calling doc.destroy unregisters it', function() {
    var doc = this.connection.get('dogs', 'fido');
    expect(this.connection.getExisting('dogs', 'fido')).equal(doc);

    doc.destroy();
    expect(this.connection.getExisting('dogs', 'fido')).equal(undefined);

    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).not.equal(doc2);
  });

  it('getting then destroying then getting returns a new doc object', function() {
    var doc = this.connection.get('dogs', 'fido');
    doc.destroy();
    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).not.equal(doc2);
    expect(doc).eql(doc2);
  });

});
<commit_msg>test doc.destroy() calls back<commit_after>var Backend = require('../../lib/backend');
var expect = require('expect.js');

describe('client query subscribe', function() {

  beforeEach(function() {
    this.backend = new Backend();
    this.connection = this.backend.connect();
  });

  it('getting twice returns the same doc', function() {
    var doc = this.connection.get('dogs', 'fido');
    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).equal(doc2);
  });

  it('calling doc.destroy unregisters it', function() {
    var doc = this.connection.get('dogs', 'fido');
    expect(this.connection.getExisting('dogs', 'fido')).equal(doc);

    doc.destroy();
    expect(this.connection.getExisting('dogs', 'fido')).equal(undefined);

    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).not.equal(doc2);
  });

  it('getting then destroying then getting returns a new doc object', function() {
    var doc = this.connection.get('dogs', 'fido');
    doc.destroy();
    var doc2 = this.connection.get('dogs', 'fido');
    expect(doc).not.equal(doc2);
    expect(doc).eql(doc2);
  });

  it('doc.destroy() calls back', function(done) {
    var doc = this.connection.get('dogs', 'fido');
    doc.destroy(done);
  });

});
<|endoftext|>