<commit_before>var chai = require('chai')
  , expect = require('chai').expect
  , acdc = require('../../lib/grant/acdc');

describe('grant.acdc', function() {

  describe('module', function() {
    var mod = acdc(function(){});

    it('should be named acdc', function() {
      expect(mod.name).to.equal('acdc');
    });

    it('should expose request and response functions', function() {
      expect(mod.request).to.be.a('function');
      expect(mod.response).to.be.a('function');
      expect(mod.error).to.be.a('function');
    });
  });

  it('should throw if constructed without a issue callback', function() {
    expect(function() {
      acdc();
    }).to.throw(TypeError, 'oauth2orize.acdc grant requires an issue callback');
  });

  describe('request parsing', function() {

  }); // request parsing

  describe('decision processing', function() {

    describe('issuing cross domain code', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ');
      });
    }); // issuing cross domain code

    describe('issuing cross domain code along with state', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256',
              state: 'f1o1o1'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ&state=f1o1o1');
      });
    }); // issuing cross domain code along with state

    describe('authorization denied by user', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, '.ignore');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: false };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?error=access_denied');
      });
    }); // authorization denied by user

    describe('authorization denied by user along with state', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, '.ignore');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256',
              state: 'f1o1o1'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: false };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?error=access_denied&state=f1o1o1');
      });
    }); // authorization denied by user along with state

    describe('authorization denied by server', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, false);
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.constructor.name).to.equal('AuthorizationError');
        expect(err.message).to.equal('Request denied by authorization server');
        expect(err.code).to.equal('access_denied');
        expect(err.status).to.equal(403);
      });
    }); // authorization denied by server

    describe('encountering an error while issuing cross domain code', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(new Error('something went wrong'));
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('something went wrong');
      });
    }); // encountering an error while issuing cross domain code

    describe('encountering an exception while issuing cross domain code', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          throw new Error('something went horribly wrong');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('something went horribly wrong');
      });
    }); // encountering an exception while issuing cross domain code

  }); // decision processing

});
<commit_msg>More tests.<commit_after>var chai = require('chai')
  , expect = require('chai').expect
  , acdc = require('../../lib/grant/acdc')
  , AuthorizationError = require('../../lib/errors/authorizationerror');

describe('grant.acdc', function() {

  describe('module', function() {
    var mod = acdc(function(){});

    it('should be named acdc', function() {
      expect(mod.name).to.equal('acdc');
    });

    it('should expose request and response functions', function() {
      expect(mod.request).to.be.a('function');
      expect(mod.response).to.be.a('function');
      expect(mod.error).to.be.a('function');
    });
  });

  it('should throw if constructed without a issue callback', function() {
    expect(function() {
      acdc();
    }).to.throw(TypeError, 'oauth2orize.acdc grant requires an issue callback');
  });

  describe('request parsing', function() {

  }); // request parsing

  describe('decision processing', function() {

    describe('issuing cross domain code', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ');
      });
    }); // issuing cross domain code

    describe('issuing cross domain code along with state', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256',
              state: 'f1o1o1'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ&state=f1o1o1');
      });
    }); // issuing cross domain code along with state

    describe('issuing cross domain code based on response', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, ares, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }
          if (ares.scope !== 'foo') { return done(new Error('incorrect ares argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true, scope: 'foo' };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ');
      });
    }); // issuing cross domain code based on response

    describe('issuing cross domain code based on response and request', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, ares, areq, done) {
          if (client.id !== '1') { return done(new Error('incorrect client argument')); }
          if (user.id !== '501') { return done(new Error('incorrect user argument')); }
          if (audience !== 'https://server.partner.com') { return done(new Error('incorrect audience argument')); }
          if (pkce.challenge !== 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM') { return done(new Error('incorrect pkce argument')); }
          if (pkce.method !== 'S256') { return done(new Error('incorrect pkce argument')); }
          if (ares.scope !== 'foo') { return done(new Error('incorrect ares argument')); }
          if (areq.foo !== 'bar') { return done(new Error('incorrect areq argument')); }

          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256',
              foo: 'bar'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true, scope: 'foo' };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?code=eyJ');
      });
    }); // issuing cross domain code based on response and request

    describe('authorization denied by user', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, '.ignore');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: false };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?error=access_denied');
      });
    }); // authorization denied by user

    describe('authorization denied by user along with state', function() {
      var response;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, '.ignore');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256',
              state: 'f1o1o1'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: false };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .decide();
      });

      it('should respond', function() {
        expect(response.statusCode).to.equal(302);
        expect(response.getHeader('Location')).to.equal('http://www.example.com/auth/callback?error=access_denied&state=f1o1o1');
      });
    }); // authorization denied by user along with state

    describe('authorization denied by server', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, false);
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.constructor.name).to.equal('AuthorizationError');
        expect(err.message).to.equal('Request denied by authorization server');
        expect(err.code).to.equal('access_denied');
        expect(err.status).to.equal(403);
      });
    }); // authorization denied by server

    describe('attempting to respond without redirect URL', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('Unable to issue redirect for OAuth 2.0 transaction');
      });
    }); // attempting to respond without redirect URL

    describe('encountering an error while issuing cross domain code', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(new Error('something went wrong'));
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('something went wrong');
      });
    }); // encountering an error while issuing cross domain code

    describe('encountering an exception while issuing cross domain code', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          throw new Error('something went horribly wrong');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('something went horribly wrong');
      });
    }); // encountering an exception while issuing cross domain code

    describe('encountering an error while completing transaction', function() {
      var response, err;

      before(function(done) {
        function issue(client, user, audience, pkce, done) {
          return done(null, 'eyJ');
        }

        chai.oauth2orize.grant(acdc(issue))
          .txn(function(txn) {
            txn.client = { id: '1', name: 'OAuth Client' };
            txn.redirectURI = 'http://www.example.com/auth/callback';
            txn.req = {
              audience: 'https://server.partner.com',
              codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
              codeChallengeMethod: 'S256'
            };
            txn.user = { id: '501', name: 'John Doe' };
            txn.res = { allow: true };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .decide(function(cb) {
            process.nextTick(function() { cb(new Error('failed to complete transaction')) });
          });
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('failed to complete transaction');
      });
    }); // encountering an error while completing transaction

  }); // decision processing

});
<|endoftext|>


<commit_before>require('babel/register');

var test = require('tape'),
    futureValue = require('../src/futureValue');

test('calculate futureValue', function(t) {
  t.plan(3);

// The Herfindahl Index is a measure of the size of firms in relation to the industry and an indicator of the amount of competition among them

  var calc1 = futureValue({
    compounding: false,
    rate: 0.10,
    principal: 1000,
    years: 5
  });

  t.equal(calc1, 1500, 'correctly calculates future Value with simple interest');

// HHI = s1^2 + s2^2 + s3^2 + ... + sn^2 (where sn is the market share of the ith firm).

// Read more: Herfindahl-Hirschman Index (HHI) Definition | Investopedia http://www.investopedia.com/terms/h/hhi.asp#ixzz3pq3k9iHA

});
<commit_msg>herfindahl-hirschman index module + updated tests<commit_after>require('babel/register');

var test = require('tape'),
    herfindahlIndex = require('../src/herfindahlIndex');

test('calculate Herfindahl Index', function(t) {
  t.plan(5);

  var calc1 = herfindahlIndex([30, 60]);

  t.equal(calc1, 4500, 'correctly calculates Herfindahl-Hirschman Index');

  var calc2 = herfindahlIndex([30, 30, 20, 20]);

  t.equal(calc2, 2600, 'correctly calculates Herfindahl-Hirschman Index');

  var calc3 = herfindahlIndex([100]);

  t.equal(calc3, 10000, 'correctly calculates Herfindahl-Hirschman Index');

  t.throws(function() {
      herfindahlIndex('not a number');
    }, 'throws with non-number arg');

    t.throws(function() {
      herfindahlIndex();
    }, 'throws with missing arg');

});
<|endoftext|>


<commit_before>/*eslint strict: [2, "function"]*/ // IIFE form
/*eslint-disable func-style*/ // So that everything is grouped in one var
/*global xhr*/
(function () {
    "use strict";
    /*jshint browser: true*/
    /*eslint-env browser*/
    /*global __coverage__*/ // Coverage data
    /*global gpfFlavors*/ // Flavors

    function _safeConsoleMethod (method) {
        return function (msg) {
            if (console.expects) {
                console.expects(method, msg, true);
            }
            console[method](msg);
        };
    }

    var _log = _safeConsoleMethod("log"),
        _error = _safeConsoleMethod("error"),
        _MAX_WAIT = 50,
        _versions = {
            release: {
                label: "release",
                path: "../build/gpf.js",
                setup: function () {}
            },
            debug: {
                label: "debug",
                path: "../build/gpf-debug.js",
                setup: function () {}
            },
            coverage: {
                label: "instrumented sources",
                setup: function () {
                    window.global = window;
                    gpfSourcesPath += "../tmp/coverage/instrument/src/";
                }
            }
        },
        _tests,

        _evalTestCase = function (testFileURL, testCaseSource) {
            var sourceURL = window.location.toString().split("/test/")[0] + "/test/" + testFileURL;
            /*jshint -W061*/
            eval("//# sourceURL=" + sourceURL + "\n" + testCaseSource); //eslint-disable-line no-eval
            /*jshint +W061*/
        },

        _waitForTestCases = function (testFiles, callback) {
            var testFileURL;
            function _testCaseLoaded (testCaseSource) {
                _evalTestCase(testFileURL, testCaseSource);
                _waitForTestCases(testFiles, callback);
            }
            if (testFiles.length) {
                testFileURL = testFiles.shift();
                xhr(window.gpfTestsPath + testFileURL).get()
                    .then(_testCaseLoaded, _error);
                return;
            }
            // Everything is loaded
            callback();
        },

        _detectLegacy = function () {
            var legacyVersion = (/version=([0-9.]+)/).exec(window.location.search);
            if (legacyVersion) {
                return legacyVersion[1];
            }
        },

        _patchLegacy = function (version) {
            // gpf is loaded
            return xhr("/test/legacy/legacy.json").get().asJson()
                .then(function (legacy) {
                    return legacy.filter(function (item) {
                        return item.before > version;
                    });
                })
                .then(function (legacy) {
                    var
                        _describes = [],
                        _describe = window.describe,
                        _it = window.it;
                    window.describe = function (label) {
                        var issue;
                        legacy.every(function (item) {
                            if (item.ignore.some(function (ignore) {
                                return ignore.describe === label && !ignore.it;

                            })) {
                                issue = item.issue;
                                return false;
                            }
                            return true;
                        });
                        if (issue) {
                            _log("describe(\"" + label + "\", ...) ignored, see issue #" + issue);
                        } else {
                            _describes.unshift(label);
                            _describe.apply(this, arguments);
                            _describes.shift();
                        }
                    };
                    window.it = function (label) {
                        var issue;
                        legacy.every(function (item) {
                            if (item.ignore.some(function (ignore) {
                                return ignore.describe === _describes[0] && ignore.it === label;

                            })) {
                                issue = item.issue;
                                return false;
                            }
                            return true;
                        });
                        if (issue) {
                            _log("it(\"" + label + "\", ...) ignored, see issue #" + issue);
                        } else {
                            _it.apply(this, arguments);
                        }
                    };
                });
        },

        // Actively wait for GPF to be loaded
        _waitForLoad = function (callback) {
            // Check if the GPF library is loaded
            if (typeof gpf === "undefined") {
                if (--_MAX_WAIT) {
                    setTimeout(function () {
                        _waitForLoad(callback);
                    }, 100);
                } else {
                    _error("Unable to load GPF");
                }
                return;
            }
            // Legacy test case?
            var legacy = _detectLegacy();
            if (legacy) {
                delete gpf.internals;
                _patchLegacy(legacy)
                    .then(function () {
                        _waitForTestCases(["legacy/" + legacy + ".js"], callback);
                    });
                return;
            }
            // GPF Library being loaded, Promises are existing (either natively or through compatiblity)
            var getTestFiles;
            if (_tests) {
                getTestFiles = Promise.resolve(_tests);
            } else {
                // Test files from sources.json
                getTestFiles = xhr(gpfSourcesPath + "sources.json").get().asJson()
                    .then(function (sources) {
                        return sources
                            .filter(function (source) {
                                return source.test !== false;
                            })
                            .map(function (source) {
                                return source.name;
                            });
                    });
            }
            getTestFiles.then(function (files) {
                _waitForTestCases(files
                    .map(function (name) {
                        return name + ".js";
                    }), callback);
            });
        },

        buildFlavorSetup = function (flavor) {
            return function () {
                _tests = gpfFlavors[flavor].tests;
            };
        },

        _addFlavors = function () {
            var flavor;
            for (flavor in gpfFlavors) {
                if (Object.prototype.hasOwnProperty.call(gpfFlavors, flavor)) {
                    _versions["flavor:" + flavor] = {
                        label: "\"" + flavor + "\" flavor",
                        path: "../build/gpf-" + flavor + ".js",
                        setup: buildFlavorSetup(flavor)
                    };
                }
            }
        },

        _getVersionParameters = function () {
            var locationSearch = location.search,
                version;
            if (typeof gpfFlavors !== "undefined") {
                _addFlavors();
            }
            for (version in _versions) {
                if (Object.prototype.hasOwnProperty.call(_versions, version)
                    && locationSearch.indexOf(version) !== -1) {
                    return _versions[version];
                }
            }
        },

        _detectVersion = function () {
            var versionParameters = _getVersionParameters(),
                version,
                path = "boot.js?map";
            if (versionParameters) {
                version = versionParameters.label;
                path = versionParameters.path || "boot.js";
                versionParameters.setup();
            } else {
                version = "sources";
            }
            _log("Using " + version + " version");
            return path;
        },

        _loadVersion = function (callback) {
            var head = document.getElementsByTagName("head")[0],
                script = document.createElement("script"),
                version = _detectVersion();
            script.src = gpfSourcesPath + version;
            script.language = "javascript";
            head.insertBefore(script, head.firstChild);
            _waitForLoad(callback);
        },

        _setupInclude = function () {
            window.include = function (source) {
                var path = window.gpfTestsPath + source + ".js";
                xhr(path, true).get()
                    .then(function (responseText) {
                        _evalTestCase(source + ".js", responseText);
                    });
            };
        },

        _setupConfig = function () {
            window.config = {};
            config.httpPort = parseInt(location.port, 10);
            config.testPath = "/test/";
            var msie = (/(msie|trident)/i).test(navigator.userAgent);
            if (msie) {
                config.timerResolution = 5; // Found out that this is the only way to safely run tests
            }
            include("host/features");
        };

    /*
     * Load the GPF framework and test cases.
     * When done, execute the callback.
     */
    window.load = function (callback) {
        _setupInclude();
        _setupConfig();
        _loadVersion(callback);
    };

    // Call it after tests to handle cached results & coverage storage
    window.afterRun = function (data) {
        var promise;
        // Store coverage data first
        if (typeof __coverage__ === "undefined") {
            promise = Promise.resolve();
        } else {
            promise = xhr("/fs/tmp/coverage/reports/coverage.browser.json").post(JSON.stringify(__coverage__));
        }
        // Check if result must be cached
        var match = (/cache=([0-9]+)/).exec(location.search);
        if (match) {
            promise.then(function () {
                // Will trigger closing of browser
                xhr("/cache/" + match[1]).post(JSON.stringify(data));
            });
        }
    };

}());
<commit_msg>Offers a way to ignore tests<commit_after>/*eslint strict: [2, "function"]*/ // IIFE form
/*eslint-disable func-style*/ // So that everything is grouped in one var
/*global xhr*/
(function () {
    "use strict";
    /*jshint browser: true*/
    /*eslint-env browser*/
    /*global __coverage__*/ // Coverage data
    /*global gpfFlavors*/ // Flavors

    function _safeConsoleMethod (method) {
        return function (msg) {
            if (console.expects) {
                console.expects(method, msg, true);
            }
            console[method](msg);
        };
    }

    var _log = _safeConsoleMethod("log"),
        _error = _safeConsoleMethod("error"),
        _MAX_WAIT = 50,
        _versions = {
            release: {
                label: "release",
                path: "../build/gpf.js",
                setup: function () {}
            },
            debug: {
                label: "debug",
                path: "../build/gpf-debug.js",
                setup: function () {}
            },
            coverage: {
                label: "instrumented sources",
                setup: function () {
                    window.global = window;
                    gpfSourcesPath += "../tmp/coverage/instrument/src/";
                }
            }
        },
        _tests,

        _evalTestCase = function (testFileURL, testCaseSource) {
            var sourceURL = window.location.toString().split("/test/")[0] + "/test/" + testFileURL;
            /*jshint -W061*/
            eval("//# sourceURL=" + sourceURL + "\n" + testCaseSource); //eslint-disable-line no-eval
            /*jshint +W061*/
        },

        _waitForTestCases = function (testFiles, callback) {
            var testFileURL;
            function _testCaseLoaded (testCaseSource) {
                _evalTestCase(testFileURL, testCaseSource);
                _waitForTestCases(testFiles, callback);
            }
            if (testFiles.length) {
                testFileURL = testFiles.shift();
                xhr(window.gpfTestsPath + testFileURL).get()
                    .then(_testCaseLoaded, _error);
                return;
            }
            // Everything is loaded
            callback();
        },

        _detectLegacy = function () {
            var legacyVersion = (/version=([0-9.]+)/).exec(window.location.search);
            if (legacyVersion) {
                return legacyVersion[1];
            }
        },

        _patchLegacy = function (version) {
            // gpf is loaded
            return xhr("/test/legacy/legacy.json").get().asJson()
                .then(function (legacy) {
                    return legacy.filter(function (item) {
                        return item.before > version;
                    });
                })
                .then(function (legacy) {
                    var
                        _describes = [],
                        _describe = window.describe,
                        _it = window.it;
                    window.describe = function (label) {
                        var issue;
                        legacy.every(function (item) {
                            if (item.ignore.some(function (ignore) {
                                return ignore.describe === label && !ignore.it;

                            })) {
                                issue = item.issue;
                                return false;
                            }
                            return true;
                        });
                        if (issue) {
                            _log("describe(\"" + label + "\", ...) ignored, see issue #" + issue);
                        } else {
                            _describes.unshift(label);
                            _describe.apply(this, arguments);
                            _describes.shift();
                        }
                    };
                    window.it = function (label) {
                        var issue;
                        legacy.every(function (item) {
                            if (item.ignore.some(function (ignore) {
                                return ignore.describe === _describes[0] && ignore.it === label;

                            })) {
                                issue = item.issue;
                                return false;
                            }
                            return true;
                        });
                        if (issue) {
                            _log("it(\"" + label + "\", ...) ignored, see issue #" + issue);
                        } else {
                            _it.apply(this, arguments);
                        }
                    };
                });
        },

        // Actively wait for GPF to be loaded
        _waitForLoad = function (callback, ignoreTests) {
            // Check if the GPF library is loaded
            if (typeof gpf === "undefined") {
                if (--_MAX_WAIT) {
                    setTimeout(function () {
                        _waitForLoad(callback, ignoreTests);
                    }, 100);
                } else {
                    _error("Unable to load GPF");
                }
                return;
            }
            if (ignoreTests) {
                return callback();
            }
            // Legacy test case?
            var legacy = _detectLegacy();
            if (legacy) {
                delete gpf.internals;
                _patchLegacy(legacy)
                    .then(function () {
                        _waitForTestCases(["legacy/" + legacy + ".js"], callback);
                    });
                return;
            }
            // GPF Library being loaded, Promises are existing (either natively or through compatiblity)
            var getTestFiles;
            if (_tests) {
                getTestFiles = Promise.resolve(_tests);
            } else {
                // Test files from sources.json
                getTestFiles = xhr(gpfSourcesPath + "sources.json").get().asJson()
                    .then(function (sources) {
                        return sources
                            .filter(function (source) {
                                return source.test !== false;
                            })
                            .map(function (source) {
                                return source.name;
                            });
                    });
            }
            getTestFiles.then(function (files) {
                _waitForTestCases(files
                    .map(function (name) {
                        return name + ".js";
                    }), callback);
            });
        },

        buildFlavorSetup = function (flavor) {
            return function () {
                _tests = gpfFlavors[flavor].tests;
            };
        },

        _addFlavors = function () {
            var flavor;
            for (flavor in gpfFlavors) {
                if (Object.prototype.hasOwnProperty.call(gpfFlavors, flavor)) {
                    _versions["flavor:" + flavor] = {
                        label: "\"" + flavor + "\" flavor",
                        path: "../build/gpf-" + flavor + ".js",
                        setup: buildFlavorSetup(flavor)
                    };
                }
            }
        },

        _getVersionParameters = function () {
            var locationSearch = location.search,
                version;
            if (typeof gpfFlavors !== "undefined") {
                _addFlavors();
            }
            for (version in _versions) {
                if (Object.prototype.hasOwnProperty.call(_versions, version)
                    && locationSearch.indexOf(version) !== -1) {
                    return _versions[version];
                }
            }
        },

        _detectVersion = function () {
            var versionParameters = _getVersionParameters(),
                version,
                path = "boot.js?map";
            if (versionParameters) {
                version = versionParameters.label;
                path = versionParameters.path || "boot.js";
                versionParameters.setup();
            } else {
                version = "sources";
            }
            _log("Using " + version + " version");
            return path;
        },

        _loadVersion = function (callback, ignoreTests) {
            var head = document.getElementsByTagName("head")[0],
                script = document.createElement("script"),
                version = _detectVersion();
            script.src = gpfSourcesPath + version;
            script.language = "javascript";
            head.insertBefore(script, head.firstChild);
            _waitForLoad(callback, ignoreTests);
        },

        _setupInclude = function () {
            window.include = function (source) {
                var path = window.gpfTestsPath + source + ".js";
                xhr(path, true).get()
                    .then(function (responseText) {
                        _evalTestCase(source + ".js", responseText);
                    });
            };
        },

        _setupConfig = function () {
            window.config = {};
            config.httpPort = parseInt(location.port, 10);
            config.testPath = "/test/";
            var msie = (/(msie|trident)/i).test(navigator.userAgent);
            if (msie) {
                config.timerResolution = 5; // Found out that this is the only way to safely run tests
            }
            include("host/features");
        };

    /*
     * Load the GPF framework and test cases.
     * When done, execute the callback.
     */
    window.load = function (callback) {
        _setupInclude();
        _setupConfig();
        _loadVersion(callback, /*ignoreTests*/ false);
    };

    /*
     * Load the GPF framework.
     * When done, execute the callback.
     */
    window.loadGpfOnly = function (callback) {
        _setupInclude();
        _setupConfig();
        _loadVersion(callback, /*ignoreTests*/ true);
    };

    // Call it after tests to handle cached results & coverage storage
    window.afterRun = function (data) {
        var promise;
        // Store coverage data first
        if (typeof __coverage__ === "undefined") {
            promise = Promise.resolve();
        } else {
            promise = xhr("/fs/tmp/coverage/reports/coverage.browser.json").post(JSON.stringify(__coverage__));
        }
        // Check if result must be cached
        var match = (/cache=([0-9]+)/).exec(location.search);
        if (match) {
            promise.then(function () {
                // Will trigger closing of browser
                xhr("/cache/" + match[1]).post(JSON.stringify(data));
            });
        }
    };

}());
<|endoftext|>


<commit_before>var chai = require('chai');
var expect = chai.expect;
var should = chai.should;
var sinon = require('sinon');

var _ = require('lodash');

var util = require('../../core/util');
var dirs = util.dirs();
var INDICATOR_PATH = dirs.indicators;

// Fake input prices to verify all indicators
// are working correctly by comparing fresh
// calculated results to pre calculated results.

// The precalculated results are compared to the Talib repository at
// https://github.com/wuhkuh/talib
// (shameless plug, sorry guys ;))

var prices = [81, 24, 75, 21, 34, 25, 72, 92, 99, 2, 86, 80, 76, 8, 87, 75, 32, 65, 41, 9, 13, 26, 56, 28, 65, 58, 17, 90, 87, 86, 99, 3, 70, 1, 27, 9, 92, 68, 9];

describe('indicators/SMMA', function() {

  var SMMA = require(INDICATOR_PATH + 'SMMA');

  var verified_smma2results = [0, 52.5, 63.75, 42.375, 38.1875, 31.59375, 51.796875, 71.8984375, 85.44921875, 43.724609375, 64.8623046875, 72.43115234375, 74.215576171875, 41.1077880859375, 64.05389404296875, 69.52694702148438, 50.76347351074219, 57.881736755371094, 49.44086837768555, 29.220434188842773, 21.110217094421387, 23.555108547210693, 39.77755427360535, 33.88877713680267, 49.44438856840134, 53.72219428420067, 35.361097142100334, 62.68054857105017, 74.84027428552508, 80.42013714276254, 89.71006857138127, 46.355034285690635, 58.17751714284532, 29.58875857142266, 28.29437928571133, 18.647189642855665, 55.32359482142783, 61.661797410713916, 35.33089870535696];
  var verified_smma12results = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57.583333333333336, 59.118055555555564, 54.8582175925926, 57.53669945987655, 58.991974504886834, 56.74264329614626, 57.43075635480074, 56.061526658567345, 52.1397327703534, 48.878088372823946, 46.97158100842196, 47.72394925772013, 46.08028681957679, 47.656929584612065, 48.518852119227724, 45.89228110929208, 49.5679243501844, 52.687263987669034, 55.46332532202995, 59.09138154519412, 54.41709974976127, 55.7156747706145, 51.15603520639663, 49.14303227253024, 45.797779583152725, 49.64796461788999, 51.177300899732494, 47.66252582475479];
  var verified_smma26results = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51.15384615384615, 49.84023668639053, 51.384842967683205, 52.75465669969539, 54.0333237497071, 55.76281129779529, 53.73347240172624, 54.35910807858292, 52.30683469094512, 51.33349489513954, 49.70528355301879, 51.33200341636422, 51.973080208042525, 50.32026943081012];

  it('should correctly calculate SMMAs with weight 2', function() {
    var ema = new SMMA(2);
    _.each(prices, function(p, i) {
      ema.update(p);
      expect(ema.result).to.equal(verified_smma2results[i]);
    });
  });

  it('should correctly calculate EMAs with weight 12', function() {
    var ema = new SMMA(12);
    _.each(prices, function(p, i) {
      ema.update(p);
      expect(ema.result).to.equal(verified_smma12results[i]);
    });
  });

  it('should correctly calculate EMAs with weight 26', function() {
    var ema = new SMMA(26);
    _.each(prices, function(p, i) {
      ema.update(p);
      expect(ema.result).to.equal(verified_smma26results[i]);
    });
  });
});
<commit_msg>Fix names<commit_after>var chai = require('chai');
var expect = chai.expect;
var should = chai.should;
var sinon = require('sinon');

var _ = require('lodash');

var util = require('../../core/util');
var dirs = util.dirs();
var INDICATOR_PATH = dirs.indicators;

// Fake input prices to verify all indicators
// are working correctly by comparing fresh
// calculated results to pre calculated results.

// The precalculated results are compared to the Talib repository at
// https://github.com/wuhkuh/talib
// (shameless plug, sorry guys ;))

var prices = [81, 24, 75, 21, 34, 25, 72, 92, 99, 2, 86, 80, 76, 8, 87, 75, 32, 65, 41, 9, 13, 26, 56, 28, 65, 58, 17, 90, 87, 86, 99, 3, 70, 1, 27, 9, 92, 68, 9];

describe('indicators/SMMA', function() {

  var SMMA = require(INDICATOR_PATH + 'SMMA');

  var verified_smma2results = [0, 52.5, 63.75, 42.375, 38.1875, 31.59375, 51.796875, 71.8984375, 85.44921875, 43.724609375, 64.8623046875, 72.43115234375, 74.215576171875, 41.1077880859375, 64.05389404296875, 69.52694702148438, 50.76347351074219, 57.881736755371094, 49.44086837768555, 29.220434188842773, 21.110217094421387, 23.555108547210693, 39.77755427360535, 33.88877713680267, 49.44438856840134, 53.72219428420067, 35.361097142100334, 62.68054857105017, 74.84027428552508, 80.42013714276254, 89.71006857138127, 46.355034285690635, 58.17751714284532, 29.58875857142266, 28.29437928571133, 18.647189642855665, 55.32359482142783, 61.661797410713916, 35.33089870535696];
  var verified_smma12results = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57.583333333333336, 59.118055555555564, 54.8582175925926, 57.53669945987655, 58.991974504886834, 56.74264329614626, 57.43075635480074, 56.061526658567345, 52.1397327703534, 48.878088372823946, 46.97158100842196, 47.72394925772013, 46.08028681957679, 47.656929584612065, 48.518852119227724, 45.89228110929208, 49.5679243501844, 52.687263987669034, 55.46332532202995, 59.09138154519412, 54.41709974976127, 55.7156747706145, 51.15603520639663, 49.14303227253024, 45.797779583152725, 49.64796461788999, 51.177300899732494, 47.66252582475479];
  var verified_smma26results = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51.15384615384615, 49.84023668639053, 51.384842967683205, 52.75465669969539, 54.0333237497071, 55.76281129779529, 53.73347240172624, 54.35910807858292, 52.30683469094512, 51.33349489513954, 49.70528355301879, 51.33200341636422, 51.973080208042525, 50.32026943081012];

  it('should correctly calculate SMMAs with weight 2', function() {
    var smma = new SMMA(2);
    _.each(prices, function(p, i) {
      smma.update(p);
      expect(smma.result).to.equal(verified_smma2results[i]);
    });
  });

  it('should correctly calculate SMMAs with weight 12', function() {
    var smma = new SMMA(12);
    _.each(prices, function(p, i) {
      smma.update(p);
      expect(smma.result).to.equal(verified_smma12results[i]);
    });
  });

  it('should correctly calculate SMMAs with weight 26', function() {
    var smma = new SMMA(26);
    _.each(prices, function(p, i) {
      smma.update(p);
      expect(smma.result).to.equal(verified_smma26results[i]);
    });
  });
});
<|endoftext|>


<commit_before>var join = require('path').join;
var nixt = require('nixt');
var bin = join(__dirname, '..', '..', 'bin');

t('--version', function(done) {
  cli()
  .stdout(require('../../package.json').version)
  .run('--version')
  .end(done);
});

t('--help', function(done) {
  cli()
  .stdout(/Usage: hydro \[debug\] \[options\]/)
  .run('--help')
  .end(done);
});

function cli() {
  return nixt({ newlines: false }).cwd(bin).base('./hydro ');
}
<commit_msg>Assert on exit codes<commit_after>var join = require('path').join;
var nixt = require('nixt');
var bin = join(__dirname, '..', '..', 'bin');

t('--version', function(done) {
  cli()
  .stdout(require('../../package.json').version)
  .run('--version')
  .code(0)
  .end(done);
});

t('--help', function(done) {
  cli()
  .stdout(/Usage: hydro \[debug\] \[options\]/)
  .run('--help')
  .code(0)
  .end(done);
});

function cli() {
  return nixt({ newlines: false }).cwd(bin).base('./hydro ');
}
<|endoftext|>


<commit_before>/* global $: false */
'use strict';

if (window.jQuery) {

  describe('jQuery patch', function() {

    var doc = null;
    var divSpy = null;
    var spy1 = null;
    var spy2 = null;

    beforeEach(function() {
      divSpy = jasmine.createSpy('div.$destroy');
      spy1 = jasmine.createSpy('span1.$destroy');
      spy2 = jasmine.createSpy('span2.$destroy');
      doc = $('
abcxyz
');
      doc.find('span.first').on('$destroy', spy1);
      doc.find('span.second').on('$destroy', spy2);
    });

    afterEach(function() {
      expect(divSpy).not.toHaveBeenCalled();

      expect(spy1).toHaveBeenCalled();
      expect(spy1).toHaveBeenCalledTimes(1);
      expect(spy2).toHaveBeenCalled();
      expect(spy2).toHaveBeenCalledTimes(1);
    });

    describe('$detach event', function() {

      it('should fire on remove()', function() {
        doc.find('span').remove();
      });

      it('should fire on replaceWith()', function() {
        doc.find('span').replaceWith('bla');
      });

      it('should fire on replaceAll()', function() {
        $('bla').replaceAll(doc.find('span'));
      });

      it('should fire on empty()', function() {
        doc.empty();
      });

      it('should fire on html(param)', function() {
        doc.html('abc');
      });

      it('should fire on html(\'\')', function() {
        doc.html('');
      });
    });
  });

  describe('jQuery patch eagerness', function() {

    var doc = null;
    var divSpy = null;
    var spy1 = null;
    var spy2 = null;

    beforeEach(function() {
      divSpy = jasmine.createSpy('div.$destroy');
      spy1 = jasmine.createSpy('span1.$destroy');
      spy2 = jasmine.createSpy('span2.$destroy');
      doc = $('
abcxyz
');
      doc.find('span.first').on('$destroy', spy1);
      doc.find('span.second').on('$destroy', spy2);
    });

    afterEach(function() {
      expect(divSpy).not.toHaveBeenCalled();
      expect(spy1).not.toHaveBeenCalled();
    });

    describe('$detach event is not invoked in too many cases', function() {

      it('should fire only on matched elements on remove(selector)', function() {
        doc.find('span').remove('.second');
        expect(spy2).toHaveBeenCalled();
        expect(spy2).toHaveBeenCalledTimes(1);
      });

      it('should not fire on html()', function() {
        doc.html();
        expect(spy2).not.toHaveBeenCalled();
      });
    });
  });
}
<commit_msg>chore(jqLite): fix $destroy describe block titles<commit_after>/* global $: false */
'use strict';

if (window.jQuery) {

  describe('jQuery patch', function() {

    var doc = null;
    var divSpy = null;
    var spy1 = null;
    var spy2 = null;

    beforeEach(function() {
      divSpy = jasmine.createSpy('div.$destroy');
      spy1 = jasmine.createSpy('span1.$destroy');
      spy2 = jasmine.createSpy('span2.$destroy');
      doc = $('
abcxyz
');
      doc.find('span.first').on('$destroy', spy1);
      doc.find('span.second').on('$destroy', spy2);
    });

    afterEach(function() {
      expect(divSpy).not.toHaveBeenCalled();

      expect(spy1).toHaveBeenCalled();
      expect(spy1).toHaveBeenCalledTimes(1);
      expect(spy2).toHaveBeenCalled();
      expect(spy2).toHaveBeenCalledTimes(1);
    });

    describe('$destroy event', function() {

      it('should fire on remove()', function() {
        doc.find('span').remove();
      });

      it('should fire on replaceWith()', function() {
        doc.find('span').replaceWith('bla');
      });

      it('should fire on replaceAll()', function() {
        $('bla').replaceAll(doc.find('span'));
      });

      it('should fire on empty()', function() {
        doc.empty();
      });

      it('should fire on html(param)', function() {
        doc.html('abc');
      });

      it('should fire on html(\'\')', function() {
        doc.html('');
      });
    });
  });

  describe('jQuery patch eagerness', function() {

    var doc = null;
    var divSpy = null;
    var spy1 = null;
    var spy2 = null;

    beforeEach(function() {
      divSpy = jasmine.createSpy('div.$destroy');
      spy1 = jasmine.createSpy('span1.$destroy');
      spy2 = jasmine.createSpy('span2.$destroy');
      doc = $('
abcxyz
');
      doc.find('span.first').on('$destroy', spy1);
      doc.find('span.second').on('$destroy', spy2);
    });

    afterEach(function() {
      expect(divSpy).not.toHaveBeenCalled();
      expect(spy1).not.toHaveBeenCalled();
    });

    describe('$destroy event is not invoked in too many cases', function() {

      it('should fire only on matched elements on remove(selector)', function() {
        doc.find('span').remove('.second');
        expect(spy2).toHaveBeenCalled();
        expect(spy2).toHaveBeenCalledTimes(1);
      });

      it('should not fire on html()', function() {
        doc.html();
        expect(spy2).not.toHaveBeenCalled();
      });
    });
  });
}
<|endoftext|>


<commit_before>var expect = require('chai').expect,
    rewire = require('rewire'),
    path = require('path'),
    Host = rewire('../../../lib/docker/host');

const UNIX_SOCKET = '/var/run/docker.sock',
      CERT_PATH   = 'mypath',
      TCP_HOST    = 'tcp://127.0.0.1:2375',
      UNIX_HOST   = `unix://${UNIX_SOCKET}`;

Host.__set__('fs', { readFileSync: function(path) { return path; } });

describe('Docker', () => {
  describe('Host', () => {
    let host = null;

    context('with tcp address', () => {
      beforeEach(() => {
        host = new Host(TCP_HOST);
      });

      it('has an http url', () => {
        expect(host.url.startsWith('http://')).to.be.true;
      });

      it("isn't tsl verified", () => {
        expect(host.tlsVerify).to.be.false;
      });

      it("hasn't any ssl certificates", () => {
        expect(host.certs).to.be.undefined;
      });
    });

    context('with unix socket address', () => {
      beforeEach(() => {
        host = new Host(UNIX_HOST);
      });

      it('has an url following request format', () => {
        let expected = `http://unix:${UNIX_SOCKET}:`;

        expect(host.url).to.equal(expected);
      });
    });

    context('when using ssl', () => {
      beforeEach(() => {
        host = new Host(TCP_HOST, true, CERT_PATH);
      });

      it('is tsl verified', () => {
        expect(host.tlsVerify).to.be.true;
      });

      it('has an https url', () => {
        expect(host.url.startsWith('https://')).to.be.true;
      });

      for (let cert of ['ca', 'cert', 'key']) {
        it(`has ${cert} ssl certificate`, () => {
          let expected = path.resolve(CERT_PATH, `${cert}.pem`);

          expect(host.certs[cert]).to.equal(expected);
        });
      }
    });

    describe('.default', () => {
      beforeEach(() => {
        host = Host.default();
      });

      it('returns a new host using DOCKER_HOST env var', () => {
        let expected = host._getUrl(process.env.DOCKER_HOST || UNIX_HOST);

        expect(host.url).to.equal(expected);
      });

      it('returns a new host using DOCKER_TLS_VERIFY env var', () => {
        expect(host.tlsVerify).to.equal(!!process.env.DOCKER_TLS_VERIFY);
      });

      it('returns a new host using DOCKER_CERT_PATH env var', () => {
        let expected = host._getCerts(process.env.DOCKER_CERT_PATH);

        expect(host.certs).to.deep.equal(expected);
      });
    });
  });
});
<commit_msg>remove useless describe in host test<commit_after>var expect = require('chai').expect,
    rewire = require('rewire'),
    path = require('path'),
    Host = rewire('../../../lib/docker/host');

const UNIX_SOCKET = '/var/run/docker.sock',
      CERT_PATH   = 'mypath',
      TCP_HOST    = 'tcp://127.0.0.1:2375',
      UNIX_HOST   = `unix://${UNIX_SOCKET}`;

Host.__set__('fs', { readFileSync: function(path) { return path; } });

describe('Docker Host', () => {
  let host = null;

  context('with tcp address', () => {
    beforeEach(() => {
      host = new Host(TCP_HOST);
    });

    it('has an http url', () => {
      expect(host.url.startsWith('http://')).to.be.true;
    });

    it("isn't tsl verified", () => {
      expect(host.tlsVerify).to.be.false;
    });

    it("hasn't any ssl certificates", () => {
      expect(host.certs).to.be.undefined;
    });
  });

  context('with unix socket address', () => {
    beforeEach(() => {
      host = new Host(UNIX_HOST);
    });

    it('has an url following request format', () => {
      let expected = `http://unix:${UNIX_SOCKET}:`;

      expect(host.url).to.equal(expected);
    });
  });

  context('when using ssl', () => {
    beforeEach(() => {
      host = new Host(TCP_HOST, true, CERT_PATH);
    });

    it('is tsl verified', () => {
      expect(host.tlsVerify).to.be.true;
    });

    it('has an https url', () => {
      expect(host.url.startsWith('https://')).to.be.true;
    });

    for (let cert of ['ca', 'cert', 'key']) {
      it(`has ${cert} ssl certificate`, () => {
        let expected = path.resolve(CERT_PATH, `${cert}.pem`);

        expect(host.certs[cert]).to.equal(expected);
      });
    }
  });

  describe('.default', () => {
    beforeEach(() => {
      host = Host.default();
    });

    it('returns a new host using DOCKER_HOST env var', () => {
      let expected = host._getUrl(process.env.DOCKER_HOST || UNIX_HOST);

      expect(host.url).to.equal(expected);
    });

    it('returns a new host using DOCKER_TLS_VERIFY env var', () => {
      expect(host.tlsVerify).to.equal(!!process.env.DOCKER_TLS_VERIFY);
    });

    it('returns a new host using DOCKER_CERT_PATH env var', () => {
      let expected = host._getCerts(process.env.DOCKER_CERT_PATH);

      expect(host.certs).to.deep.equal(expected);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-disable max-lines-per-function */

const {unlink, writeFile} = require('fs');
const {resolve} = require('path');
const {expect} = require('chai');

const mapFolder = require('../index');
const getExpectedResult = require('./expected-result');
const expectedResult = getExpectedResult();

const DUMMY_FOLDER = 'dummy-folder';

describe('mapFolder', () => {
	const gitkeepPath = resolve('./test/dummy-folder/empty/.gitkeep');

	before((done) => {
		unlink(gitkeepPath, (err) => {
			if (err && !err.message.includes('ENOENT: no such file or directory')) throw err;
			done();
		});
	});

	after((done) => {
		writeFile(gitkeepPath, '', (err) => {
			if (err) throw err;
			done();
		});
	});

	it('is a function', () => {
		expect(mapFolder).to.be.a('function');
	});

	it('exports entery type constants', () => {
		expect(mapFolder.FOLDER).to.equal(0);
		expect(mapFolder.FILE).to.equal(1);
	});

	it('throws when given path does not exist', () => (
		mapFolder('./test/not/exist')
			.then(() => expect(true).to.be.false)
			.catch(err => expect(err.message).to.include('ENOENT: no such file or directory'))
	));

	it('can map a file', () => {
		const filePath = `./test/${DUMMY_FOLDER}/main.html`;

		return mapFolder(filePath)
			.then(res => expect(res).to.deep.equal({
				path: resolve(filePath),
				type: mapFolder.FILE,
				name: 'main',
				ext: 'html',
			}))
			.catch(() => expect(false).to.be.true);
	});

	it('maps a given folder to a JSON', async () => {
		let res;

		try {
			res = await mapFolder(`./test/${DUMMY_FOLDER}`);
		}
		catch (ex) {
			return expect(false).to.be.true;
		}

		return expect(res).to.deep.equal(expectedResult);
	});

	it('has a synchronous version', () => {
		let res;

		try {
			res = mapFolder.sync(`./test/${DUMMY_FOLDER}`);
		}
		catch (ex) {
			throw expect(false).to.be.true;
		}

		expect(res).to.deep.equal(expectedResult);
	});

	describe('ignore', () => {
		it('ignores a given item', async () => {
			let res;

			try {
				res = await mapFolder(`./test/${DUMMY_FOLDER}`, 'aaa');
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.aaa;

			return expect(res).to.deep.equal(expected);
		});

		it('ignores a given item (sync)', () => {
			let res;

			try {
				res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, 'aaa');
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.aaa;

			expect(res).to.deep.equal(expected);
		});

		it('ignores given list of items', async () => {
			let res;

			try {
				res = await mapFolder(`./test/${DUMMY_FOLDER}`, ['bbb.min.js', 'empty']);
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.aaa.entries['bbb.min.js'];
			delete expected.entries.empty;

			return expect(res).to.deep.equal(expected);
		});

		it('ignores given list of items (sync)', () => {
			let res;

			try {
				res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, ['bbb.min.js', 'empty']);
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.aaa.entries['bbb.min.js'];
			delete expected.entries.empty;

			expect(res).to.deep.equal(expected);
		});

		it('ignores by a function', async () => {
			let res;

			try {
				const ignore = name => name.includes('z');

				res = await mapFolder(`./test/${DUMMY_FOLDER}`, ignore);
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.foo.entries.bar.entries['baz.js'];

			return expect(res).to.deep.equal(expected);
		});

		it('ignores by a function (sync)', () => {
			let res;

			try {
				const ignore = name => name.includes('z');

				res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, ignore);
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			const expected = getExpectedResult();

			delete expected.entries.foo.entries.bar.entries['baz.js'];

			expect(res).to.deep.equal(expected);
		});
	});
});
<commit_msg>split tests<commit_after>/* eslint-disable max-lines-per-function */

const {unlink, writeFile} = require('fs');
const {resolve} = require('path');
const {expect} = require('chai');

const mapFolder = require('../index');
const getExpectedResult = require('./expected-result');
const expectedResult = getExpectedResult();

const DUMMY_FOLDER = 'dummy-folder';

describe('mapFolder', () => {
	const gitkeepPath = resolve('./test/dummy-folder/empty/.gitkeep');

	before((done) => {
		unlink(gitkeepPath, (err) => {
			if (err && !err.message.includes('ENOENT: no such file or directory')) throw err;
			done();
		});
	});

	after((done) => {
		writeFile(gitkeepPath, '', (err) => {
			if (err) throw err;
			done();
		});
	});

	it('exports entery type constants', () => {
		expect(mapFolder.FOLDER).to.equal(0);
		expect(mapFolder.FILE).to.equal(1);
	});

	describe('sync', () => {
		it('is a function', () => {
			expect(mapFolder.sync).to.be.a('function');
		});

		it('maps a given folder to a JSON', () => {
			let res;

			try {
				res = mapFolder.sync(`./test/${DUMMY_FOLDER}`);
			}
			catch (ex) {
				throw expect(false).to.be.true;
			}

			expect(res).to.deep.equal(expectedResult);
		});

		describe('ignore', () => {
			it('ignores a given item', async () => {
				let res;

				try {
					res = await mapFolder(`./test/${DUMMY_FOLDER}`, 'aaa');
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.aaa;

				return expect(res).to.deep.equal(expected);
			});

			it('ignores given list of items', async () => {
				let res;

				try {
					res = await mapFolder(`./test/${DUMMY_FOLDER}`, ['bbb.min.js', 'empty']);
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.aaa.entries['bbb.min.js'];
				delete expected.entries.empty;

				return expect(res).to.deep.equal(expected);
			});

			it('ignores by a function', async () => {
				let res;

				try {
					const ignore = name => name.includes('z');

					res = await mapFolder(`./test/${DUMMY_FOLDER}`, ignore);
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.foo.entries.bar.entries['baz.js'];

				return expect(res).to.deep.equal(expected);
			});
		});

		it('can map a file', () => {
			const filePath = `./test/${DUMMY_FOLDER}/main.html`;

			try {
				const res = mapFolder.sync(filePath);

				expect(res).to.deep.equal({
					path: resolve(filePath),
					type: mapFolder.FILE,
					name: 'main',
					ext: 'html',
				});
			}
			catch (err) {
				return expect(false).to.be.true;
			}
		});

		it('throws when given path does not exist', () => {
			try {
				mapFolder.sync('./test/not/exist');
			}
			catch (err) {
				expect(err.message).to.include('ENOENT: no such file or directory');
			}
		});
	});

	describe('async', () => {
		it('is a function', () => {
			expect(mapFolder).to.be.a('function');
		});

		it('maps a given folder to a JSON', async () => {
			let res;

			try {
				res = await mapFolder(`./test/${DUMMY_FOLDER}`);
			}
			catch (ex) {
				return expect(false).to.be.true;
			}

			return expect(res).to.deep.equal(expectedResult);
		});

		describe('ignore', () => {
			it('ignores a given item', () => {
				let res;

				try {
					res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, 'aaa');
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.aaa;

				expect(res).to.deep.equal(expected);
			});

			it('ignores given list of items', () => {
				let res;

				try {
					res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, ['bbb.min.js', 'empty']);
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.aaa.entries['bbb.min.js'];
				delete expected.entries.empty;

				expect(res).to.deep.equal(expected);
			});

			it('ignores by a function', () => {
				let res;

				try {
					const ignore = name => name.includes('z');

					res = mapFolder.sync(`./test/${DUMMY_FOLDER}`, ignore);
				}
				catch (ex) {
					return expect(false).to.be.true;
				}

				const expected = getExpectedResult();

				delete expected.entries.foo.entries.bar.entries['baz.js'];

				expect(res).to.deep.equal(expected);
			});
		});

		it('can map a file', () => {
			const filePath = `./test/${DUMMY_FOLDER}/main.html`;

			return mapFolder(filePath)
				.then(res => expect(res).to.deep.equal({
					path: resolve(filePath),
					type: mapFolder.FILE,
					name: 'main',
					ext: 'html',
				}))
				.catch(() => expect(false).to.be.true);
		});

		it('throws when given path does not exist', () => (
			mapFolder('./test/not/exist')
				.then(() => expect(true).to.be.false)
				.catch(err => expect(err.message).to.include('ENOENT: no such file or directory'))
		));
	});
});
<|endoftext|>


<commit_before>"use strict";

const assert = require('assert');
const xpath = require('fontoxpath');
const utils = require('./utils');

const meiText = utils.getTestMeiDom('text.mei');

describe("Text elements", function() {
    it("figured bass elements in measure 4", function() {
        const m4harms = xpath.evaluateXPath("//*:measure[@n='4']/*:harm", meiText);
        assert.strictEqual(m4harms.length, 3, "There should be 3 <harm> elements in measure 4");
    });
    it("check for <tempo> in measure 6", function() {
        const tempo = xpath.evaluateXPath("//*:measure[@n='6']/*:tempo", meiText);
        assert.notStrictEqual(tempo.length, null ,"<tempo> in measure 6 is missing");
    });
    // test for dynam
    it("two <dynam> elements", function() {
        const dynams = xpath.evaluateXPath("//*:dynam", meiText);
        assert.strictEqual(dynams.length,2,"there should be 2 <dynam> elements");
    });
    // test for title, subtitle & composer
    // test for plain text
    // test formatting: bold, subscript, superscript,italic, font change, font size

});<commit_msg>Added simple more tests and fixed tempo test<commit_after>"use strict";

const assert = require('assert');
const xpath = require('fontoxpath');
const utils = require('./utils');

const meiText = utils.getTestMeiDom('text.mei');

describe("Text elements", function() {
    it("figured bass elements in measure 4", function() {
        const m4harms = xpath.evaluateXPath("//*:measure[@n='4']/*:harm", meiText);
        assert.strictEqual(m4harms.length, 3, "There should be 3 <harm> elements in measure 4");
    });
    it("check for <tempo> in measure 6", function() {
        const tempo = xpath.evaluateXPath("//*:measure[@n='6']/*:tempo", meiText);
        assert.notStrictEqual(tempo.length, 0 ,"<tempo> in measure 6 is missing");
    });
    // test for dynam
    it("two <dynam> elements", function() {
        const dynams = xpath.evaluateXPath("//*:dynam", meiText);
        assert.strictEqual(dynams.length, 2,"there should be 2 <dynam> elements");
    });
    // test for title, subtitle & composer
    it("check for composer label in measure 1", function() {
        const composerEl = xpath.evaluateXPath("//*:measure[@n='1']//*:persName[@role='Composer']", meiText);
        assert.notStrictEqual(composerEl.length, 0,"The composer label is missing");
    });
    it("check for subordinate title in measure 1", function() {
        const subTitle = xpath.evaluateXPath("//*:measure[@n='1']//*:title[@type='subordinate']", meiText);
        assert.notStrictEqual(subTitle.length, 0, "The subtitle is missing");
    });
    // test for plain text (not implemented yet)
    // test formatting: subscript, superscript
    it("check for superscript", function() {
        const superscript = xpath.evaluateXPath("//*:measure[@n='1']//*:title[@type='subordinate']/*:rend[@rend='sup']", meiText);
        assert.notStrictEqual(superscript.length, 0, "Superscript in subtitle is missing");
    });
    it("check for subscript", function() {
        const subscript = xpath.evaluateXPath("//*:measure[@n='1']//*:title[@type='subordinate']/*:rend[@rend='sub']", meiText);
        assert.notStrictEqual(subscript.length, 0, "Subscript in subtitle is missing");
    });
    // test formatting: bold, italic, font change, font size
});<|endoftext|>