<commit_before>const assert = require('assert'),
      esprima = require('esprima'),
      jsonjs = require('../lib')

function parse_expr(text, do_log) {
  var expr = esprima.parse(text)
  if (do_log) {
    console.log("expr", JSON.stringify(expr, null, '  '))
  }
  return expr
}

describe('nonexistence', function() {
  it('an empty program is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr('')), undefined)
  }),
  it('an empty statement is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr(';')), undefined)
  }),
  it('an empty block is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr('{}')), undefined)
  })
})

describe('literals', function() {
  it('a numeric literal should return itself', function() {
    assert.equal(jsonjs.eval(parse_expr('123')), 123)
  })
})

describe('binary expressions', function() {
  it('multiplication should work on numbers', function () {
    assert.equal(jsonjs.eval(parse_expr('6 * 9')), 54)
  }),
  it('addition should work on numbers', function () {
    assert.equal(jsonjs.eval(parse_expr('11 + 22')), 33)
  })
  // FIXME etc
})

describe('sequence of expressions', function() {
  it('sequence of expressions should return the last value', function () {
    assert.equal(jsonjs.eval(parse_expr('1,1,2,3,5,8')), 8)
  })
})

describe('bindings', function() {
  it('const assignment should create a binding', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = 47; x')), 47)
  }),
  it('const assignment results in undefined', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = 47')), undefined)
  }),
  it('unbound name should throw a ReferenceError', function () {
    assert.throws(
      function () { jsonjs.eval(parse_expr('x')) }, ReferenceError)
  }),
  it('const assignments are not visible outside a block scope', function () {
    assert.throws(
      function () { jsonjs.eval(parse_expr('{ const x = 47 }; x')) }, ReferenceError)
  })
})

describe('functions', function() {
  it('function definition should create a binding', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() {}; x', true)), 47)
  }),
  it('calling an empty function should return undefined', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() {}; x()', true)), undefined)
  }),
  it('calling a no-arg function', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() { return 47 }; x()', true)), 47)
  }),
  it('calling a single arg function', function () {
    assert.equal(jsonjs.eval(parse_expr('const add1 = function(x) { return x + 1 }; add1(41)', true)), 42)
  })
  // FIXME recursion; arity > 1
  // FIXME obvious extensions to apply "alpha renaming" and get lexical scope
})

describe('conditional expressions and if statements', function() {
  it('true conditional only specifies consequent', function()  {
    assert.equal(jsonjs.eval(parse_expr('if (true) { 47 }')), 47)
  }),
  it('false conditional only specifies consequent returns undefined', function()  {
    assert.equal(jsonjs.eval(parse_expr('if (false) { 47 }')), undefined)
  }),
  it('false conditional short circuit on consequent', function()  {
    // ReferenceError would be raised if no short circuiting
    assert.equal(jsonjs.eval(parse_expr('false ? x : 47')), 47)
  }),
  it('true conditional short circuit on alternate', function()  {
    // ReferenceError would be raised if no short circuiting
    assert.equal(jsonjs.eval(parse_expr('true ? 47 : x')), 47)
  })
})
<commit_msg>Switch to chai.assert<commit_after>const assert = require('chai').assert,
      esprima = require('esprima'),
      jsonjs = require('../lib')

function parse_expr(text, do_log) {
  var expr = esprima.parse(text)
  if (do_log) {
    console.log("expr", JSON.stringify(expr, null, '  '))
  }
  return expr
}

describe('nonexistence', function() {
  it('an empty program is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr('')), undefined)
  }),
  it('an empty statement is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr(';')), undefined)
  }),
  it('an empty block is undefined', function() {
    assert.equal(jsonjs.eval(parse_expr('{}')), undefined)
  })
})

describe('literals', function() {
  it('a numeric literal should return itself', function() {
    assert.equal(jsonjs.eval(parse_expr('123')), 123)
  })
})

describe('binary expressions', function() {
  it('multiplication should work on numbers', function () {
    assert.equal(jsonjs.eval(parse_expr('6 * 9')), 54)
  }),
  it('addition should work on numbers', function () {
    assert.equal(jsonjs.eval(parse_expr('11 + 22')), 33)
  })
  // FIXME etc
})

describe('sequence of expressions', function() {
  it('sequence of expressions should return the last value', function () {
    assert.equal(jsonjs.eval(parse_expr('1,1,2,3,5,8')), 8)
  })
})

describe('bindings', function() {
  it('const assignment should create a binding', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = 47; x')), 47)
  }),
  it('const assignment results in undefined', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = 47')), undefined)
  }),
  it('unbound name should throw a ReferenceError', function () {
    assert.throws(
      function () { jsonjs.eval(parse_expr('x')) }, ReferenceError)
  }),
  it('const assignments are not visible outside a block scope', function () {
    assert.throws(
      function () { jsonjs.eval(parse_expr('{ const x = 47 }; x')) }, ReferenceError)
  })
})

describe('functions', function() {
  it('function definition should create a binding', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() {}; x', true)), 47)
  }),
  it('calling an empty function should return undefined', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() {}; x()', true)), undefined)
  }),
  it('calling a no-arg function', function () {
    assert.equal(jsonjs.eval(parse_expr('const x = function() { return 47 }; x()', true)), 47)
  }),
  it('calling a single arg function', function () {
    assert.equal(jsonjs.eval(parse_expr('const add1 = function(x) { return x + 1 }; add1(41)', true)), 42)
  })
  // FIXME recursion; arity > 1
  // FIXME obvious extensions to apply "alpha renaming" and get lexical scope
})

describe('conditional expressions and if statements', function() {
  it('true conditional only specifies consequent', function()  {
    assert.equal(jsonjs.eval(parse_expr('if (true) { 47 }')), 47)
  }),
  it('false conditional only specifies consequent returns undefined', function()  {
    assert.equal(jsonjs.eval(parse_expr('if (false) { 47 }')), undefined)
  }),
  it('false conditional short circuit on consequent', function()  {
    // ReferenceError would be raised if no short circuiting
    assert.equal(jsonjs.eval(parse_expr('false ? x : 47')), 47)
  }),
  it('true conditional short circuit on alternate', function()  {
    // ReferenceError would be raised if no short circuiting
    assert.equal(jsonjs.eval(parse_expr('true ? 47 : x')), 47)
  })
})
<|endoftext|>


<commit_before>'use strict';

require('mocha');
var Base = require('base');
var assert = require('assert');
var task = require('base-task');
var option = require('base-option');
var Assemble = require('assemble-core');
var generators = require('base-generators');
Assemble.use(generators());

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

describe('base-compose', function() {
  beforeEach(function() {
    app = new Assemble();
    app.use(compose());
  });

  it('should add `.compose` method to `app`', function() {
    assert.equal(typeof app.compose, 'function');
  });

  it('should not have any generators if none are passed', function() {
    assert.deepEqual(app.compose().generators, []);
  });

  describe('data', function() {
    it('should copy data from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.data('foo', 'aaa');
      });

      app.compose(['a'])
        .data();

      assert.deepEqual(app.cache.data, a.cache.data);
    });

    it('should copy data from `a` to `app` specified by property path', function() {
      var a = app.register('a', function(a) {
        a.data({
          a: {
            b: {
              c: {d: 'e'},
              c1: {d: 'e'}
            },
            b1: {
              c1: {d: 'e'}
            }
          },
          a1: {b: {c: {d: 'e'}}}
        });
      });

      app.compose(['a'])
        .data('a.b.c');

      assert.deepEqual(app.cache.data, {a: {b: {c: {d: 'e'}}}});
    });

    it('should throw an error when the `data` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).data();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.data expects a ".data()" method on "app"');
        cb();
      }
    });
  });

  describe('engines', function() {
    it('should copy engines from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.engine('hbs', require('engine-handlebars'));
        a.engine('tmpl', require('engine-base'));
      });

      app.compose(['a'])
        .engines();

      assert.deepEqual(app._.engines, a._.engines);
    });
  });

  describe('helpers', function() {
    it('should copy helpers from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.helper('foo', function(str) {
          return str + ' FOO';
        });

        a.asyncHelper('bar', function(str, next) {
          next(null, str + ' BAR');
        });
      });

      app.compose(['a'])
        .helpers();

      assert.deepEqual(app._.helpers, a._.helpers);
    });
  });

  describe('options', function() {
    it('should copy options from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.option('foo', 'aaa');
      });

      app.compose(['a'])
        .options();

      assert.deepEqual(app.options, a.options);
    });

    it('should copy options from `a` to `app` specified by property path', function() {
      var a = app.register('a', function(a) {
        a.option({
          a: {
            b: {
              c: {d: 'e'},
              c1: {d: 'e'}
            },
            b1: {
              c1: {d: 'e'}
            }
          },
          a1: {b: {c: {d: 'e'}}}
        });
      });

      app.compose(['a'])
        .options('a.b.c');

      assert.deepEqual(app.options, {a: {b: {c: {d: 'e'}}}});
    });
  });

  describe('tasks', function() {
    it('should copy a task from `a` to `app`', function(cb) {
      var count = 0;
      var output = [];
      app.name = 'app';
      var a = app.register('a', function(a) {
        a.task('default', function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });
      });

      app.compose(['a'])
        .tasks('default');

      app.build('default', function(err) {
        if (err) cb(err);
        assert.deepEqual(output, ['app: default']);
        assert.equal(count, 1);
        cb();
      });
    });

    it('should copy a task and dependencies from `a` to `app`', function(cb) {
      var count = 0;
      var output = [];
      app.name = 'app';
      var a = app.register('a', function(a) {
        a.task('foo', function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });

        a.task('default', ['foo'], function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });
      });

      app.compose(['a'])
        .tasks('default');

      app.build('default', function(err) {
        if (err) cb(err);
        assert.deepEqual(output, ['app: foo', 'app: default']);
        assert.equal(count, 2);
        cb();
      });
    });

    it('should throw an error when a task does not exist on `a`.', function(cb) {
      var a = app.register('a', function(a) {
        a.task('foo', function(cb) {
          cb();
        });

        a.task('default', function(cb) {
          cb();
        });
      });

      try {
        app.compose(['a'])
          .tasks(['foo', 'bar']);
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '"bar" not found in tasks');
        cb();
      }
    });
  });

  describe('views', function() {
    it('should copy views from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.create('templates');
        a.template('foo', {content: 'foo'});
      });

      app.compose(['a'])
        .views();

      assert.equal(typeof app.template, 'function');
      assert.equal(typeof app.templates, 'function');
      assert.equal(typeof app.views.templates, 'object');
      assert.equal(typeof app.views.templates.foo, 'object');
    });

    it('should only copy collections from `a` to `app` that are not already on `app`', function() {
      app.create('templates');
      app.template('bar', {content: 'bar'});
      var a = app.register('a', function(a) {
        a.create('templates');
        a.template('foo', {content: 'foo'});
      });

      app.compose(['a'])
        .views();

      assert.equal(typeof app.template, 'function');
      assert.equal(typeof app.templates, 'function');
      assert.equal(typeof app.views.templates, 'object');
      assert.equal(typeof app.views.templates.foo, 'object');
      assert.equal(typeof app.views.templates.bar, 'object');
    });
  });

  describe('iterator', function() {
    it('should allow using the iterator with the currently loaded generators', function() {
      app.register('a', function(a) {});
      app.register('b', function(b) {});

      var output = [];

      app.compose(['a', 'b'])
        .iterator(function(gen) {
          output.push(gen.name);
        });

      assert.deepEqual(output, ['a', 'b']);
    });

    it('should allow using the iterator with the custom specified generators', function() {
      app.register('a', function(a) {});
      app.register('b', function(b) {});
      app.register('c', function(c) {});
      app.register('d', function(d) {});

      var output = [];

      app.compose(['a', 'b'])
        .iterator(['c', 'd'], function(gen) {
          output.push(gen.name);
        });

      assert.deepEqual(output, ['c', 'd']);
    });

    it('should throw an error when a generator is not found', function(cb) {
      var count = 0;
      try {
        app.compose('a')
          .iterator(function(gen, app) {
            count++;
          });
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, 'Invalid generator "a"');
        assert.equal(count, 0);
        cb(null);
      }
    });
  });
});
<commit_msg>add tests for thrown errors<commit_after>'use strict';

require('mocha');
var Base = require('base').namespace('test');
var assert = require('assert');
var Assemble = require('assemble-core');
var generators = require('base-generators');
Assemble.use(generators());

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

describe('base-compose', function() {
  beforeEach(function() {
    app = new Assemble();
    app.use(compose());
  });

  it('should add `.compose` method to `app`', function() {
    assert.equal(typeof app.compose, 'function');
  });

  it('should not have any generators if none are passed', function() {
    assert.deepEqual(app.compose().generators, []);
  });

  it('should throw an error when an app not using "base-generators" is used', function(cb) {
    function App () {
      Base.call(this);
    }
    Base.extend(App);
    app = new App();
    app.use(compose());
    try {
      app.compose();
      cb(new Error('expected an error'));
    } catch (err) {
      assert(err);
      assert.equal(err.message, '.compose expects an "app" using the "base-generators" plugin');
      cb();
    }
  });

  describe('data', function() {
    it('should copy data from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.data('foo', 'aaa');
      });

      app.compose(['a'])
        .data();

      assert.deepEqual(app.cache.data, a.cache.data);
    });

    it('should copy data from `a` to `app` specified by property path', function() {
      var a = app.register('a', function(a) {
        a.data({
          a: {
            b: {
              c: {d: 'e'},
              c1: {d: 'e'}
            },
            b1: {
              c1: {d: 'e'}
            }
          },
          a1: {b: {c: {d: 'e'}}}
        });
      });

      app.compose(['a'])
        .data('a.b.c');

      assert.deepEqual(app.cache.data, {a: {b: {c: {d: 'e'}}}});
    });

    it('should throw an error when the `data` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).data();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.data expects a ".data()" method on "app"');
        cb();
      }
    });
  });

  describe('engines', function() {
    it('should copy engines from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.engine('hbs', require('engine-handlebars'));
        a.engine('tmpl', require('engine-base'));
      });

      app.compose(['a'])
        .engines();

      assert.deepEqual(app._.engines, a._.engines);
    });

    it('should throw an error when the `engine` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).engines();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.engines expects an ".engine()" method on "app"');
        cb();
      }
    });
  });

  describe('helpers', function() {
    it('should copy helpers from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.helper('foo', function(str) {
          return str + ' FOO';
        });

        a.asyncHelper('bar', function(str, next) {
          next(null, str + ' BAR');
        });
      });

      app.compose(['a'])
        .helpers();

      assert.deepEqual(app._.helpers, a._.helpers);
    });

    it('should throw an error when the `helper` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).helpers();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.helpers expects a ".helper()" method on "app"');
        cb();
      }
    });
  });

  describe('options', function() {
    it('should copy options from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.option('foo', 'aaa');
      });

      app.compose(['a'])
        .options();

      assert.deepEqual(app.options, a.options);
    });

    it('should copy options from `a` to `app` specified by property path', function() {
      var a = app.register('a', function(a) {
        a.option({
          a: {
            b: {
              c: {d: 'e'},
              c1: {d: 'e'}
            },
            b1: {
              c1: {d: 'e'}
            }
          },
          a1: {b: {c: {d: 'e'}}}
        });
      });

      app.compose(['a'])
        .options('a.b.c');

      assert.deepEqual(app.options, {a: {b: {c: {d: 'e'}}}});
    });

    it('should throw an error when the `option` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).options();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.options expects an ".option()" method from "base-option" on "app"');
        cb();
      }
    });
  });

  describe('tasks', function() {
    it('should copy a task from `a` to `app`', function(cb) {
      var count = 0;
      var output = [];
      app.name = 'app';
      var a = app.register('a', function(a) {
        a.task('default', function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });
      });

      app.compose(['a'])
        .tasks('default');

      app.build('default', function(err) {
        if (err) cb(err);
        assert.deepEqual(output, ['app: default']);
        assert.equal(count, 1);
        cb();
      });
    });

    it('should copy a task and dependencies from `a` to `app`', function(cb) {
      var count = 0;
      var output = [];
      app.name = 'app';
      var a = app.register('a', function(a) {
        a.task('foo', function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });

        a.task('default', ['foo'], function(cb) {
          output.push(this.app.name + ': ' + this.name);
          count++;
          cb();
        });
      });

      app.compose(['a'])
        .tasks('default');

      app.build('default', function(err) {
        if (err) cb(err);
        assert.deepEqual(output, ['app: foo', 'app: default']);
        assert.equal(count, 2);
        cb();
      });
    });

    it('should throw an error when a task does not exist on `a`.', function(cb) {
      var a = app.register('a', function(a) {
        a.task('foo', function(cb) {
          cb();
        });

        a.task('default', function(cb) {
          cb();
        });
      });

      try {
        app.compose(['a'])
          .tasks(['foo', 'bar']);
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '"bar" not found in tasks');
        cb();
      }
    });

    it('should throw an error when the `task` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      delete app.task;

      app.register('a', function() {});
      try {
        app.compose(['a']).tasks();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.tasks expects a ".task()" method from "base-task" on "app"');
        cb();
      }
    });
  });

  describe('views', function() {
    it('should copy views from `a` to `app`', function() {
      var a = app.register('a', function(a) {
        a.create('templates');
        a.template('foo', {content: 'foo'});
      });

      app.compose(['a'])
        .views();

      assert.equal(typeof app.template, 'function');
      assert.equal(typeof app.templates, 'function');
      assert.equal(typeof app.views.templates, 'object');
      assert.equal(typeof app.views.templates.foo, 'object');
    });

    it('should only copy collections from `a` to `app` that are not already on `app`', function() {
      app.create('templates');
      app.template('bar', {content: 'bar'});
      var a = app.register('a', function(a) {
        a.create('templates');
        a.template('foo', {content: 'foo'});
      });

      app.compose(['a'])
        .views();

      assert.equal(typeof app.template, 'function');
      assert.equal(typeof app.templates, 'function');
      assert.equal(typeof app.views.templates, 'object');
      assert.equal(typeof app.views.templates.foo, 'object');
      assert.equal(typeof app.views.templates.bar, 'object');
    });

    it('should throw an error when the `views` api is not present', function(cb) {
      app = new Base();
      app.use(generators());
      app.use(compose());
      app.register('a', function() {});
      try {
        app.compose(['a']).views();
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, '.views expects the "app" to be inherited from "templates"');
        cb();
      }
    });
  });

  describe('iterator', function() {
    it('should allow using the iterator with the currently loaded generators', function() {
      app.register('a', function(a) {});
      app.register('b', function(b) {});

      var output = [];

      app.compose(['a', 'b'])
        .iterator(function(gen) {
          output.push(gen.name);
        });

      assert.deepEqual(output, ['a', 'b']);
    });

    it('should allow using the iterator with the custom specified generators', function() {
      app.register('a', function(a) {});
      app.register('b', function(b) {});
      app.register('c', function(c) {});
      app.register('d', function(d) {});

      var output = [];

      app.compose(['a', 'b'])
        .iterator(['c', 'd'], function(gen) {
          output.push(gen.name);
        });

      assert.deepEqual(output, ['c', 'd']);
    });

    it('should throw an error when a generator is not found', function(cb) {
      var count = 0;
      try {
        app.compose('a')
          .iterator(function(gen, app) {
            count++;
          });
        cb(new Error('expected an error'));
      } catch (err) {
        assert(err);
        assert.equal(err.message, 'Invalid generator "a"');
        assert.equal(count, 0);
        cb(null);
      }
    });
  });
});
<|endoftext|>


<commit_before>const = require(__dirname + '/test-server');
const = contentHead(__dirname + '/../lib/fileTypes');
const chai = require('chai').expect;
const chaiHttp = require('chai-http').request;

chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;

describe('REST functionality', function () {
  it('should reqpond to 404 error with GET request unknown route', (done) => {
    request(origin)
      .get('/doesnotexist')
      .end((err, req) => {
        expect(err).to.eql(null);
        expect(res).to.have.status(404);
        expect(res.body.msg).to.eql('Page not found');
        done();
      });
  });

  it('should GET', (done) => {
    request(origin)
      .get('/test')
      .end(('err, res') => {
        expect(err).to.eql(null);
        expect(res.body.msg).to.eql('get test');
        done();
      });
  });

  it('should POST', (done) => {
    request(origin)
      .post('/test')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.body.msg).to.eql('post test');
        done();
      });
  });

});

describe('server test', () => {
  after(() => {
    server.close();
  });

  //write get and post tests with correct exportObj.data function from fileTypes
  it('should GET and read files with exportObj.view function', (done) => {
    request(origin)
      .get('/filePath')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.text).to.eql('hi there\n');
        done();
      });
  });

  it('should POST request data with exportObj.data function', (done) => {
    request(origin)
      .post('/')
      .send('we are data')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.text).to.eql('we are data');
        done();
      });
  });
});

describe('reading fileTypes', () => {
  it('should match specified extension', () => {
    expect(contentHead('/index.html')).to.eql({'Content-Type': 'text/html'});
    expect(contentHead('/index.js')).to.eql({'Content-Type': 'application/json'});
  });
});
<commit_msg>added chai-http as dependency<commit_after>// const test-server = require(__dirname + '/test-server');
const contentHead = require(__dirname + '/../lib/content-type');
const chai = require('chai').expect;
const chaiHttp = require('chai-http').request;

// chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;

describe('REST functionality', function () {
  it('should respond to 404 error with GET request unknown route', (done) => {
    request(origin)
      .get('/doesnotexist')
      .end((err, req) => {
        expect(err).to.eql(null);
        expect(res).to.have.status(404);
        expect(res.body.msg).to.eql('Page not found');
        debugger;
        done();
      });
  });

  it('should GET', (done) => {
    request(origin)
      .get('/test')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.body.msg).to.eql('get test');
        done();
      });
  });

  it('should POST', (done) => {
    request(origin)
      .post('/test')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.body.msg).to.eql('post test');
        done();
      });
  });

});

describe('server test', () => {
  after(() => {
    server.close();
  });

  //write get and post tests with correct exportObj.data function from fileTypes
  it('should GET and read files with exportObj.view function', (done) => {
    request(origin)
      .get('/filePath')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.text).to.eql('hi there\n');
        done();
      });
  });

  it('should POST request data with exportObj.data function', (done) => {
    request(origin)
      .post('/')
      .send('we are data')
      .end((err, res) => {
        expect(err).to.eql(null);
        expect(res.text).to.eql('we are data');
        done();
      });
  });
});

describe('reading content-Type', () => {
  it('should match specified extension', () => {
    expect(contentHead('/index.html')).to.eql({'Content-Type': 'text/html'});
    expect(contentHead('/index.js')).to.eql({'Content-Type': 'application/json'});
  });
});
<|endoftext|>


<commit_before>var chai = require('chai'),
    expect = chai.expect,
    cb = require('../cron-builder.js');

describe('cron-builder', function () {
    var cron;

    it('defaults to "* * * * * *" when initialized without arguments', function () {
        cron = new cb();
        expect(cron.expression.minute).to.eql(['*']);
        expect(cron.expression.hour).to.eql(['*']);
        expect(cron.expression.dayOfTheMonth).to.eql(['*']);
        expect(cron.expression.monthOfTheYear).to.eql(['*']);
        expect(cron.expression.dayOfTheWeek).to.eql(['*']);
        expect(cron.expression.year).to.eql(['*']);
    });

    it('returns a working cron expression when calling .build()', function () {
        expect(cron.build()).to.equal('* * * * * *');
    });

    it('sets a single value', function () {
        cron = new cb();
        expect(cron.set(['5'], 'hour')).to.equal('5');
        expect(cron.build()).to.equal('* 5 * * * *');
    });

    it('sets multiple values at once', function () {
        cron = new cb();
        expect(cron.set(['0', '10', '20', '30', '40', '50'], 'minute')).to.equal('0,10,20,30,40,50');
        expect(cron.build()).to.equal('0,10,20,30,40,50 * * * * *');
    });

    it('sets a range', function () {
        cron = new cb();
        expect(cron.set(['5-7'], 'dayOfTheWeek')).to.equal('5-7');
        expect(cron.build()).to.equal('* * * * 5-7 *');
    });

    it('multiple sets build the cron string accurately', function () {
        cron = new cb();
        cron.set(['10', '30', '50'], 'minute');
        cron.set(['6', '18'], 'hour');
        cron.set(['1', '15'], 'dayOfTheMonth');
        cron.set(['1-5'], 'dayOfTheWeek');
        cron.set(['2015-2025'], 'year');
        expect(cron.build()).to.equal('10,30,50 6,18 1,15 * 1-5 2015-2025');
    });

    it('validates against setting an incorrect measureOfTime', function () {
        cron = new cb();
        expect(function () { cron.set(['5'], 'minutes') }).to.throw(Error);
    });

    it('validates against setting a value that is not an Array', function () {
        cron = new cb();
        expect(function () { cron.set('10', 'hour') }).to.throw(Error);
    });

    it('validates against setting a value that is not a number or range of numbers', function () {
        cron = new cb();
        expect(function () { cron.set(['!'], 'year') }).to.throw(Error);
    });

    describe('validates against setting values outside the valid range', function () {
        it('validates against values too low', function () {
            cron = new cb();
            expect(function () { cron.set(['0'], 'dayOfTheWeek') }).to.throw(Error);
        });

        it('validates against values too high', function () {
            cron = new cb();
            expect(function () { cron.set(['100'], 'hour') }).to.throw(Error);
        });

        it('validates against setting a range that is out of bounds', function () {
            cron = new cb();
            expect(function () { cron.set(['1834-2015'], 'year') }).to.throw(Error);

            expect(function () { cron.set(['20-60'], 'minute') }).to.throw(Error);

            expect(function () { cron.set(['12', '22-26', '15'], 'hour') }).to.throw(Error);
        });
    });

    it('gets a single value', function () {
        cron = new cb();
        cron.set(['30'], 'minute');
        expect(cron.get('minute')).to.equal('30');
    });
});

//var cb = require('./cron-builder.js'),
//    test,
//    test2,
//    test2Exp;
//
//// init with default values ('* * * * * *')
//test = new cb();
//console.log('test init: ', test.build());
//
//test.addValue('3', 'minute');
//test.addValue('56', 'minute'); // test multiple values
//test.addValue('6', 'minutes'); // test spelling error
//
//test.addValue('1', 'hour');
//test.addValue('5', 'hour'); // test multiple values
//test.addValue('5', 'hour'); // test duplicates
//test.addValue('6-24', 'hour');
//
//test.addValue('26', 'dayOfTheMonth');
//
//test.addValue('7', 'monthOfTheYear');
//
//test.addValue('5', 'dayOfTheWeek');
//
//test.addValue('2016', 'year');
//
//console.log('after adding values: ', test.build());
//
//test.removeValue('6-24', 'hour');
//test.removeValue('6-24', 'hour');
//
//test.removeValue('2016', 'year');
//console.log('after removing values: ', test.build());
//
//console.log('getting minutes values: ', test.get('minute'));
//
//console.log('setting new minutes', test.set(['13', '26', '54-57'], 'minute'));
//test.set('5,6,7', 'dayOfTheMonth');
//test.set(['1-6'], 'dayoftheweek');
//
//console.log('test final build', test.build());
//
//// test with explicit values
//test2 = new cb('34 1 * *');
//
//console.log('test2 init', test2.build());
//
//test2Exp = test2.getAll();
//console.log('test2Exp', test2Exp);
//
//// validation test for too many values
//test2Exp.extraUnit = ['1'];
//console.log('error, exp too long', test2.setAll(test2Exp))
//
//// validation test for bad values while using setAll
//test2Exp = test2.getAll();
//
//
//
//console.log('test2 final build', test2.build());
<commit_msg>testing get validation<commit_after>var chai = require('chai'),
    expect = chai.expect,
    cb = require('../cron-builder.js');

describe('cron-builder', function () {
    var cron;

    it('defaults to "* * * * * *" when initialized without arguments', function () {
        cron = new cb();
        expect(cron.expression.minute).to.eql(['*']);
        expect(cron.expression.hour).to.eql(['*']);
        expect(cron.expression.dayOfTheMonth).to.eql(['*']);
        expect(cron.expression.monthOfTheYear).to.eql(['*']);
        expect(cron.expression.dayOfTheWeek).to.eql(['*']);
        expect(cron.expression.year).to.eql(['*']);
    });

    it('returns a working cron expression when calling .build()', function () {
        expect(cron.build()).to.equal('* * * * * *');
    });

    it('sets a single value', function () {
        cron = new cb();
        expect(cron.set(['5'], 'hour')).to.equal('5');
        expect(cron.build()).to.equal('* 5 * * * *');
    });

    it('sets multiple values at once', function () {
        cron = new cb();
        expect(cron.set(['0', '10', '20', '30', '40', '50'], 'minute')).to.equal('0,10,20,30,40,50');
        expect(cron.build()).to.equal('0,10,20,30,40,50 * * * * *');
    });

    it('sets a range', function () {
        cron = new cb();
        expect(cron.set(['5-7'], 'dayOfTheWeek')).to.equal('5-7');
        expect(cron.build()).to.equal('* * * * 5-7 *');
    });

    it('multiple sets build the cron string accurately', function () {
        cron = new cb();
        cron.set(['10', '30', '50'], 'minute');
        cron.set(['6', '18'], 'hour');
        cron.set(['1', '15'], 'dayOfTheMonth');
        cron.set(['1-5'], 'dayOfTheWeek');
        cron.set(['2015-2025'], 'year');
        expect(cron.build()).to.equal('10,30,50 6,18 1,15 * 1-5 2015-2025');
    });

    it('validates against setting an incorrect measureOfTime', function () {
        cron = new cb();
        expect(function () { cron.set(['5'], 'minutes') }).to.throw(Error);
    });

    it('validates against setting a value that is not an Array', function () {
        cron = new cb();
        expect(function () { cron.set('10', 'hour') }).to.throw(Error);
    });

    it('validates against setting a value that is not a number or range of numbers', function () {
        cron = new cb();
        expect(function () { cron.set(['!'], 'year') }).to.throw(Error);
    });

    describe('validates against setting values outside the valid range', function () {
        it('validates against values too low', function () {
            cron = new cb();
            expect(function () { cron.set(['0'], 'dayOfTheWeek') }).to.throw(Error);
        });

        it('validates against values too high', function () {
            cron = new cb();
            expect(function () { cron.set(['100'], 'hour') }).to.throw(Error);
        });

        it('validates against setting a range that is out of bounds', function () {
            cron = new cb();
            expect(function () { cron.set(['1834-2015'], 'year') }).to.throw(Error);

            expect(function () { cron.set(['20-60'], 'minute') }).to.throw(Error);

            expect(function () { cron.set(['12', '22-26', '15'], 'hour') }).to.throw(Error);
        });
    });

    it('gets a single value', function () {
        cron = new cb();
        cron.set(['30'], 'minute');
        expect(cron.get('minute')).to.equal('30');
    });

    it('validates against getting with an invalid measureOfTime', function () {
        cron = new cb();
        expect(function () { cron.get('hours'); }).to.throw(Error);
    });
});

//var cb = require('./cron-builder.js'),
//    test,
//    test2,
//    test2Exp;
//
//// init with default values ('* * * * * *')
//test = new cb();
//console.log('test init: ', test.build());
//
//test.addValue('3', 'minute');
//test.addValue('56', 'minute'); // test multiple values
//test.addValue('6', 'minutes'); // test spelling error
//
//test.addValue('1', 'hour');
//test.addValue('5', 'hour'); // test multiple values
//test.addValue('5', 'hour'); // test duplicates
//test.addValue('6-24', 'hour');
//
//test.addValue('26', 'dayOfTheMonth');
//
//test.addValue('7', 'monthOfTheYear');
//
//test.addValue('5', 'dayOfTheWeek');
//
//test.addValue('2016', 'year');
//
//console.log('after adding values: ', test.build());
//
//test.removeValue('6-24', 'hour');
//test.removeValue('6-24', 'hour');
//
//test.removeValue('2016', 'year');
//console.log('after removing values: ', test.build());
//
//console.log('getting minutes values: ', test.get('minute'));
//
//console.log('setting new minutes', test.set(['13', '26', '54-57'], 'minute'));
//test.set('5,6,7', 'dayOfTheMonth');
//test.set(['1-6'], 'dayoftheweek');
//
//console.log('test final build', test.build());
//
//// test with explicit values
//test2 = new cb('34 1 * *');
//
//console.log('test2 init', test2.build());
//
//test2Exp = test2.getAll();
//console.log('test2Exp', test2Exp);
//
//// validation test for too many values
//test2Exp.extraUnit = ['1'];
//console.log('error, exp too long', test2.setAll(test2Exp))
//
//// validation test for bad values while using setAll
//test2Exp = test2.getAll();
//
//
//
//console.log('test2 final build', test2.build());
<|endoftext|>


<commit_before>/* eslint-env mocha */

'use strict';

const assert = require(`assert`);
const debug = require(`debug`)(`test`);
const fs = require(`fs`);
const jsdom = require(`mocha-jsdom`);
const parse5 = require(`parse5-utils`);
const path = require(`path`);
const vdomToHTML = require(`vdom-to-html`);
const snabbdomToHTML = require(`snabbdom-to-html`);

const render = require(`..`);

function fixtureFilename(name) {
  return path.resolve(__dirname, `fixtures/` + name + `.jade`);
}

function fixture(name) {
  return fs.readFileSync(fixtureFilename(name), `utf8`);
}

function fixtureToHTML(fixtureName, locals, options) {
  options = Object.assign({filename: fixtureFilename(fixtureName)}, options);

  const snabb = options.vdom === `snabbdom`;
  if (snabb) {
    // putting all 'raw' attrs into the props object allows
    // the same template fixtures to work with both virtual-dom
    // and snabbdom, otherwise snabb expects special keys
    // props: {}, attrs: {}
    options.propsWrapper = `props`;
  }

  const compiled = render(fixture(fixtureName), options);
  debug(compiled);

  const fn = eval(`(${compiled})`);
  const root = fn.call({class: `asdf`}, locals);
  const toHTML = snabb ? snabbdomToHTML : vdomToHTML;
  const html = toHTML(root);
  parse5.parse(html, true);
  return html;
}

describe(`configuration`, function() {
  it(`should throw when an invalid vdom config is supplied`, function() {
    let threw = false;
    try {
      render(fixture(`simple`), {
        filename: fixtureFilename(`simple`),
        vdom: `foobar`,
      });
    } catch (err) {
      threw = true;
      assert(err.message === `No virtual-jade config found for vdom type: foobar`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should throw a parser error with filename and line number when rendering a broken template`, function() {
    const file = `break-parser`;
    const filename = fixtureFilename(file);
    const compile = function() {
      render(fixture(file), {filename});
    };
    let threw = false;

    try {
      compile();
    } catch (err) {
      threw = true;
      const filenameAndLineNo = new RegExp(filename.replace(`/`, `\/`) + `:2`);
      assert(err.path === filename, `err.path should be the full path to the jade file`);
      assert(err.message.match(filenameAndLineNo), `the error message should contain the full path and line number`);
      assert(err.message.match(/Unexpected identifier/), `the error message should contain the error type`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should throw a compiler error with filename and line number when rendering a broken template`, function() {
    const file = `break-compiler`;
    const filename = fixtureFilename(file);
    const compile = function() {
      render(fixture(file), {filename});
    };
    let threw = false;

    try {
      compile();
    } catch (err) {
      threw = true;
      const filenameAndLineNo = new RegExp(filename.replace(`/`, `\/`) + `:2`);
      assert(err.path === filename, `err.path (` + err.path + `) should be the full path to the jade file`);
      assert(err.message.match(filenameAndLineNo), `the error message should contain the full path and line number`);
      assert(err.message.match(/You can only have one top-level tag!/), `the error message should contain the error type`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should render a template without options`, function() {
    const compiled = render(fixture(`attributes`));
    assert(compiled.includes(`class1`));
    assert(compiled.includes(`foo`));
    assert(compiled.includes(`doge`));
  });
});

// run rendering tests against each supported Virtual DOM library

const VDOM_LIBS = [
  `virtual-dom`,
  `snabbdom`,
];

for (let vdom of VDOM_LIBS) {
  const renderFixture = function(fixtureName, locals) {
    return fixtureToHTML(fixtureName, locals, {vdom});
  };

  describe(`rendering with ${vdom}`, function() {
    it(`should render a template`, function() {
      const html = renderFixture(`item`, {
        item: {
          id: `1234`,
          title: `some title`,
          description: `some description`,
          active: true,
        },
      });

      assert(~html.indexOf(`item active`));
      assert(~html.indexOf(`class="title"`));
      assert(~html.indexOf(`<h3`));
      assert(~html.indexOf(`</h3>`));
      assert(~html.indexOf(`some title`));
      assert(~html.indexOf(`some description`));
    });

    it(`should beautify when option is set`, function() {
      const fn = render(fixture(`item`), {pretty: true});
      const lines = fn.split(`\n`);
      assert(lines.length > 15);
      assert(lines[lines.length - 1].trim() === `}`);
    });

    it(`should insert dynamic tag names`, function() {
      let html = renderFixture(`dynamic-tag`, {myTag: `input`});
      assert(html.includes(`<input class="llamas">`));
      html = renderFixture(`dynamic-tag`, {myTag: `textarea`});
      assert(html.includes(`<textarea class="llamas">`));
    });

    it(`renders a simple template`, function() {
      const html = renderFixture(`simple`);
      assert(html === `<div>This is text</div>`);
    });

    it(`translates basic class notation`, function() {
      const html = renderFixture(`class`);
      assert(html.includes(`div class="foo"`));
      assert(html.includes(`div class="baz llamas"`));
    });

    describe(`iteration`, function() {
      it(`should run "each" loops correctly`, function() {
        const html = renderFixture(`each-expression`, {values: [`foo`, `bar`]});
        assert(html.includes(`<li>foo</li><li>bar</li>`));
      });

      it(`should run "while" loops correctly`, function() {
        const html = renderFixture(`while`);
        assert(html.match(/
/g).length === 5);
      });
    });

    describe(`multiple files`, function() {
      it(`should insert included files`, function() {
        const html = renderFixture(`include`);
        assert(html.includes(`<p>Hello</p>`));
        assert(html.includes(`<div class="included-content">llamas!!!</div>`));
        assert(html.includes(`<p>world</p>`));
      });

      it(`should make included mixins available`, function() {
        const html = renderFixture(`include-with-mixin`);
        assert(html.includes(`<div class="foo">`));
        assert(html.includes(`<div class="hello">insert me</div>`));
      });

      it(`should insert extended files`, function() {
        const html = renderFixture(`extends`);
        assert(html.includes(`<div class="foo">`));
        assert(html.includes(`capybara`));
        assert(html.includes(`default content`));
      });
    });

    describe(`attributes`, function() {
      it(`should add arbitrary attributes`, function() {
        const html = renderFixture(`attributes`);
        assert(html.includes(`required`));
        assert(!html.includes(`something`) || html.includes(`something="false"`));
      });

      it(`should add class attributes in array notation`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`1 2`));
        html = renderFixture(`attributes`, {variable: `meow`});
        assert(html.includes(`1 2 meow`));
      });

      it(`should add class attributes in object notation`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`obj1`));
        assert(!html.includes(`obj2`));

        html = renderFixture(`attributes`, {variable: `doge`});
        assert(html.includes(`obj1`));
        assert(html.includes(`obj2`));
      });

      it(`should combine class attributes in different notations gracefully`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`mixed`));
        assert(html.includes(`mixedArray1`));
        assert(!html.includes(`mixedObj1`));

        html = renderFixture(`attributes`, {var2: `doge`});
        assert(html.includes(`mixed`));
        assert(html.includes(`mixedArray1`));
        assert(html.includes(`mixedObj1`));
        assert(html.includes(`doge`));
      });

      it(`should render data attributes`, function() {
        const html = renderFixture(`attributes`, {variable: `capybara`});
        assert(html.includes(`data-foo-id="42"`));
        assert(html.includes(`data-var="capybara"`));
      });

      it(`should convert attributes to correct property names`, function() {
        const html = renderFixture(`attributes`);
        assert(html.includes(`autocomplete="on"`));
        assert(html.includes(`tabindex="5"`));
        assert(html.includes(`for="special-attr"`));
      });
    });

    describe(`case statements`, function() {
      it(`should not execute any cases when none match`, function() {
        const html = renderFixture(`case`);
        assert(!html.includes(`foo`));
        assert(!html.includes(`bar`));
      });

      it(`should execute default when no others match`, function() {
        const html = renderFixture(`case`);
        assert(html.includes(`llama`));
      });

      it(`should execute only one match`, function() {
        const html = renderFixture(`case`, {variable: 1});
        assert(html.includes(`span`));
        assert(!html.includes(`input`));
        assert(!html.includes(`textarea`));
      });

      it(`should fall through from the first case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `d`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });

      it(`should fall through from the middle case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `e`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });

      it(`should fall through from the last case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `f`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });
    });

    describe(`code blocks`, function() {
      let html;

      beforeEach(function() {
        html = renderFixture(`code`);
      });

      it(`should run unbuffered code correctly`, function() {
        assert(~html.indexOf(`<div class="example bar">`));
      });

      it(`should use locals when evaluating`, function() {
        html = renderFixture(`code`, {x: 0});
        assert(~html.indexOf(`<div class="baz">`));

        html = renderFixture(`code`, {x: -1});
        assert(!~html.indexOf(`<div class="baz">`));
      });

      it(`should output inline buffered code`, function() {
        assert(html.includes(`<div class="inline-script"><div class="raw-inline">within another div`));
      });

      it(`should output standalone buffered code`, function() {
        assert(html.includes(`<div class="raw-buffered">raw so raw`));
      });

      it(`should not output unbuffered code`, function() {
        assert(!html.includes(`should not be output`));
      });
    });
  });
}

describe(`Render`, function() {
  jsdom();

  describe(`multiple files`, function() {
    it(`should insert included literal (non-jade) files`, function() {
      const html = fixtureToHTML(`literal-import`);
      const singleRootImport = `<div class="test">test</div>`;
      const multiRootImport = `<div>child 1</div><div>child 2</div>`;
      const htmlEntities = function(str) {
        return String(str).replace(/&/g, `&`).replace(/</g, `<`).replace(/>/g, `>`).replace(/"/g, `"`);
      };
      const expectedContents =
        `<div class="raw">` +
          `<div class="single-root">` +
            `<text>` + htmlEntities(singleRootImport) + `</text>` +
          `</div>` +
          `<div class="multi-root">` +
            `<text>` + htmlEntities(`<div>` + multiRootImport + `</div>`) + `</text>` +
          `</div>` +
        `</div>`;
      assert(html === expectedContents);
    });
  });
});
<commit_msg>improve test debugging output<commit_after>/* eslint-env mocha */

'use strict';

const assert = require(`assert`);
const debug = require(`debug`)(`test`);
const fs = require(`fs`);
const jsdom = require(`mocha-jsdom`);
const parse5 = require(`parse5-utils`);
const path = require(`path`);
const vdomToHTML = require(`vdom-to-html`);
const snabbdomToHTML = require(`snabbdom-to-html`);

const render = require(`..`);

function fixtureFilename(name) {
  return path.resolve(__dirname, `fixtures/` + name + `.jade`);
}

function fixture(name) {
  return fs.readFileSync(fixtureFilename(name), `utf8`);
}

function fixtureToHTML(fixtureName, locals, options) {
  options = Object.assign({filename: fixtureFilename(fixtureName)}, options);

  const snabb = options.vdom === `snabbdom`;
  if (snabb) {
    // putting all 'raw' attrs into the props object allows
    // the same template fixtures to work with both virtual-dom
    // and snabbdom, otherwise snabb expects special keys
    // props: {}, attrs: {}
    options.propsWrapper = `props`;
  }

  const compiled = render(fixture(fixtureName), options);
  debug(compiled);

  const fn = eval(`(${compiled})`);
  const root = fn.call({class: `asdf`}, locals);
  const toHTML = snabb ? snabbdomToHTML : vdomToHTML;
  const html = toHTML(root);
  debug(html);

  parse5.parse(html, true);
  return html;
}

describe(`configuration`, function() {
  it(`should throw when an invalid vdom config is supplied`, function() {
    let threw = false;
    try {
      render(fixture(`simple`), {
        filename: fixtureFilename(`simple`),
        vdom: `foobar`,
      });
    } catch (err) {
      threw = true;
      assert(err.message === `No virtual-jade config found for vdom type: foobar`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should throw a parser error with filename and line number when rendering a broken template`, function() {
    const file = `break-parser`;
    const filename = fixtureFilename(file);
    const compile = function() {
      render(fixture(file), {filename});
    };
    let threw = false;

    try {
      compile();
    } catch (err) {
      threw = true;
      const filenameAndLineNo = new RegExp(filename.replace(`/`, `\/`) + `:2`);
      assert(err.path === filename, `err.path should be the full path to the jade file`);
      assert(err.message.match(filenameAndLineNo), `the error message should contain the full path and line number`);
      assert(err.message.match(/Unexpected identifier/), `the error message should contain the error type`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should throw a compiler error with filename and line number when rendering a broken template`, function() {
    const file = `break-compiler`;
    const filename = fixtureFilename(file);
    const compile = function() {
      render(fixture(file), {filename});
    };
    let threw = false;

    try {
      compile();
    } catch (err) {
      threw = true;
      const filenameAndLineNo = new RegExp(filename.replace(`/`, `\/`) + `:2`);
      assert(err.path === filename, `err.path (` + err.path + `) should be the full path to the jade file`);
      assert(err.message.match(filenameAndLineNo), `the error message should contain the full path and line number`);
      assert(err.message.match(/You can only have one top-level tag!/), `the error message should contain the error type`);
    } finally {
      assert(threw, `an error should be thrown`);
    }
  });

  it(`should render a template without options`, function() {
    const compiled = render(fixture(`attributes`));
    assert(compiled.includes(`class1`));
    assert(compiled.includes(`foo`));
    assert(compiled.includes(`doge`));
  });
});

// run rendering tests against each supported Virtual DOM library

const VDOM_LIBS = [
  `virtual-dom`,
  `snabbdom`,
];

for (let vdom of VDOM_LIBS) {
  const renderFixture = function(fixtureName, locals) {
    return fixtureToHTML(fixtureName, locals, {vdom, pretty: true});
  };

  describe(`rendering with ${vdom}`, function() {
    it(`should render a template`, function() {
      const html = renderFixture(`item`, {
        item: {
          id: `1234`,
          title: `some title`,
          description: `some description`,
          active: true,
        },
      });

      assert(~html.indexOf(`item active`));
      assert(~html.indexOf(`class="title"`));
      assert(~html.indexOf(`<h3`));
      assert(~html.indexOf(`</h3>`));
      assert(~html.indexOf(`some title`));
      assert(~html.indexOf(`some description`));
    });

    it(`should beautify when option is set`, function() {
      const fn = render(fixture(`item`), {pretty: true});
      const lines = fn.split(`\n`);
      assert(lines.length > 15);
      assert(lines[lines.length - 1].trim() === `}`);
    });

    it(`should insert dynamic tag names`, function() {
      let html = renderFixture(`dynamic-tag`, {myTag: `input`});
      assert(html.includes(`<input class="llamas">`));
      html = renderFixture(`dynamic-tag`, {myTag: `textarea`});
      assert(html.includes(`<textarea class="llamas">`));
    });

    it(`renders a simple template`, function() {
      const html = renderFixture(`simple`);
      assert(html === `<div>This is text</div>`);
    });

    it(`translates basic class notation`, function() {
      const html = renderFixture(`class`);
      assert(html.includes(`div class="foo"`));
      assert(html.includes(`div class="baz llamas"`));
    });

    describe(`iteration`, function() {
      it(`should run "each" loops correctly`, function() {
        const html = renderFixture(`each-expression`, {values: [`foo`, `bar`]});
        assert(html.includes(`<li>foo</li><li>bar</li>`));
      });

      it(`should run "while" loops correctly`, function() {
        const html = renderFixture(`while`);
        assert(html.match(/
/g).length === 5);
      });
    });

    describe(`multiple files`, function() {
      it(`should insert included files`, function() {
        const html = renderFixture(`include`);
        assert(html.includes(`<p>Hello</p>`));
        assert(html.includes(`<div class="included-content">llamas!!!</div>`));
        assert(html.includes(`<p>world</p>`));
      });

      it(`should make included mixins available`, function() {
        const html = renderFixture(`include-with-mixin`);
        assert(html.includes(`<div class="foo">`));
        assert(html.includes(`<div class="hello">insert me</div>`));
      });

      it(`should insert extended files`, function() {
        const html = renderFixture(`extends`);
        assert(html.includes(`<div class="foo">`));
        assert(html.includes(`capybara`));
        assert(html.includes(`default content`));
      });
    });

    describe(`attributes`, function() {
      it(`should add arbitrary attributes`, function() {
        const html = renderFixture(`attributes`);
        assert(html.includes(`required`));
        assert(!html.includes(`something`) || html.includes(`something="false"`));
      });

      it(`should add class attributes in array notation`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`1 2`));
        html = renderFixture(`attributes`, {variable: `meow`});
        assert(html.includes(`1 2 meow`));
      });

      it(`should add class attributes in object notation`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`obj1`));
        assert(!html.includes(`obj2`));

        html = renderFixture(`attributes`, {variable: `doge`});
        assert(html.includes(`obj1`));
        assert(html.includes(`obj2`));
      });

      it(`should combine class attributes in different notations gracefully`, function() {
        let html = renderFixture(`attributes`);
        assert(html.includes(`mixed`));
        assert(html.includes(`mixedArray1`));
        assert(!html.includes(`mixedObj1`));

        html = renderFixture(`attributes`, {var2: `doge`});
        assert(html.includes(`mixed`));
        assert(html.includes(`mixedArray1`));
        assert(html.includes(`mixedObj1`));
        assert(html.includes(`doge`));
      });

      it(`should render data attributes`, function() {
        const html = renderFixture(`attributes`, {variable: `capybara`});
        assert(html.includes(`data-foo-id="42"`));
        assert(html.includes(`data-var="capybara"`));
      });

      it(`should convert attributes to correct property names`, function() {
        const html = renderFixture(`attributes`);
        assert(html.includes(`autocomplete="on"`));
        assert(html.includes(`tabindex="5"`));
        assert(html.includes(`for="special-attr"`));
      });
    });

    describe(`case statements`, function() {
      it(`should not execute any cases when none match`, function() {
        const html = renderFixture(`case`);
        assert(!html.includes(`foo`));
        assert(!html.includes(`bar`));
      });

      it(`should execute default when no others match`, function() {
        const html = renderFixture(`case`);
        assert(html.includes(`llama`));
      });

      it(`should execute only one match`, function() {
        const html = renderFixture(`case`, {variable: 1});
        assert(html.includes(`span`));
        assert(!html.includes(`input`));
        assert(!html.includes(`textarea`));
      });

      it(`should fall through from the first case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `d`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });

      it(`should fall through from the middle case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `e`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });

      it(`should fall through from the last case in a chain`, function() {
        const html = renderFixture(`case`, {variable2: `f`});
        assert(html.includes(`bar`));
        assert(!html.includes(`foo`));
      });
    });

    describe(`code blocks`, function() {
      let html;

      beforeEach(function() {
        html = renderFixture(`code`);
      });

      it(`should run unbuffered code correctly`, function() {
        assert(~html.indexOf(`<div class="example bar">`));
      });

      it(`should use locals when evaluating`, function() {
        html = renderFixture(`code`, {x: 0});
        assert(~html.indexOf(`<div class="baz">`));

        html = renderFixture(`code`, {x: -1});
        assert(!~html.indexOf(`<div class="baz">`));
      });

      it(`should output inline buffered code`, function() {
        assert(html.includes(`<div class="inline-script"><div class="raw-inline">within another div`));
      });

      it(`should output standalone buffered code`, function() {
        assert(html.includes(`<div class="raw-buffered">raw so raw`));
      });

      it(`should not output unbuffered code`, function() {
        assert(!html.includes(`should not be output`));
      });
    });
  });
}

describe(`Render`, function() {
  jsdom();

  describe(`multiple files`, function() {
    it(`should insert included literal (non-jade) files`, function() {
      const html = fixtureToHTML(`literal-import`);
      const singleRootImport = `<div class="test">test</div>`;
      const multiRootImport = `<div>child 1</div><div>child 2</div>`;
      const htmlEntities = function(str) {
        return String(str).replace(/&/g, `&`).replace(/</g, `<`).replace(/>/g, `>`).replace(/"/g, `"`);
      };
      const expectedContents =
        `<div class="raw">` +
          `<div class="single-root">` +
            `<text>` + htmlEntities(singleRootImport) + `</text>` +
          `</div>` +
          `<div class="multi-root">` +
            `<text>` + htmlEntities(`<div>` + multiRootImport + `</div>`) + `</text>` +
          `</div>` +
        `</div>`;
      assert(html === expectedContents);
    });
  });
});
<|endoftext|>


<commit_before>/* global describe, it */
'use strict';
import austin from 'austin';
import chai, {expect} from 'chai';
import chaiImmutable from 'chai-immutable';
import combineReducers from '../lib/';
import {List, Map} from 'immutable';

chai.use(chaiImmutable);

describe('redux-immutable-combine-reducers', () => {
  it('should throw error if an object or Immutable Map is not given', () => {
    function objTest() {
      combineReducers();
    }

    function immutableTest() {
      combineReducers(List());
    }

    expect(objTest).to.throw(TypeError, /Expected an object or Immutable Map/);
    expect(immutableTest).to.throw(TypeError, /Expected an object or Immutable Map/);
  });

  it('should throw error if not all of an object\'s keys are functions', () => {
    function test() {
      combineReducers({
        test() {},
        string: ''
      });
    }

    expect(test).to.throw(Error, /Expected an object with all keys being functions/);
  });

  it('should return function that returns a map and calls all reducers for an object', () => {
    const reducers = {
      testReducer(state = 0, action = {}) {
        switch (action.type) {
          case 'INCREMENT':
            return state + 1;
          default:
            return state;
        }
      },
      anotherTestReducer(state = '', action = {}) {
        switch (action.type) {
          case 'SET':
            return action.value;
          default:
            return state;
        }
      }
    };
    austin.spy(reducers, 'testReducer');
    austin.spy(reducers, 'anotherTestReducer');

    expect(combineReducers(reducers)()).to.equal(Map({
      testReducer: 0,
      anotherTestReducer: ''
    }));

    expect(reducers.testReducer.callCount()).to.equal(1);
    expect(reducers.anotherTestReducer.callCount()).to.equal(1);
  });

  it('should throw error if not all of a Map\'s entries are functions', () => {
    function test() {
      combineReducers(Map({
        test() {},
        string: ''
      }));
    }

    expect(test).to.throw(Error, /Expected an Immutable.Map with all entries being functions/);
  });

  it('should return function that returns a map and calls all reducers for a Map', () => {
    let testReducerCalled = false
      , anotherTestReducerCalled = false;

    const mapReducers = Map({
      testReducer(state = 0, action = {}) {
        testReducerCalled = true;
        switch (action.type) {
          case 'INCREMENT':
            return state + 1;
          default:
            return state;
        }
      },
      anotherTestReducer(state = '', action = {}) {
        anotherTestReducerCalled = true;
        switch (action.type) {
          case 'SET':
            return action.value;
          default:
            return state;
        }
      }
    });

    expect(combineReducers(mapReducers)()).to.equal(Map({
      testReducer: 0,
      anotherTestReducer: ''
    }));

    expect(testReducerCalled).to.equal(true);
    expect(anotherTestReducerCalled).to.equal(true);
  });

  it('should return same Immutable reference if nothing changed', () => {
    const sameReducer = {
      test(state = Map({})) {
        return state;
      }
    };
    const reducer = combineReducers(sameReducer);
    const first = reducer();
    const second = reducer(first);

    /* eslint eqeqeq: 0 */
    expect(first == second).to.equal(true);
  });
});
<commit_msg>test(combineReducers): verify action is passed<commit_after>/* global describe, it */
'use strict';
import austin from 'austin';
import chai, {expect} from 'chai';
import chaiImmutable from 'chai-immutable';
import combineReducers from '../lib/';
import {List, Map} from 'immutable';

chai.use(chaiImmutable);

describe('redux-immutable-combine-reducers', () => {
  it('should throw error if an object or Immutable Map is not given', () => {
    function objTest() {
      combineReducers();
    }

    function immutableTest() {
      combineReducers(List());
    }

    expect(objTest).to.throw(TypeError, /Expected an object or Immutable Map/);
    expect(immutableTest).to.throw(TypeError, /Expected an object or Immutable Map/);
  });

  it('should throw error if not all of an object\'s keys are functions', () => {
    function test() {
      combineReducers({
        test() {},
        string: ''
      });
    }

    expect(test).to.throw(Error, /Expected an object with all keys being functions/);
  });

  it('should return function that returns a map and calls all reducers for an object', () => {
    const reducers = {
      testReducer(state = 0, action = {}) {
        switch (action.type) {
          case 'INCREMENT':
            return state + 1;
          default:
            return state;
        }
      },
      anotherTestReducer(state = '', action = {}) {
        switch (action.type) {
          case 'SET':
            return action.value;
          default:
            return state;
        }
      }
    };
    austin.spy(reducers, 'testReducer');
    austin.spy(reducers, 'anotherTestReducer');

    const firstState = combineReducers(reducers)();
    expect(firstState).to.equal(Map({
      testReducer: 0,
      anotherTestReducer: ''
    }));

    expect(reducers.testReducer.callCount()).to.equal(1);
    expect(reducers.anotherTestReducer.callCount()).to.equal(1);

    const secondState = combineReducers(reducers)(firstState, {type: 'INCREMENT'});
    expect(secondState).to.equal(Map({
      testReducer: 1,
      anotherTestReducer: ''
    }));
  });

  it('should throw error if not all of a Map\'s entries are functions', () => {
    function test() {
      combineReducers(Map({
        test() {},
        string: ''
      }));
    }

    expect(test).to.throw(Error, /Expected an Immutable.Map with all entries being functions/);
  });

  it('should return function that returns a map and calls all reducers for a Map', () => {
    let testReducerCalled = false
      , anotherTestReducerCalled = false;

    const mapReducers = Map({
      testReducer(state = 0, action = {}) {
        testReducerCalled = true;
        switch (action.type) {
          case 'INCREMENT':
            return state + 1;
          default:
            return state;
        }
      },
      anotherTestReducer(state = '', action = {}) {
        anotherTestReducerCalled = true;
        switch (action.type) {
          case 'SET':
            return action.value;
          default:
            return state;
        }
      }
    });

    const firstState = combineReducers(mapReducers)();

    expect(firstState).to.equal(Map({
      testReducer: 0,
      anotherTestReducer: ''
    }));

    expect(testReducerCalled).to.equal(true);
    expect(anotherTestReducerCalled).to.equal(true);

    const secondState = combineReducers(mapReducers)(firstState, {type: 'INCREMENT'});
    expect(secondState).to.equal(Map({
      testReducer: 1,
      anotherTestReducer: ''
    }));
  });

  it('should return same Immutable reference if nothing changed', () => {
    const sameReducer = {
      test(state = Map({})) {
        return state;
      }
    };
    const reducer = combineReducers(sameReducer);
    const first = reducer();
    const second = reducer(first);

    /* eslint eqeqeq: 0 */
    expect(first == second).to.equal(true);
  });
});
<|endoftext|>


<commit_before>var Trie = require('../app/trie');

describe('Trie', function() {
  var trie;

  beforeEach(function() {
    trie = new Trie();
  });

  it('should be an object', function() {
    expect(trie).to.be.ok;
  });
});
<commit_msg>Add tests for Trie add, search, and find methods<commit_after>var Trie = require('../app/trie');

describe('Trie', function() {
  var trie;

  beforeEach(function() {
    trie = new Trie();
  });

  it('should be an object', function() {
    expect(trie).to.be.ok;
  });

  it('should have add method', function() {
    expect(trie.add).to.be.an.instanceof(Function);
  });

  it('should have search method', function() {
    expect(trie.search).to.be.an.instanceof(Function);
  });

  it('should have find method', function() {
    expect(trie.find).to.be.an.instanceof(Function);
  });
});
<|endoftext|>


<commit_before>import * as I from 'infestines'
import * as R from 'ramda'

export function lazy(ty2ty) {
  let memo = x => {
    memo = ty2ty(rec)
    return memo(x)
  }
  const rec = x => memo(x)
  return rec
}

export const any = I.id

export const and = R.pipe

export const or = (...ps) => x => {
  const es = [],
    n = ps.length
  for (let i = 0; i < n; ++i) {
    try {
      return ps[i](x)
    } catch (e) {
      es.push([ps[i], e])
    }
  }
  throw Error(`or(${ps}): ${x}`)
}

export const fromPredicate = p => x => {
  if (p(x)) return x
  throw Error(`fromPredicate(${p}): ${x}`)
}

const type = t => fromPredicate(x => typeof x === t)
export const instanceOf = c => fromPredicate(x => x instanceof c)

const isFreezable = x => I.isArray(x) || I.isObject(x)
const isFrozen = x => !isFreezable(x) || Object.isFrozen(x)
const isDeepFrozen = x =>
  !isFreezable(x) ||
  (Object.isFrozen(x) &&
    !Object.getOwnPropertyNames(x).find(x => !isDeepFrozen(x)))

export const frozen = fromPredicate(isFrozen)

export const deepFrozen = fromPredicate(isDeepFrozen)

export const deepFreeze = x =>
  isFrozen(x)
    ? x
    : (Object.getOwnPropertyNames(x).forEach(k => deepFreeze(x[k])),
      Object.freeze(x))

export const integer = fromPredicate(Number.isInteger)
export const nonNegative = and(integer, fromPredicate(x => 0 <= x))

export const boolean = type('boolean')
export const number = type('number')
export const string = type('string')
export const undef = fromPredicate(x => x === undefined)
export const def = fromPredicate(x => x !== undefined)

export const array = ty => and(instanceOf(Array), R.map(ty))

export const arity = n => fromPredicate(x => x.length === n)

export const props = R.map

export const object = template => object => {
  const result = {}
  if (!I.isObject(object)) throw Error(`Expected object, got ${object}`)
  if (!I.hasKeysOfU(template, object))
    throw Error(`Expected object with keys ${I.keys(template)}, got ${object}`)
  for (const k in template) result[k] = template[k](object[k])
  return result
}

export function fn(argTys, resultTy) {
  if (!(argTys instanceof Array))
    throw Error(`fn arg types must be an array, given ${argTys}`)
  return fn => {
    if (!I.isFunction(fn)) throw Error(`Expected function, got ${fn}`)
    if (argTys.length < fn.length)
      throw Error(`Expected arity ${argTys.length}, but got ${fn.length}`)
    return I.arityN(argTys.length, (...argIns) => {
      const n = argIns.length,
        args = Array(n)
      for (let i = 0; i < n; ++i) args[i] = argTys[i](argIns[i])
      return resultTy(fn.apply(this, args))
    })
  }
}

export const fnVarN = (minArity, argsTy, resultTy) => fn => {
  if (!I.isFunction(fn)) throw Error(`Expected function, got ${fn}`)
  return R.curryN(minArity, (...argIns) => {
    const n = argIns.length,
      args = Array(n)
    for (let i = 0; i < n; ++i) args[i] = argsTy(argIns[i])
    return resultTy(fn.apply(this, args))
  })
}
<commit_msg>Show the unexpected keys<commit_after>import * as I from 'infestines'
import * as R from 'ramda'

export function lazy(ty2ty) {
  let memo = x => {
    memo = ty2ty(rec)
    return memo(x)
  }
  const rec = x => memo(x)
  return rec
}

export const any = I.id

export const and = R.pipe

export const or = (...ps) => x => {
  const es = [],
    n = ps.length
  for (let i = 0; i < n; ++i) {
    try {
      return ps[i](x)
    } catch (e) {
      es.push([ps[i], e])
    }
  }
  throw Error(`or(${ps}): ${x}`)
}

export const fromPredicate = p => x => {
  if (p(x)) return x
  throw Error(`fromPredicate(${p}): ${x}`)
}

const type = t => fromPredicate(x => typeof x === t)
export const instanceOf = c => fromPredicate(x => x instanceof c)

const isFreezable = x => I.isArray(x) || I.isObject(x)
const isFrozen = x => !isFreezable(x) || Object.isFrozen(x)
const isDeepFrozen = x =>
  !isFreezable(x) ||
  (Object.isFrozen(x) &&
    !Object.getOwnPropertyNames(x).find(x => !isDeepFrozen(x)))

export const frozen = fromPredicate(isFrozen)

export const deepFrozen = fromPredicate(isDeepFrozen)

export const deepFreeze = x =>
  isFrozen(x)
    ? x
    : (Object.getOwnPropertyNames(x).forEach(k => deepFreeze(x[k])),
      Object.freeze(x))

export const integer = fromPredicate(Number.isInteger)
export const nonNegative = and(integer, fromPredicate(x => 0 <= x))

export const boolean = type('boolean')
export const number = type('number')
export const string = type('string')
export const undef = fromPredicate(x => x === undefined)
export const def = fromPredicate(x => x !== undefined)

export const array = ty => and(instanceOf(Array), R.map(ty))

export const arity = n => fromPredicate(x => x.length === n)

export const props = R.map

export const object = template => object => {
  const result = {}
  if (!I.isObject(object)) throw Error(`Expected object, got ${object}`)
  if (!I.hasKeysOfU(template, object))
    throw Error(
      `Expected object with keys ${I.keys(template)}, got ${I.keys(object)}`
    )
  for (const k in template) result[k] = template[k](object[k])
  return result
}

export function fn(argTys, resultTy) {
  if (!(argTys instanceof Array))
    throw Error(`fn arg types must be an array, given ${argTys}`)
  return fn => {
    if (!I.isFunction(fn)) throw Error(`Expected function, got ${fn}`)
    if (argTys.length < fn.length)
      throw Error(`Expected arity ${argTys.length}, but got ${fn.length}`)
    return I.arityN(argTys.length, (...argIns) => {
      const n = argIns.length,
        args = Array(n)
      for (let i = 0; i < n; ++i) args[i] = argTys[i](argIns[i])
      return resultTy(fn.apply(this, args))
    })
  }
}

export const fnVarN = (minArity, argsTy, resultTy) => fn => {
  if (!I.isFunction(fn)) throw Error(`Expected function, got ${fn}`)
  return R.curryN(minArity, (...argIns) => {
    const n = argIns.length,
      args = Array(n)
    for (let i = 0; i < n; ++i) args[i] = argsTy(argIns[i])
    return resultTy(fn.apply(this, args))
  })
}
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Shape Security, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as assert from "assert";

import * as Shift from "../"

suite("unit", () => {
  suite("toJSON", () => {
    test("includes `type` member", () => {
      let node = new Shift.LiteralNumericExpression(0);
      assert.equal(node.type, JSON.parse(JSON.stringify(node)).type);
    });
  });

  // enough nonces to fill up the longest constructor parameter list
  const NONCES = Array.apply(null, Array(Object.keys(Shift).reduce((memo, t) => Math.max(memo, Shift[t].length), 0))).map(() => ({}));

  function testConstructor(t, members) {
    test(t, () => {
      assert(Shift[t]);
      let node = new Shift[t](...NONCES);
      assert(node instanceof Shift[t]);
      assert.equal(typeof node.type, "string");
      members.forEach((member, index) => {
        assert.equal(node[member], NONCES[index], `${t}: ${member}`);
      });
    });
  }

  const SPEC = {
    ArrayExpression: ["elements"],
    AssignmentExpression: ["operator", "binding", "expression"],
    BinaryExpression: ["operator", "left", "right"],
    Block: ["statements"],
    BlockStatement: ["block"],
    BreakStatement: ["label"],
    CallExpression: ["callee", "arguments"],
    CatchClause: ["binding", "body"],
    ComputedMemberExpression: ["object", "expression"],
    ConditionalExpression: ["test", "consequent", "alternate"],
    ContinueStatement: ["label"],
    DataProperty: ["name", "expression"],
    DebuggerStatement: [],
    DoWhileStatement: ["body", "test"],
    EmptyStatement: [],
    ExpressionStatement: ["expression"],
    ForInStatement: ["left", "right", "body"],
    ForStatement: ["init", "test", "update", "body"],
    FunctionBody: ["directives", "statements"],
    FunctionDeclaration: ["name", "parameters", "body"],
    FunctionExpression: ["name", "parameters", "body"],
    Getter: ["name", "body"],
    Identifier: ["name"],
    IdentifierExpression: ["identifier"],
    IfStatement: ["test", "consequent", "alternate"],
    LabeledStatement: ["label", "body"],
    LiteralBooleanExpression: ["value"],
    LiteralInfinityExpression: [],
    LiteralNullExpression: [],
    LiteralNumericExpression: ["value"],
    LiteralRegExpExpression: ["value"],
    LiteralStringExpression: ["value"],
    NewExpression: ["callee", "arguments"],
    ObjectExpression: ["properties"],
    PostfixExpression: ["operand", "operator"],
    PrefixExpression: ["operator", "operand"],
    PropertyName: ["kind", "value"],
    ReturnStatement: ["expression"],
    Script: ["body"],
    Setter: ["name", "parameter", "body"],
    StaticMemberExpression: ["object", "property"],
    SwitchCase: ["test", "consequent"],
    SwitchDefault: ["consequent"],
    SwitchStatement: ["discriminant", "cases"],
    SwitchStatementWithDefault: ["discriminant", "preDefaultCases", "defaultCase", "postDefaultCases"],
    ThisExpression: [],
    ThrowStatement: ["expression"],
    TryCatchStatement: ["body", "catchClause"],
    TryFinallyStatement: ["body", "catchClause", "finalizer"],
    UnknownDirective: ["value"],
    UseStrictDirective: [],
    VariableDeclaration: ["kind", "declarators"],
    VariableDeclarationStatement: ["declaration"],
    VariableDeclarator: ["binding", "init"],
    WhileStatement: ["test", "body"],
    WithStatement: ["object", "body"],
  };

  suite("constructors", () => {
    Object.keys(SPEC).forEach((t) => {
      testConstructor(t, SPEC[t]);
    });
  });

  test("VariableDeclaration declarators must be non-empty", () => {
    assert.throws(() => new Shift.VariableDeclaration("var", []));
  });
});
<commit_msg>ensure all constructors are tested<commit_after>/**
 * Copyright 2014 Shape Security, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as assert from "assert";

import * as Shift from "../"

suite("unit", () => {
  suite("toJSON", () => {
    test("includes `type` member", () => {
      let node = new Shift.LiteralNumericExpression(0);
      assert.equal(node.type, JSON.parse(JSON.stringify(node)).type);
    });
  });

  // enough nonces to fill up the longest constructor parameter list
  const NONCES = Array.apply(null, Array(Object.keys(Shift).reduce((memo, t) => Math.max(memo, Shift[t].length), 0))).map(() => ({}));

  function testConstructor(t, members) {
    test(t, () => {
      assert(Shift[t]);
      let node = new Shift[t](...NONCES);
      assert(node instanceof Shift[t]);
      assert.equal(typeof node.type, "string");
      members.forEach((member, index) => {
        assert.equal(node[member], NONCES[index], `${t}: ${member}`);
      });
    });
  }

  const SPEC = {
    ArrayExpression: ["elements"],
    AssignmentExpression: ["operator", "binding", "expression"],
    BinaryExpression: ["operator", "left", "right"],
    Block: ["statements"],
    BlockStatement: ["block"],
    BreakStatement: ["label"],
    CallExpression: ["callee", "arguments"],
    CatchClause: ["binding", "body"],
    ComputedMemberExpression: ["object", "expression"],
    ConditionalExpression: ["test", "consequent", "alternate"],
    ContinueStatement: ["label"],
    DataProperty: ["name", "expression"],
    DebuggerStatement: [],
    DoWhileStatement: ["body", "test"],
    EmptyStatement: [],
    ExpressionStatement: ["expression"],
    ForInStatement: ["left", "right", "body"],
    ForStatement: ["init", "test", "update", "body"],
    FunctionBody: ["directives", "statements"],
    FunctionDeclaration: ["name", "parameters", "body"],
    FunctionExpression: ["name", "parameters", "body"],
    Getter: ["name", "body"],
    Identifier: ["name"],
    IdentifierExpression: ["identifier"],
    IfStatement: ["test", "consequent", "alternate"],
    LabeledStatement: ["label", "body"],
    LiteralBooleanExpression: ["value"],
    LiteralInfinityExpression: [],
    LiteralNullExpression: [],
    LiteralNumericExpression: ["value"],
    LiteralRegExpExpression: ["value"],
    LiteralStringExpression: ["value"],
    NewExpression: ["callee", "arguments"],
    ObjectExpression: ["properties"],
    PostfixExpression: ["operand", "operator"],
    PrefixExpression: ["operator", "operand"],
    PropertyName: ["kind", "value"],
    ReturnStatement: ["expression"],
    Script: ["body"],
    Setter: ["name", "parameter", "body"],
    StaticMemberExpression: ["object", "property"],
    SwitchCase: ["test", "consequent"],
    SwitchDefault: ["consequent"],
    SwitchStatement: ["discriminant", "cases"],
    SwitchStatementWithDefault: ["discriminant", "preDefaultCases", "defaultCase", "postDefaultCases"],
    ThisExpression: [],
    ThrowStatement: ["expression"],
    TryCatchStatement: ["body", "catchClause"],
    TryFinallyStatement: ["body", "catchClause", "finalizer"],
    UnknownDirective: ["value"],
    UseStrictDirective: [],
    VariableDeclaration: ["kind", "declarators"],
    VariableDeclarationStatement: ["declaration"],
    VariableDeclarator: ["binding", "init"],
    WhileStatement: ["test", "body"],
    WithStatement: ["object", "body"],
  };

  suite("constructors", () => {
    test("all constructors are tested", () => {
      let shiftCtors = Object.keys(Shift).sort();
      let specCtors = Object.keys(SPEC).sort();
      shiftCtors.forEach((shiftCtor, i) => {
        assert.equal(shiftCtor, specCtors[i]);
      })
      assert.equal(shiftCtors.length, specCtors.length);
    });

    Object.keys(SPEC).forEach((t) => {
      testConstructor(t, SPEC[t]);
    });
  });

  test("VariableDeclaration declarators must be non-empty", () => {
    assert.throws(() => new Shift.VariableDeclaration("var", []));
  });
});
<|endoftext|>


<commit_before>import test from 'ava'
import Onionoo from '../'

test('Onionoo is a function', t => {
  t.is(typeof Onionoo, 'function')
})

test('Onionoo cannot be invoked without \'new\'', t => {
  t.throws(() => Onionoo())
  t.notThrows(() => new Onionoo())
})

test('Onionoo instance is an object', t => {
  const onionoo = new Onionoo()

  t.is(typeof onionoo, 'object')
})

test('Onionoo instance contains expected endpoints', t => {
  const onionoo = new Onionoo()
  const expectedEndpoints = [
    'summary',
    'details',
    'bandwidth',
    'weights',
    'clients',
    'uptime'
  ]

  t.deepEqual(Object.keys(onionoo), expectedEndpoints)
})
<commit_msg>Test passing in custom endpoint array<commit_after>import test from 'ava'
import Onionoo from '../'

test('Onionoo is a function', t => {
  t.is(typeof Onionoo, 'function')
})

test('Onionoo cannot be invoked without \'new\'', t => {
  t.throws(() => Onionoo())
  t.notThrows(() => new Onionoo())
})

test('Onionoo instance is an object', t => {
  const onionoo = new Onionoo()

  t.is(typeof onionoo, 'object')
})

test('Onionoo instance contains expected endpoints', t => {
  const onionoo = new Onionoo()
  const expectedEndpoints = [
    'summary',
    'details',
    'bandwidth',
    'weights',
    'clients',
    'uptime'
  ]

  t.deepEqual(Object.keys(onionoo), expectedEndpoints)
})

test('Can pass in custom endpoint array', t => {
  const endpoints = [
    'foo',
    'bar'
  ]
  const onionoo = new Onionoo({ endpoints })

  t.deepEqual(Object.keys(onionoo), endpoints)
})
<|endoftext|>


<commit_before>
/*
 * usage:

describe('whatever', run(function () {

}, function () {
  return 'registerElement'
}, 'does not support whatevs'))

 */
function ifEnvSupports(test, block) {
  return function () {
    var message = (test.message || test.name || test);
    if (typeof test === 'string' ? !!window[test] : test()) {
      block();
    } else {
      it('should skip the test if the API does not exist', function () {
        console.log('WARNING: skipping ' + message + ' tests (missing this API)');
      });
    }
  };
};

function assertInChildOf(parentZone) {
  var zone = window.zone.parent;
  while (zone) {
    if (zone === parentZone) return;
    zone = zone.parent;
  }

  throw new Error('The current zone [' + window.zone.$id +
                  '] is not a child of the given zone [' + parentZone.$id + '] !');
}

// useful for testing mocks
window.__setTimeout = window.setTimeout;
<commit_msg>test(assertInChildOf): use a custom matcher for easier debugging failures<commit_after>
/*
 * usage:

describe('whatever', run(function () {

}, function () {
  return 'registerElement'
}, 'does not support whatevs'))

 */
function ifEnvSupports(test, block) {
  return function () {
    var message = (test.message || test.name || test);
    if (typeof test === 'string' ? !!window[test] : test()) {
      block();
    } else {
      it('should skip the test if the API does not exist', function () {
        console.log('WARNING: skipping ' + message + ' tests (missing this API)');
      });
    }
  };
};

function assertInChildOf(parentZone) {
  expect(window.zone).toBeChildOf(parentZone);
}

var customMatchers = {
  // Assert that a zone is a child of an other zone
  // usage: `expect(childZone).toBeChildOf(parentZone);`
  toBeChildOf: function() {
    return {
      compare: function(childZone, parentZone) {
        var zone = childZone.parent;
        while (zone) {
          if (zone === parentZone) {
            return {
              pass: true,
              message: 'The zone [' + childZone.$id + '] is a child of the zone [' + parentZone.$id + ']'
            };
          }
          zone = zone.parent;
        }

        return {
          pass: false,
          message: 'The zone [' + childZone.$id + '] is not a child of the zone [' + parentZone.$id + ']'
        };
      }
    }
  }
}

beforeEach(function() {
  jasmine.addMatchers(customMatchers);
});

// useful for testing mocks
window.__setTimeout = window.setTimeout;
<|endoftext|>