<commit_before>;((rc) => {
  'use strict';
  var tagContent = 'router2-content';

  var div = document.createElement('div');
  div.innerHTML = `
  <${tagContent} id="case6-1" hash="case(\\d+)">
    Case 6 via RegExp
  </${tagContent}>
  `;

  var async1 = async_test('Case 6: hash changed to content[hash="case(\d+)"]');

  async1.next = async1.step_func(_ => {
    var check_hash = async1.step_func((e) => {
      window.removeEventListener('hashchange', check_hash);
      var content1 = document.querySelector('#case6-1');
      assert_false(content1.hidden);
      assert_equals(content1.getAttribute('route-param1'), '6');

      document.body.removeChild(div);
      async1.done();
      rc.next();

    });
    window.addEventListener('hashchange', check_hash);
    window.location.hash = "case6";
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  })

})(window.routeCases);
<commit_msg>Test case 6 - the order of contents at the DOM-tree<commit_after>;((rc) => {
  'use strict';
  var tagContent = 'router2-content';

  var div = document.createElement('div');
  div.innerHTML = `
  <${tagContent} id="case6-2" hash="case62">
    Case 6. It's suposed that this will come before (\\d+)
  </${tagContent}>
  <${tagContent} id="case6-1" hash="case(\\d+)">
    Case 6 via RegExp
  </${tagContent}>
  `;

  var async1 = async_test('Case 6: hash changed to content[hash="case(\d+)"]');
  var async2 = async_test('Case 6; hash changed to content[hash="case62"]');

  async1.next = async1.step_func(_ => {
    var check_hash = async1.step_func((e) => {
      window.removeEventListener('hashchange', check_hash);
      var content1 = document.querySelector('#case6-1');
      assert_false(content1.hidden);
      assert_equals(content1.getAttribute('route-param1'), '6');

      async1.done();
      async2.next();
    });
    window.addEventListener('hashchange', check_hash);
    window.location.hash = "case6";
  });

  async2.next = async2.step_func(_ => {
    var check_hash = async2.step_func((e) => {
      window.removeEventListener('hashchange', check_hash);
      var content1 = document.querySelector('#case6-2');
      assert_false(content1.hidden);

      document.body.removeChild(div);
      async2.done();
      rc.next();

    });
    window.addEventListener('hashchange', check_hash);
    window.location.hash = "case62";
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  })

})(window.routeCases);
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var m = require('mithril');
var a = require('../src/mithril-armor');

describe('Composition', function() {

  describe('Constructing non-void elements', function() {
    it("a(tag) returns extendable function", function() {
      expect(a('div')).to.be.a('function');
    });

    it("a(tag, attrs) returns extendable function", function() {
      expect(a('div', {class: 'test'})).to.be.a('function');
    });

    it("a(tag, attrs, children) returns mithril object", function() {

      var aObj = a('div', {class: 'test'}, []);
      var mObj = m('div', {class: 'test'}, []);
      expect(aObj).to.eql(mObj);
    });

    it("a(tag)(attrs)(children) returns mithril object", function() {
      var aObj = a('div')({class: 'test'})('content');
      var mObj = m('div', {class: 'test'}, 'content');
      expect(aObj).to.eql(mObj);
    });

    it("a(className) returns extendable function with div as tag", function(){
      var aObj = a('.container');
      var fObj = aObj({}, []);

      expect(aObj).to.be.a('function');
      expect(fObj.tag).to.equal('div');
      expect(fObj.attrs.className).to.equal('container');
    })

    it("a(className) return fn can handle array.map for children", function() {
      var arr = [1,2,3,4,5];
      var button = a('button');
      var container = a('.container');
      var aObj = container(arr.map(function(element){
        return button(element);
      }));

      var mObj = m('.container', arr.map(function(element) {
        return m('button', element);
      }))

      expect(aObj).to.eql(mObj);

    })

    describe('extending non-void armor elements', function() {
      var container = a('div'),
          button = a('button');

      it('assuming var container = a("div")', function() { return true; })

      it('container("content") should be a div with child "content"', function(){
        var aObj = container('content');
        var mObj = m('div', 'content');
        expect(aObj).to.eql(mObj);
      })

      it('container([]) should be an empty div mithril object', function(){
        var aObj = container([]);
        var mObj = m('div', []);
        expect(aObj).to.eql(mObj);
      })

      it('container({})("content") should be a div mithril object with child content', function(){
        var aObj = container({})("content");
        var mObj = m('div', "content");
        expect(aObj).to.eql(mObj);
      })

      it('assuming var button = a("button")', function() { return true; })

      it('button("content") should be a button with text "content"', function(){
        var aObj = button('content');
        var mObj = m('button', 'content');
        expect(aObj).to.eql(mObj);
      })

      it('button({class: "danger"}) should be an extendable function', function(){
        var aObj = button({class: "danger"});
        var mObj = m('button', 'content');
        expect(aObj).to.be.a('function');
      })

      it('button({class: "danger"})("content") should be a mithril object with child content and class danger', function(){
        var aObj = button({class: "danger"})("content");
        var mObj = m('button', {class: "danger"}, 'content');
        expect(aObj).to.eql(mObj);
      })

    });

  })

  describe('Constructing void elements', function() {

    it("a(tag) returns extendable function", function() {
      expect(a('input')).to.be.a('function');
    });

    it("a(tag, attrs) returns mithril object", function() {

      var aObj = a('input', {type: 'text'});
      var mObj = m('input', {type: 'text'});
      expect(aObj).to.eql(mObj);
    });

    it("a(tag)(attrs) returns mithril object", function() {
      var aObj = a('input')({type: 'text'});
      var mObj = m('input', {type: 'text'});
      expect(aObj).to.eql(mObj);
    })

    describe('extending void armor elements', function() {

      var input = a('input');
      var image = a('img');

      it('assuming var input = a("input")', function(){return true});

      it('input({type: text}) should yield mithril text input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      });

      it('input({type: text}) should yield mithril checkbox input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      });

      it('input({type: text}) should yield mithril submit input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      })

      it('assuming var image = a("image")', function(){return true});

      it('image({src: "fakepath"}) should yield an img tag with src "fakepath"', function() {
        var aObj = image({src: 'fakepath'});
        var mObj = m('img', {src: 'fakepath'});
        expect(aObj).to.eql(mObj);
      })

      it('image({}) should yield a blank img tag ', function() {
        var aObj = image({});
        var mObj = m('img');
        expect(aObj).to.eql(mObj);
      })

    });

  })

});
<commit_msg>code style changes for test<commit_after>var expect = require('chai').expect;
var m = require('mithril');
var a = require('../src/mithril-armor');

describe('Composition', function() {

  describe('Constructing non-void elements', function() {
    it("a(tag) returns extendable function", function() {
      expect(a('div')).to.be.a('function');
    });

    it("a(tag, attrs) returns extendable function", function() {
      expect(a('div', {class: 'test'})).to.be.a('function');
    });

    it("a(tag, attrs, children) returns mithril object", function() {

      var aObj = a('div', {class: 'test'}, []);
      var mObj = m('div', {class: 'test'}, []);
      expect(aObj).to.eql(mObj);
    });

    it("a(tag)(attrs)(children) returns mithril object", function() {
      var aObj = a('div')({class: 'test'})('content');
      var mObj = m('div', {class: 'test'}, 'content');
      expect(aObj).to.eql(mObj);
    });

    it("a(className) returns extendable function with div as tag", function(){
      var aObj = a('.container');
      var fObj = aObj({}, []);

      expect(aObj).to.be.a('function');
      expect(fObj.tag).to.equal('div');
      expect(fObj.attrs.className).to.equal('container');
    })

    it("a(className) return fn can handle array.map for children", function() {
      var arr       = [1,2,3,4,5],
          button    = a('button'),
          container = a('.container');

      var aObj = container(arr.map(function(element){
        return button(element);
      }));

      var mObj = m('.container', arr.map(function(element) {
        return m('button', element);
      }))

      expect(aObj).to.eql(mObj);
    })

    describe('extending non-void armor elements', function() {
      var container = a('div'),
          button = a('button');

      it('assuming var container = a("div")', function() { return true; })

      it('container("content") should be a div with child "content"', function(){
        var aObj = container('content');
        var mObj = m('div', 'content');
        expect(aObj).to.eql(mObj);
      })

      it('container([]) should be an empty div mithril object', function(){
        var aObj = container([]);
        var mObj = m('div', []);
        expect(aObj).to.eql(mObj);
      })

      it('container({})("content") should be a div mithril object with child content', function(){
        var aObj = container({})("content");
        var mObj = m('div', "content");
        expect(aObj).to.eql(mObj);
      })

      it('assuming var button = a("button")', function() { return true; })

      it('button("content") should be a button with text "content"', function(){
        var aObj = button('content');
        var mObj = m('button', 'content');
        expect(aObj).to.eql(mObj);
      })

      it('button({class: "danger"}) should be an extendable function', function(){
        var aObj = button({class: "danger"});
        var mObj = m('button', 'content');
        expect(aObj).to.be.a('function');
      })

      it('button({class: "danger"})("content") should be a mithril object with child content and class danger', function(){
        var aObj = button({class: "danger"})("content");
        var mObj = m('button', {class: "danger"}, 'content');
        expect(aObj).to.eql(mObj);
      })

    });

  })

  describe('Constructing void elements', function() {

    it("a(tag) returns extendable function", function() {
      expect(a('input')).to.be.a('function');
    });

    it("a(tag, attrs) returns mithril object", function() {

      var aObj = a('input', {type: 'text'});
      var mObj = m('input', {type: 'text'});
      expect(aObj).to.eql(mObj);
    });

    it("a(tag)(attrs) returns mithril object", function() {
      var aObj = a('input')({type: 'text'});
      var mObj = m('input', {type: 'text'});
      expect(aObj).to.eql(mObj);
    })

    describe('extending void armor elements', function() {

      var input = a('input');
      var image = a('img');

      it('assuming var input = a("input")', function(){return true});

      it('input({type: text}) should yield mithril text input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      });

      it('input({type: text}) should yield mithril checkbox input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      });

      it('input({type: text}) should yield mithril submit input', function() {
        var aObj = input({type: 'text'});
        var mObj = m('input', {type: 'text'});
        expect(aObj).to.eql(mObj);
      })

      it('assuming var image = a("image")', function(){return true});

      it('image({src: "fakepath"}) should yield an img tag with src "fakepath"', function() {
        var aObj = image({src: 'fakepath'});
        var mObj = m('img', {src: 'fakepath'});
        expect(aObj).to.eql(mObj);
      })

      it('image({}) should yield a blank img tag ', function() {
        var aObj = image({});
        var mObj = m('img');
        expect(aObj).to.eql(mObj);
      })

    });

  })

});
<|endoftext|>


<commit_before>define(["Test", "Tone/core/Buffer"], function (Test, Buffer) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	var testFile = "./audio/sine.wav";

	describe("Buffer", function(){
		it ("can be created and disposed", function(){
			var buff = new Buffer(testFile);
			buff.dispose();
			Test.wasDisposed(buff);
		});

		it("loads a file from a url string", function(done){
			var buffer = new Buffer(testFile, function(buff){
				expect(buff).to.be.instanceof(Buffer);
				buffer.dispose();
				done();
			});
		});

		it("has a duration", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				buffer.dispose();
				done();
			});
		});

		it("can get the number of channels", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.numberOfChannels).to.be.equal(1);
				buffer.dispose();
				done();
			});
		});

		it("can get the length of the buffer", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.length).to.be.a.number;
				expect(buffer.length).to.be.above(130000);
				buffer.dispose();
				done();
			});
		});

		it("the static on('load') method is invoked", function(done){
			var buffer = new Buffer(testFile);
			Buffer.on("load", function(){
				buffer.dispose();
				Buffer.off("load");
				done();
			});
		});

		it("can be constructed with an options object", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"reverse" : true,
				"onload" : function(){
					buffer.dispose();
					done();
				}
			});
		});

		it("takes an AudioBuffer in the constructor method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(buffer.get());
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes a Tone.Buffer in the constructor method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(buffer);
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes Tone.Buffer in the set method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(testFile);
					testOne.set(buffer);
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes AudioBuffer in the set method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(testFile);
					testOne.set(buffer.get());
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("the static on('progress') method is invoked", function(done){
			var buffer = new Buffer(testFile);
			Buffer.on("progress", function(percent){
				expect(percent).to.be.a.number;
				Buffer.off("progress");
				buffer.dispose();
				done();
			});
		});

		it("can reverse a buffer", function(done){
			var buffer = new Buffer(testFile, function(){
				var buffArray = buffer.get();
				var lastSample = buffArray[buffArray.length - 1];
				buffer.reverse = true;
				expect(buffer.get()[0]).to.equal(lastSample);
				buffer.dispose();
				done();
			});
		});

		it("can convert from an array", function(){
			var buffer = new Buffer();
			var arr = new Float32Array(0.5 * buffer.context.sampleRate);
			arr[0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.duration).to.equal(0.5);
			expect(buffer.numberOfChannels).to.equal(1);
			//test the first sample of the first channel to see if it's the same
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can convert from a multidimentional array", function(){
			var buffer = new Buffer();
			var arr = [new Float32Array(0.5 * buffer.context.sampleRate), new Float32Array(0.5 * buffer.context.sampleRate)];
			arr[0][0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.duration).to.equal(0.5);
			expect(buffer.numberOfChannels).to.equal(2);
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can convert to and from an array", function(){
			var buffer = new Buffer();
			var arr = [new Float32Array(0.5 * buffer.context.sampleRate), new Float32Array(0.5 * buffer.context.sampleRate)];
			arr[0][0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			expect(buffer.toArray()[0][0]).to.equal(0.5);
			//with a selected channel
			expect(buffer.toArray(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can slice a portion of the array", function(done){
			var buffer = new Buffer(testFile, function(){
				//original duration
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				var sliced1 = buffer.slice(0, 1);
				//does not modify the original
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				expect(sliced1.duration).to.be.closeTo(1, 0.01);
				var sliced2 = sliced1.slice(0.5);
				expect(sliced2.duration).to.be.closeTo(0.5, 0.01);

				buffer.dispose();
				sliced1.dispose();
				sliced2.dispose();
				done();
			});
		});
	});
});<commit_msg>testing error callbacks<commit_after>define(["Test", "Tone/core/Buffer"], function (Test, Buffer) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	var testFile = "./audio/sine.wav";

	describe("Buffer", function(){
		it ("can be created and disposed", function(){
			var buff = new Buffer(testFile);
			buff.dispose();
			Test.wasDisposed(buff);
		});

		it("loads a file from a url string", function(done){
			var buffer = new Buffer(testFile, function(buff){
				expect(buff).to.be.instanceof(Buffer);
				buffer.dispose();
				done();
			});
		});

		it("has a duration", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				buffer.dispose();
				done();
			});
		});

		it("can get the number of channels", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.numberOfChannels).to.be.equal(1);
				buffer.dispose();
				done();
			});
		});

		it("can get the length of the buffer", function(done){
			var buffer = new Buffer(testFile, function(){
				expect(buffer.length).to.be.a.number;
				expect(buffer.length).to.be.above(130000);
				buffer.dispose();
				done();
			});
		});

		it("invokes the error callback if there is a problem with the file", function(done){
			var buffer = new Buffer("nosuchfile.wav", function(){
				throw new Error("shouldn't invoke this function");
			}, function(e){
				buffer.dispose();
				done();
			});
		});

		it("invokes the error callback on static .load method", function(done){
			Buffer.load("nosuchfile.wav", function(){
				throw new Error("shouldn't invoke this function");
			}, function(){
				done();
			});
		});

		it("the static on('load') method is invoked", function(done){
			var buffer = new Buffer(testFile);
			Buffer.on("load", function(){
				buffer.dispose();
				Buffer.off("load");
				done();
			});
		});

		it("can be constructed with an options object", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"reverse" : true,
				"onload" : function(){
					buffer.dispose();
					done();
				}
			});
		});

		it("takes an AudioBuffer in the constructor method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(buffer.get());
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes a Tone.Buffer in the constructor method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(buffer);
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes Tone.Buffer in the set method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(testFile);
					testOne.set(buffer);
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("takes AudioBuffer in the set method", function(done){
			var buffer = new Buffer({
				"url" : testFile,
				"onload" : function(){
					var testOne = new Buffer(testFile);
					testOne.set(buffer.get());
					expect(testOne.get()).to.equal(buffer.get());
					testOne.dispose();
					buffer.dispose();
					done();
				}
			});
		});

		it("the static on('progress') method is invoked", function(done){
			var buffer = new Buffer(testFile);
			Buffer.on("progress", function(percent){
				expect(percent).to.be.a.number;
				Buffer.off("progress");
				buffer.dispose();
				done();
			});
		});

		it("can reverse a buffer", function(done){
			var buffer = new Buffer(testFile, function(){
				var buffArray = buffer.get();
				var lastSample = buffArray[buffArray.length - 1];
				buffer.reverse = true;
				expect(buffer.get()[0]).to.equal(lastSample);
				buffer.dispose();
				done();
			});
		});

		it("can convert from an array", function(){
			var buffer = new Buffer();
			var arr = new Float32Array(0.5 * buffer.context.sampleRate);
			arr[0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.duration).to.equal(0.5);
			expect(buffer.numberOfChannels).to.equal(1);
			//test the first sample of the first channel to see if it's the same
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can convert from a multidimentional array", function(){
			var buffer = new Buffer();
			var arr = [new Float32Array(0.5 * buffer.context.sampleRate), new Float32Array(0.5 * buffer.context.sampleRate)];
			arr[0][0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.duration).to.equal(0.5);
			expect(buffer.numberOfChannels).to.equal(2);
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can convert to and from an array", function(){
			var buffer = new Buffer();
			var arr = [new Float32Array(0.5 * buffer.context.sampleRate), new Float32Array(0.5 * buffer.context.sampleRate)];
			arr[0][0] = 0.5;
			buffer.fromArray(arr);
			expect(buffer.get().getChannelData(0)[0]).to.equal(0.5);
			expect(buffer.toArray()[0][0]).to.equal(0.5);
			//with a selected channel
			expect(buffer.toArray(0)[0]).to.equal(0.5);
			buffer.dispose();
		});

		it("can slice a portion of the array", function(done){
			var buffer = new Buffer(testFile, function(){
				//original duration
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				var sliced1 = buffer.slice(0, 1);
				//does not modify the original
				expect(buffer.duration).to.be.closeTo(3, 0.01);
				expect(sliced1.duration).to.be.closeTo(1, 0.01);
				var sliced2 = sliced1.slice(0.5);
				expect(sliced2.duration).to.be.closeTo(0.5, 0.01);

				buffer.dispose();
				sliced1.dispose();
				sliced2.dispose();
				done();
			});
		});
	});
});<|endoftext|>


<commit_before>module("vie.js - Schema.org Ontology");

test("Initialization", function() {
    var z = new VIE();

    ok(z.loadSchema);
    equal(typeof z.loadSchema, "function");

    if (navigator.userAgent === 'Zombie') {
        // ignore this test on the headless browser
        return;
    }

    stop();
    z.loadSchema("http://schema.rdfs.org/all.json", {
        baseNS : "http://schema.org/",
        success : function () {
            ok(true, "successfully loaded types!");
            equal(z.types.list().length, 299);

            //just pick some and test them:
            ok (z.types.get("Person"));
            ok (z.types.get("Corporation"));
            ok (z.types.get("Corporation").isof("Thing"));
            ok (z.types.get("Organization").subsumes("Corporation"));
            ok (z.types.get("BowlingAlley").isof("Thing"));

            ok (z.types.get("Person").id.indexOf("<http://schema.org/") === 0);

            var hospital = z.types.get("Hospital");
            ok (hospital);
            equal( hospital.attributes.list().length, 27);

            equal(hospital.attributes.get('description').range.length, 1);
            equal(hospital.attributes.get('description').range[0], "Text");
            equal(hospital.attributes.get('geo').range.length, 2);
            equal(hospital.attributes.get('geo').range[0], "GeoCoordinates");
            equal(hospital.attributes.get('location').range.length, 2);
            equal(hospital.attributes.get('location').range[0], "PostalAddress");
            equal(hospital.attributes.get('location').range[1], "Place");

            raises(function () {
                hospital.attributes.remove("description");
            });

            z.types.get("Organization").attributes.remove("founders");

            equal( hospital.attributes.list().length, 26);
            start();
        },
        error : function (msg) {
            ok(false, msg);
            start();
        }
    });

});
<commit_msg>fixed schema.org import test<commit_after>module("vie.js - Schema.org Ontology");

test("Initialization", function() {
    var z = new VIE();

    ok(z.loadSchema);
    equal(typeof z.loadSchema, "function");

    if (navigator.userAgent === 'Zombie') {
        // ignore this test on the headless browser
        return;
    }

    stop();
    z.loadSchema("http://schema.rdfs.org/all.json", {
        baseNS : "http://schema.org/",
        success : function () {
            ok(true, "successfully loaded types!");
            equal(z.types.list().length, 303);

            //just pick some and test them:
            ok (z.types.get("Person"));
            ok (z.types.get("Corporation"));
            ok (z.types.get("Corporation").isof("Thing"));
            ok (z.types.get("Organization").subsumes("Corporation"));
            ok (z.types.get("BowlingAlley").isof("Thing"));

            ok (z.types.get("Person").id.indexOf("<http://schema.org/") === 0);

            var hospital = z.types.get("Hospital");
            ok (hospital);
            var hospAttrs = hospital.attributes.list();
            equal( hospAttrs.length, 35);

            equal(hospital.attributes.get('description').range.length, 1);
            equal(hospital.attributes.get('description').range[0], "Text");
            equal(hospital.attributes.get('geo').range.length, 2);
            equal(hospital.attributes.get('geo').range[0], "GeoCoordinates");
            equal(hospital.attributes.get('location').range.length, 2);
            equal(hospital.attributes.get('location').range[0], "PostalAddress");
            equal(hospital.attributes.get('location').range[1], "Place");

            raises(function () {
                hospital.attributes.remove("description");
            });

            z.types.get("Organization").attributes.remove("founders");

            equal( hospital.attributes.list().length, 34);
            start();
        },
        error : function (msg) {
            ok(false, msg);
            start();
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
const mocha = require('mocha');
const coMocha = require('co-mocha');
coMocha(mocha);

const should = require('should');
const co = require('co');
const util = require('util');
const _ = require('lodash');
const isGeneratorFn = require('is-generator').fn;
const logger = require('./logger_test.js');
const chassis = require('../');
const config = chassis.config;
const Events = chassis.events.Events;

/* global describe it */

describe('events', () => {
  describe('without a provider', () => {
    const topicName = 'test';
    describe('yielding subscribe', () => {
      it('should throw an error', function* checkGetTopic() {
        const result = yield co(function* getTopic() {
          const events = new Events();
          return yield events.topic(topicName);
        }).then((res) => {
          should.ok(false, 'should not call then');
        }).catch((err) => {
          should.exist(err);
          err.should.be.Error();
          err.message.should.equal('missing argument name');
        });
        should.not.exist(result);
      });
    });
  });
  const providers = ['kafkaTest', 'localTest'];
  _.forEach(providers, (eventsName) => {
    describe(util.format(`testing config ${eventsName}`), () => {
      config.load(process.cwd() + '/test', logger);
      const events = new Events(eventsName, null, logger);
      const topicName = 'test';
      let topic;
      const eventName = 'test-event';
      const testMessage = {
        value: 'test',
        count: 1,
      };
      describe('yielding subscribe', () => {
        it('should return a topic', function* checkGetTopic() {
          topic = yield events.topic(topicName);
          should.exist(topic);
          should.exist(topic.on);
          should.exist(topic.emit);
          should.exist(topic.listenerCount);
          should.exist(topic.hasListeners);
          should.exist(topic.removeListener);
          should.exist(topic.removeAllListeners);
          should.ok(isGeneratorFn(topic.on));
          should.ok(isGeneratorFn(topic.emit));
          should.ok(isGeneratorFn(topic.listenerCount));
          should.ok(isGeneratorFn(topic.hasListeners));
          should.ok(isGeneratorFn(topic.removeListener));
          should.ok(isGeneratorFn(topic.removeAllListeners));
        });
      });
      describe('yielding Provider.start', function startKafka() {
        let callback;
        const listener = function* listener(message) {
          should.exist(message);
          testMessage.value.should.equal(message.value);
          testMessage.count.should.equal(message.count);
          if (callback) {
            callback();
            callback = undefined;
          }
        };
        this.timeout(8000);
        it('should setup the provider', function* connectToKafka() {
          yield events.start();
        });
        it('should allow listening to events', function* listenToEvents() {
          const count = yield topic.listenerCount(eventName);
          yield topic.on(eventName, listener);
          const countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count + 1);
        });
        it('should allow removing all listeners', function* removeAllListeners() {
          yield topic.on(eventName, listener);
          yield topic.removeAllListeners(eventName);
          const count = yield topic.listenerCount(eventName);
          count.should.equal(0);
        });
        it('should allow removing a listener', function* removeListener() {
          const count = yield topic.listenerCount(eventName);
          yield topic.on(eventName, listener);
          yield topic.removeListener(eventName, listener);
          const countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count);
        });
        it('should allow counting listeners', function* countListeners() {
          const count = yield topic.listenerCount(eventName);
          should.exist(count);
          const hasListeners = yield topic.hasListeners(eventName);
          hasListeners.should.equal(count > 0);
          yield topic.on(eventName, listener);
          let countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count + 1);
          yield topic.removeListener(eventName, listener);
          countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count);
        });
        it('should allow emitting', function* sendEvents(done) {
          yield topic.on(eventName, listener);
          callback = done;
          try {
            yield topic.emit(eventName, testMessage);
          } catch (e) {
            done(e);
          }
        });
        describe('yielding provider.end', () => {
          it('should stop the event provider', function* endProvider() {
            yield events.end();
          });
        });
      });
    });
  });
});
<commit_msg>Start Events before and shutdown after tests<commit_after>'use strict';

/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
const mocha = require('mocha');
const coMocha = require('co-mocha');
coMocha(mocha);

const should = require('should');
const co = require('co');
const util = require('util');
const _ = require('lodash');
const isGeneratorFn = require('is-generator').fn;
const logger = require('./logger_test.js');
const chassis = require('../');
const config = chassis.config;
const Events = chassis.events.Events;

/* global describe it before after */

describe('events', () => {
  describe('without a provider', () => {
    const topicName = 'test';
    describe('yielding subscribe', () => {
      it('should throw an error', function* checkGetTopic() {
        const result = yield co(function* getTopic() {
          const events = new Events();
          return yield events.topic(topicName);
        }).then((res) => {
          should.ok(false, 'should not call then');
        }).catch((err) => {
          should.exist(err);
          err.should.be.Error();
          err.message.should.equal('missing argument name');
        });
        should.not.exist(result);
      });
    });
  });
  const providers = ['kafkaTest', 'localTest'];
  _.forEach(providers, (eventsName) => {
    describe(util.format(`testing config ${eventsName}`), () => {
      config.load(process.cwd() + '/test', logger);
      let events;
      const topicName = 'test';
      let topic;
      const eventName = 'test-event';
      const testMessage = {
        value: 'test',
        count: 1,
      };
      before(function* start() {
        events = new Events(eventsName, null, logger);
        yield events.start();
      });
      after(function* start() {
        yield events.end();
        events = null;
      });
      describe('yielding subscribe', () => {
        it('should return a topic', function* checkGetTopic() {
          topic = yield events.topic(topicName);
          topic.someValue = 'from events_test.js';
          should.exist(topic);
          should.exist(topic.on);
          should.exist(topic.emit);
          should.exist(topic.listenerCount);
          should.exist(topic.hasListeners);
          should.exist(topic.removeListener);
          should.exist(topic.removeAllListeners);
          should.ok(isGeneratorFn(topic.on));
          should.ok(isGeneratorFn(topic.emit));
          should.ok(isGeneratorFn(topic.listenerCount));
          should.ok(isGeneratorFn(topic.hasListeners));
          should.ok(isGeneratorFn(topic.removeListener));
          should.ok(isGeneratorFn(topic.removeAllListeners));
        });
      });
      describe('yielding Provider.start', function startKafka() {
        let callback;
        const listener = function* listener(message, context) {
          should.exist(message);
          testMessage.value.should.equal(message.value);
          testMessage.count.should.equal(message.count);
          if (callback) {
            callback();
            callback = undefined;
          }
        };
        this.timeout(20000);
        it('should allow listening to events', function* listenToEvents() {
          const count = yield topic.listenerCount(eventName);
          yield topic.on(eventName, listener);
          const countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count + 1);
        });
        it('should allow removing all listeners', function* removeAllListeners() {
          yield topic.on(eventName, listener);
          yield topic.removeAllListeners(eventName);
          const count = yield topic.listenerCount(eventName);
          count.should.equal(0);
        });
        it('should allow removing a listener', function* removeListener() {
          const count = yield topic.listenerCount(eventName);
          yield topic.on(eventName, listener);
          yield topic.removeListener(eventName, listener);
          const countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count);
        });
        it('should allow counting listeners', function* countListeners() {
          const count = yield topic.listenerCount(eventName);
          should.exist(count);
          const hasListeners = yield topic.hasListeners(eventName);
          hasListeners.should.equal(count > 0);
          yield topic.on(eventName, listener);
          let countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count + 1);
          yield topic.removeListener(eventName, listener);
          countAfter = yield topic.listenerCount(eventName);
          countAfter.should.equal(count);
        });
        it('should allow emitting', function* sendEvents(done) {
          yield topic.on(eventName, listener);
          callback = done;
          try {
            yield topic.emit(eventName, testMessage);
          } catch (e) {
            done(e);
          }
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var gather = require('../lib/gather');
var path = require('path');

describe('The gather module', function () {
	describe('minimal_1 fixture', function () {
		var data;
		before(function () {
			data = gather.gatherDocletsAndMeta(path.join(__dirname, 'fixtures', 'minimal_1'), 'http://github.com/foo/bar', 'v1.0.0');
		});

		it('basic info is correct', function () {
			var date;
			assert.equal(data.version, '1.0.0');
			assert.equal(data.type, 'jsdoc');
			assert.doesNotThrow(function () {
				date = new Date(data.date);
			});
			assert((date - new Date()) < 5000, 'date is plausible');
		});

		it('repo info is correct', function () {
			assert.equal(data.repo.type, 'github');
			assert.equal(data.repo.user, 'foo');
			assert.equal(data.repo.name, 'bar');
			assert.equal(data.repo.branch, 'v1.0.0');
			assert.equal(data.repo.private, false);
			assert.equal(data.repo.url, 'http://github.com/foo/bar');

		});

		it('.articles[0] is correct', function () {
			var article = data.articles[0];
			assert.equal(data.articles.length, 1);
			assert.equal(article.title, 'About');
			assert.equal(article.markdown, '#hello\n');
		});

		it('.doclets are correct', function () {
			assert.equal(data.doclets.length, 1);
			assert.equal(data.doclets[0].name, 'foo');
		});

		it('.doclets filename is relative to dir', function () {
			assert.equal(data.doclets[0].meta.filename, 'index.js');
		});

	});

	describe('minimal_2 fixture', function () {
		var data;
		before(function () {
			data = gather.gatherDocletsAndMeta(path.join(__dirname, 'fixtures', 'minimal_2'), 'http://github.com/foo/bar', 'v1.0.0');
		});

		it('.doclets filename is relative to dir', function () {
			assert.equal(data.doclets[0].meta.filename, 'lib/index.js');
		});

		it('.articles[0] is correct', function () {
			var article = data.articles[0];
			assert.equal(data.articles.length, 1);
			assert.equal(article.title, 'About');
			assert.equal(article.markdown, '#hello\n');
		});

	});
});<commit_msg>refactor test<commit_after>var assert = require('assert');
var gather = require('../lib/gather');
var path = require('path');

var loadFixture = function (name) {
	var dir = path.join(__dirname, 'fixtures', name);
	return gather.gatherDocletsAndMeta(dir, 'http://github.com/foo/bar', 'v1.0.0');
};

describe('The gather module', function () {
	describe('minimal_1 fixture', function () {
		var data;
		before(function () {
			data = loadFixture('minimal_1');
		});

		it('basic info is correct', function () {
			var date;
			assert.equal(data.version, '1.0.0');
			assert.equal(data.type, 'jsdoc');
			assert.doesNotThrow(function () {
				date = new Date(data.date);
			});
			assert((date - new Date()) < 5000, 'date is plausible');
		});

		it('repo info is correct', function () {
			assert.equal(data.repo.type, 'github');
			assert.equal(data.repo.user, 'foo');
			assert.equal(data.repo.name, 'bar');
			assert.equal(data.repo.branch, 'v1.0.0');
			assert.equal(data.repo.private, false);
			assert.equal(data.repo.url, 'http://github.com/foo/bar');

		});

		it('.articles[0] is correct', function () {
			var article = data.articles[0];
			assert.equal(data.articles.length, 1);
			assert.equal(article.title, 'About');
			assert.equal(article.markdown, '#hello\n');
		});

		it('.doclets are correct', function () {
			assert.equal(data.doclets.length, 1);
			assert.equal(data.doclets[0].name, 'foo');
		});

		it('.doclets filename is relative to dir', function () {
			assert.equal(data.doclets[0].meta.filename, 'index.js');
		});

	});

	describe('minimal_2 fixture', function () {
		var data;
		before(function () {
			data = loadFixture('minimal_2');
		});

		it('.doclets filename is relative to dir', function () {
			assert.equal(data.doclets[0].meta.filename, 'lib/index.js');
		});

		it('.articles[0] is correct', function () {
			var article = data.articles[0];
			assert.equal(data.articles.length, 1);
			assert.equal(article.title, 'About');
			assert.equal(article.markdown, '#hello\n');
		});

	});
});<|endoftext|>


<commit_before>/**
 * @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

var assert = require('assert');
var fs = require('fs');
var path = require('path');
var stream = require('stream');
var swaggerSpecValidatorCmd = require('../bin/swagger-spec-validator');

// Simulate arguments passed by the node runtime
var RUNTIME_ARGS = ['node', 'swagger-spec-validator'];

var swaggerJsonPath =
  path.join(__dirname, '..', 'test-data', 'petstore-minimal.json');
var swaggerYamlPath =
  path.join(__dirname, '..', 'test-data', 'petstore-minimal.yaml');
var invalidYamlPath =
  path.join(__dirname, '..', 'test-data', 'petstore-invalid.yaml');

describe('swagger-spec-validator', function() {
  it('validates JSON and YAML files', function() {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var allArgs = RUNTIME_ARGS.concat([swaggerJsonPath, swaggerYamlPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 0);
      assert.strictEqual(options.out.read(), null);
      assert.ok(/\bvalid/i.test(options.err.read()));
    });
  });

  it('validates from stdin', function() {
    var options = {
      in: fs.createReadStream(swaggerYamlPath),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    swaggerSpecValidatorCmd(RUNTIME_ARGS, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 0);
      assert.strictEqual(options.out.read(), null);
      assert.ok(/\bvalid/i.test(options.err.read()));
    });
  });

  it('handles validation failures', function() {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var allArgs = RUNTIME_ARGS.concat([invalidYamlPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 1);
      var outStr = String(options.out.read());
      assert.strictEqual(outStr.indexOf(invalidYamlPath + ':'), 0);
      assert.strictEqual(options.err.read(), null);
    });
  });

  it('handles unreadable file errors', function() {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var nonexistentPath = 'nonexistent.yaml';
    var allArgs = RUNTIME_ARGS.concat([nonexistentPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 2);
      assert.strictEqual(options.out.read(), null);
      var errStr = String(options.err.read());
      assert.strictEqual(errStr.indexOf(nonexistentPath + ':'), 0);
      assert.ok(errStr.indexOf('ENOENT') >= 0);
    });
  });
});
<commit_msg>Add callback to async integration tests<commit_after>/**
 * @copyright Copyright 2017 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

var assert = require('assert');
var fs = require('fs');
var path = require('path');
var stream = require('stream');
var swaggerSpecValidatorCmd = require('../bin/swagger-spec-validator');

// Simulate arguments passed by the node runtime
var RUNTIME_ARGS = ['node', 'swagger-spec-validator'];

var swaggerJsonPath =
  path.join(__dirname, '..', 'test-data', 'petstore-minimal.json');
var swaggerYamlPath =
  path.join(__dirname, '..', 'test-data', 'petstore-minimal.yaml');
var invalidYamlPath =
  path.join(__dirname, '..', 'test-data', 'petstore-invalid.yaml');

describe('swagger-spec-validator', function() {
  it('validates JSON and YAML files', function(done) {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var allArgs = RUNTIME_ARGS.concat([swaggerJsonPath, swaggerYamlPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 0);
      assert.strictEqual(options.out.read(), null);
      assert.ok(/\bvalid/i.test(options.err.read()));
      done();
    });
  });

  it('validates from stdin', function(done) {
    var options = {
      in: fs.createReadStream(swaggerYamlPath),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    swaggerSpecValidatorCmd(RUNTIME_ARGS, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 0);
      assert.strictEqual(options.out.read(), null);
      assert.ok(/\bvalid/i.test(options.err.read()));
      done();
    });
  });

  it('handles validation failures', function(done) {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var allArgs = RUNTIME_ARGS.concat([invalidYamlPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 1);
      var outStr = String(options.out.read());
      assert.strictEqual(outStr.indexOf(invalidYamlPath + ':'), 0);
      assert.strictEqual(options.err.read(), null);
      done();
    });
  });

  it('handles unreadable file errors', function(done) {
    var options = {
      in: new stream.PassThrough(),
      out: new stream.PassThrough(),
      err: new stream.PassThrough()
    };
    var nonexistentPath = 'nonexistent.yaml';
    var allArgs = RUNTIME_ARGS.concat([nonexistentPath]);
    swaggerSpecValidatorCmd(allArgs, options, function(err, code) {
      assert.ifError(err);
      assert.strictEqual(code, 2);
      assert.strictEqual(options.out.read(), null);
      var errStr = String(options.err.read());
      assert.strictEqual(errStr.indexOf(nonexistentPath + ':'), 0);
      assert.ok(errStr.indexOf('ENOENT') >= 0);
      done();
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var grunt = require('grunt');
var jshint = require('../tasks/lib/jshint').init(grunt);

var fixtures = path.join(__dirname, 'fixtures');

// Helper for testing stdout
var hooker = grunt.util.hooker;
var stdoutEqual = function(callback, done) {
  var actual = '';
  // Hook process.stdout.write
  hooker.hook(process.stdout, 'write', {
    // This gets executed before the original process.stdout.write.
    pre: function(result) {
      // Concatenate uncolored result onto actual.
      actual += grunt.log.uncolor(result);
      // Prevent the original process.stdout.write from executing.
      return hooker.preempt();
    }
  });
  // Execute the logging code to be tested.
  callback();
  // Restore process.stdout.write to its original value.
  hooker.unhook(process.stdout, 'write');
  // Actually test the actually-logged stdout string to the expected value.
  done(actual);
};

exports.jshint = {
  basic: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'missingsemicolon.js')];
    var options = {};
    jshint.lint(files, options, function(results, data) {
      test.equal(results[0].error.reason, 'Missing semicolon.', 'Should reporter a missing semicolon.');
      test.done();
    });
  },
  jshintrc: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      jshintrc: path.join(__dirname, '..', '.jshintrc')
    };
    jshint.lint(files, options, function(results, data) {
      test.ok(results.length === 0, 'Should not have reported any errors with supplied .jshintrc');
      test.done();
    });
  },
  passTheJshintrcBuck: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      jshintrc: true
    };
    jshint.lint(files, options, function(results, data) {
      test.ok(results.length === 0, 'Should not have reported any errors, .jshintrc must not have been found');
      test.done();
    });
  },
  defaultReporter: function(test) {
    test.expect(2);
    grunt.log.muted = false;
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {};
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok(jshint.usingGruntReporter, 'Should be using the default grunt reporter.');
      test.ok(result.indexOf('[L3:C1] W117: \'module\' is not defined.') !== -1, 'Should have reported errors with the default grunt reporter.');
      test.done();
    });
  },
  defaultReporterErrors: function(test) {
    test.expect(3);
    grunt.log.muted = false;
    var files = [path.join(fixtures, 'nodemodule.js'), path.join(fixtures, 'missingsemicolon.js')];
    var options = {};
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok(jshint.usingGruntReporter, 'Should be using the default grunt reporter.');
      test.ok(result.match(/nodemodule\.js\s\.\.\.ERROR/g).length === 1, 'Should have reported nodemodule.js only once.');
      test.ok(result.match(/missingsemicolon\.js\s\.\.\.ERROR/g).length === 1, 'Should have reported missingsemicolon.js only once.');
      test.done();
    });
  },
  alternateReporter: function(test) {
    test.expect(2);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      reporter: 'jslint'
    };
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok((jshint.usingGruntReporter === false), 'Should NOT be using the default grunt reporter.');
      test.ok(result.indexOf('<jslint>') !== -1, 'Should have reported errors with the jslint reporter.');
      test.done();
    });
  },
  reporterOutput: function(test) {
    test.expect(1);
    var result = grunt.file.read(path.join('tmp', 'report.xml'));
    test.ok(result.indexOf('<file name="test/fixtures/missingsemicolon.js">') !== -1, 'Should have reported errors with the checkstyle reporter.');
    test.done();
  },
  dontBlowUp: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'lint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(results[0].error.code, 'W100', 'It should not blow up if an error occurs on character 0.');
      test.done();
    });
  },
  jshintignore: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'dontlint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(data.length, 0, 'Should not have linted a file listed in the .jshintignore.');
      test.done();
    });
  },
  ignoresOption: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'lint.txt')];
    var options = {
      ignores: files
    };
    jshint.lint(files, options, function(results, data) {
      test.equal(data.length, 0, 'Should not have linted a file listed in the ignores option.');
      test.done();
    });
  },
  singleReportCall: function(test) {
    test.expect(2);

    // stub jshint.reporter
    var reporterCallCount = 0;
    var _report = jshint.reporter;
    jshint.reporter = function() { reporterCallCount++; };

    var files = [path.join(fixtures, 'dontlint.txt'), path.join(fixtures, 'lint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(data.length, 1, 'Should not have linted a file listed in the .jshintignore.');
      test.equal(reporterCallCount, 1, 'Should have called the reporter once.');
      test.done();
    });
  },
  extractOption: function(test) {
    test.expect(2);
    var files = [path.join(fixtures, 'extract.html')];
    var options = {
      extract: 'always'
    };
    jshint.lint(files, options, function(results, data) {
      test.equal(results[0].error.reason, 'Missing semicolon.', 'Should reporter a missing semicolon.');
      test.equal(results.length, 1, 'Should report only one.');
      test.done();
    });
  }
};
<commit_msg>fix typos in jshint_test.js<commit_after>'use strict';

var path = require('path');
var grunt = require('grunt');
var jshint = require('../tasks/lib/jshint').init(grunt);

var fixtures = path.join(__dirname, 'fixtures');

// Helper for testing stdout
var hooker = grunt.util.hooker;
var stdoutEqual = function(callback, done) {
  var actual = '';
  // Hook process.stdout.write
  hooker.hook(process.stdout, 'write', {
    // This gets executed before the original process.stdout.write.
    pre: function(result) {
      // Concatenate uncolored result onto actual.
      actual += grunt.log.uncolor(result);
      // Prevent the original process.stdout.write from executing.
      return hooker.preempt();
    }
  });
  // Execute the logging code to be tested.
  callback();
  // Restore process.stdout.write to its original value.
  hooker.unhook(process.stdout, 'write');
  // Actually test the actually-logged stdout string to the expected value.
  done(actual);
};

exports.jshint = {
  basic: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'missingsemicolon.js')];
    var options = {};
    jshint.lint(files, options, function(results, data) {
      test.equal(results[0].error.reason, 'Missing semicolon.', 'Should report a missing semicolon.');
      test.done();
    });
  },
  jshintrc: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      jshintrc: path.join(__dirname, '..', '.jshintrc')
    };
    jshint.lint(files, options, function(results, data) {
      test.ok(results.length === 0, 'Should not have reported any errors with supplied .jshintrc');
      test.done();
    });
  },
  passTheJshintrcBuck: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      jshintrc: true
    };
    jshint.lint(files, options, function(results, data) {
      test.ok(results.length === 0, 'Should not have reported any errors, .jshintrc must not have been found');
      test.done();
    });
  },
  defaultReporter: function(test) {
    test.expect(2);
    grunt.log.muted = false;
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {};
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok(jshint.usingGruntReporter, 'Should be using the default grunt reporter.');
      test.ok(result.indexOf('[L3:C1] W117: \'module\' is not defined.') !== -1, 'Should have reported errors with the default grunt reporter.');
      test.done();
    });
  },
  defaultReporterErrors: function(test) {
    test.expect(3);
    grunt.log.muted = false;
    var files = [path.join(fixtures, 'nodemodule.js'), path.join(fixtures, 'missingsemicolon.js')];
    var options = {};
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok(jshint.usingGruntReporter, 'Should be using the default grunt reporter.');
      test.ok(result.match(/nodemodule\.js\s\.\.\.ERROR/g).length === 1, 'Should have reported nodemodule.js only once.');
      test.ok(result.match(/missingsemicolon\.js\s\.\.\.ERROR/g).length === 1, 'Should have reported missingsemicolon.js only once.');
      test.done();
    });
  },
  alternateReporter: function(test) {
    test.expect(2);
    var files = [path.join(fixtures, 'nodemodule.js')];
    var options = {
      reporter: 'jslint'
    };
    stdoutEqual(function() {
      jshint.lint(files, options, function(results, data) {});
    }, function(result) {
      test.ok((jshint.usingGruntReporter === false), 'Should NOT be using the default grunt reporter.');
      test.ok(result.indexOf('<jslint>') !== -1, 'Should have reported errors with the jslint reporter.');
      test.done();
    });
  },
  reporterOutput: function(test) {
    test.expect(1);
    var result = grunt.file.read(path.join('tmp', 'report.xml'));
    test.ok(result.indexOf('<file name="test/fixtures/missingsemicolon.js">') !== -1, 'Should have reported errors with the checkstyle reporter.');
    test.done();
  },
  dontBlowUp: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'lint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(results[0].error.code, 'W100', 'It should not blow up if an error occurs on character 0.');
      test.done();
    });
  },
  jshintignore: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'dontlint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(data.length, 0, 'Should not have linted a file listed in the .jshintignore.');
      test.done();
    });
  },
  ignoresOption: function(test) {
    test.expect(1);
    var files = [path.join(fixtures, 'lint.txt')];
    var options = {
      ignores: files
    };
    jshint.lint(files, options, function(results, data) {
      test.equal(data.length, 0, 'Should not have linted a file listed in the ignores option.');
      test.done();
    });
  },
  singleReportCall: function(test) {
    test.expect(2);

    // stub jshint.reporter
    var reporterCallCount = 0;
    var _report = jshint.reporter;
    jshint.reporter = function() { reporterCallCount++; };

    var files = [path.join(fixtures, 'dontlint.txt'), path.join(fixtures, 'lint.txt')];
    jshint.lint(files, {}, function(results, data) {
      test.equal(data.length, 1, 'Should not have linted a file listed in the .jshintignore.');
      test.equal(reporterCallCount, 1, 'Should have called the reporter once.');
      test.done();
    });
  },
  extractOption: function(test) {
    test.expect(2);
    var files = [path.join(fixtures, 'extract.html')];
    var options = {
      extract: 'always'
    };
    jshint.lint(files, options, function(results, data) {
      test.equal(results[0].error.reason, 'Missing semicolon.', 'Should report a missing semicolon.');
      test.equal(results.length, 1, 'Should report only one.');
      test.done();
    });
  }
};
<|endoftext|>


<commit_before>const BUFFERS = false

var leveldown = require('..')
  , crypto    = require('crypto')
  , putCount  = 0
  , getCount  = 0
  , rssBase
  , db

function run () {
  var key = 'long key to test memory usage ' + String(Math.floor(Math.random() * 10000000))

  if (BUFFERS) key = new Buffer(key)

  db.get(key, function (err, value) {
    getCount++

    if (err) {
      var putValue = crypto.randomBytes(1024)
      if (!BUFFERS) putValue = putValue.toString('hex')

      return db.put(key, putValue, function () {
        putCount++
        process.nextTick(run)
      })
    }

    process.nextTick(run)
  })

  if (getCount % 1000 === 0) {
    gc()
    console.log(
        'getCount ='
      , getCount
      , ', putCount = '
      , putCount
      , ', rss ='
      , Math.round(process.memoryUsage().rss / rssBase * 100) + '%'
      , Math.round(process.memoryUsage().rss / 1024 / 1024) + 'M'
      , JSON.stringify([0,1,2,3,4,5,6].map(function (l) {
          return db.getProperty('leveldb.num-files-at-level' + l)
        }))
    )
  }
}

leveldown.destroy('./leakydb', function () {
  db = leveldown('./leakydb')
  db.open({ xcacheSize: 0, xmaxOpenFiles: 10 }, function () {
    rssBase = process.memoryUsage().rss
    run()
  })
})<commit_msg>qualify 'gc()' use<commit_after>const BUFFERS = false

var leveldown = require('..')
  , crypto    = require('crypto')
  , putCount  = 0
  , getCount  = 0
  , rssBase
  , db

function run () {
  var key = 'long key to test memory usage ' + String(Math.floor(Math.random() * 10000000))

  if (BUFFERS) key = new Buffer(key)

  db.get(key, function (err, value) {
    getCount++

    if (err) {
      var putValue = crypto.randomBytes(1024)
      if (!BUFFERS) putValue = putValue.toString('hex')

      return db.put(key, putValue, function () {
        putCount++
        process.nextTick(run)
      })
    }

    process.nextTick(run)
  })

  if (getCount % 1000 === 0) {
    if (typeof gc != 'undefined')
      gc()
    console.log(
        'getCount ='
      , getCount
      , ', putCount = '
      , putCount
      , ', rss ='
      , Math.round(process.memoryUsage().rss / rssBase * 100) + '%'
      , Math.round(process.memoryUsage().rss / 1024 / 1024) + 'M'
      , JSON.stringify([0,1,2,3,4,5,6].map(function (l) {
          return db.getProperty('leveldb.num-files-at-level' + l)
        }))
    )
  }
}

leveldown.destroy('./leakydb', function () {
  db = leveldown('./leakydb')
  db.open({ xcacheSize: 0, xmaxOpenFiles: 10 }, function () {
    rssBase = process.memoryUsage().rss
    run()
  })
})<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey
 * http://scratchdisk.com/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

// Register a jsDump parser for Base.
QUnit.jsDump.setParser('Base', function (obj, stack) {
    // Just compare the string representation of classes inheriting from Base,
    // since they hide the internal values.
    return obj.toString();
});

// Override the default object parser to handle Base objects.
// We need to keep a reference to the previous implementation.
var objectParser = QUnit.jsDump.parsers.object;

QUnit.jsDump.setParser('object', function (obj, stack) {
    return (obj instanceof Base
            ? QUnit.jsDump.parsers.Base
            : objectParser).call(this, obj, stack);
});

function compareProperties(actual, expected, properties, message, options) {
    Base.each(properties, function(key) {
        equals(actual[key], expected[key], message + '.' + key, options);
    });
}

function compareItem(actual, expected, message, options, properties) {
    if (options && options.cloned)
        QUnit.notStrictEqual(actual.id, 'not ' + expected.id, message + '.id');
    QUnit.strictEqual(actual.constructor, expected.constructor,
            message + '.constructor');
    // When item was cloned and had a name, the name will be versioned
    equals(options && options.cloned && actual.name ? actual.name + ' 1'
            : actual.name, expected.name,
            message + '.name');
    compareProperties(actual, expected, ['children', 'bounds', 'position',
            'matrix', 'data', 'opacity', 'locked', 'visible', 'blendMode',
            'selected', 'fullySelected', 'clipMask', 'guide'],
            message, options);
    if (properties)
        compareProperties(actual, expected, properties, message, options);
    // Style
    compareProperties(actual.style, expected.style, ['fillColor', 'strokeColor',
            'strokeCap', 'strokeJoin', 'dashArray', 'dashOffset', 'miterLimit',
            'fontSize', 'font', 'leading', 'justification'],
            message + '.style', options);
}

var comparators = {
    Null: QUnit.strictEqual,
    Undefined: QUnit.strictEqual,
    Boolean: QUnit.strictEqual,

    Object: function(actual, expected, message, options) {
        QUnit.push(Base.equals(actual, expected), actual, expected, message);
    },

    Base: function(actual, expected, message, options) {
        comparators.Object(actual, expected, message, options);
    },

    Number: function(actual, expected, message, options) {
        // Compare with a default tolerance of Numerical.TOLERANCE:
        var ok = Math.abs(actual - expected)
                <= Base.pick(options && options.tolerance, Numerical.TOLERANCE);
        QUnit.push(ok, ok ? expected : actual, expected, message);
    },

    Array: function(actual, expected, message, options) {
        QUnit.strictEqual(actual.length, expected.length, message + '.length');
        for (var i = 0, l = actual.length; i < l; i++) {
            equals(actual[i], expected[i], (message || '') + '[' + i + ']',
                options);
        }
    },

    Point: function(actual, expected, message, options) {
        comparators.Number(actual.x, expected.x, message + '.x', options);
        comparators.Number(actual.y, expected.y, message + '.y', options);
    },

    Size: function(actual, expected, message, options) {
        comparators.Number(actual.width, expected.width, message + '.width',
                options);
        comparators.Number(actual.height, expected.height, message + '.height',
                options);
    },

    Rectangle: function(actual, expected, message, options) {
        comparators.Point(actual, expected, message, options);
        comparators.Size(actual, expected, message, options);
    },

    Matrix: function(actual, expected, message, options) {
        comparators.Array(actual.values, expected.values, message, options);
    },

    Color: function(actual, expected, message, options) {
        if (actual && expected) {
            equals(actual.type, expected.type, message + '.type', options);
            // NOTE: This also compares gradients, with identity checks and all.
            equals(actual.components, expected.components,
                    message + '.components', options);
        } else {
            QUnit.strictEqual(actual, expected, message);
        }
    },

    Symbol: function(actual, expected, message, options) {
        equals(actual.definition, expected.definition, message + '.definition',
                options);
    },

    Segment: function(actual, expected, message, options) {
        Base.each(['handleIn', 'handleOut', 'point', 'selected'],
            function(key) {
                equals(actual[key], expected[key], message + '.' + key);
            }
        );
    },

    SegmentPoint: function(actual, expected, message, options) {
        comparators.Point(actual, expected, message, options);
        comparators.Boolean(actual.selected, expected.selected,
                message + '.selected', options);
    },

    Item: compareItem,

    Group: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['clipped']);
    },

    Layer: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options);
        equals(function() {
            return options && options.dontShareProject
                    ? actual.project !== expected.project
                    : actual.project === expected.project;
        }, true);
    },

    Path: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['segments', 'closed', 'clockwise', 'length']);
    },

    CompoundPath: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options);
    },

    Raster: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['size', 'width', 'height', 'ppi', 'source', 'image']);
        equals(actual.toDataURL(), expected.toDataURL(),
                message + '.toDataUrl()');
    },

    Shape: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['shape', 'size', 'radius']);
    },

    PlacedSymbol: function(actual, expected, message, options) {
        compareItem(actual, expected, message,
                // Cloning PlacedSymbols does not result in cloned Symbols
                options && options.cloned
                        ? new Base(options, { cloned: false })
                        : options,
                ['symbol']);
    },

    PointText: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['content', 'point']);
    },

    Project: function(actual, expected, message, options) {
        compareProperties(actual, expected, ['symbols', 'layers'],
                message, options);
    }
};

var strictIdenticalAfterCloning = {
    Gradient: true,
    Symbol: true
};

function getFunctionMessage(func) {
    var message = func.toString().match(
        /^\s*function[^\{]*\{([\s\S]*)\}\s*$/)[1]
            .replace(/    /g, '')
            .replace(/^\s+|\s+$/g, '');
    if (/^return /.test(message)) {
        message = message
            .replace(/^return /, '')
            .replace(/;$/, '');
    }
    return message;
}

// Override equals to convert functions to message and execute them as tests()
function equals(actual, expected, message, options) {
    // Allow the use of functions for actual, which will get called and their
    // source content extracted for readable reports.
    if (typeof actual === 'function') {
        if (!message)
            message = getFunctionMessage(actual);
        actual = actual();
    }
    // Get the comparator based on the expected value's type only and ignore the
    // actual value's type.
    var type = typeof expected,
        cls;
    type = expected === null && 'Null'
            || type === 'number' && 'Number'
            || type === 'boolean' && 'Boolean'
            || type === 'undefined' && 'Undefined'
            || Array.isArray(expected) && 'Array'
            || (cls = expected && expected._class)
            || type === 'object' && 'Object';
    var comparator = type && comparators[type];
    if (!message) {
        message = type
                ? type.charAt(0).toLowerCase() + type.substring(1)
                : 'value';
    }
    if (comparator) {
        comparator(actual, expected, message, options);
    } else if (expected && expected.equals) {
        // Fall back to equals
        QUnit.push(expected.equals(actual), actual, expected, message);
    } else {
        // Finally perform a strict compare
        QUnit.push(actual === expected, actual, expected, message);
    }
    if (options && options.cloned && cls) {
        var identical = strictIdenticalAfterCloning[cls];
        QUnit.push(identical ? actual === expected : actual !== expected,
                actual, identical ? expected : 'not ' + expected,
                message + ': identical after cloning');
    }
}

function test(testName, expected) {
    return QUnit.test(testName, function() {
        var project = new Project();
        expected();
        project.remove();
    });
}

function asyncTest(testName, expected) {
    return QUnit.asyncTest(testName, function() {
        var project = new Project();
        expected(function() {
            project.remove();
            start();
        });
    });
}

// SVG

function createSVG(xml) {
    return new DOMParser().parseFromString(
        '<svg xmlns="http://www.w3.org/2000/svg">' + xml + '</svg>',
        'text/xml');
}
<commit_msg>Some more clean-up in unit test helpers code.<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey
 * http://scratchdisk.com/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

// Register a jsDump parser for Base.
QUnit.jsDump.setParser('Base', function (obj, stack) {
    // Just compare the string representation of classes inheriting from Base,
    // since they hide the internal values.
    return obj.toString();
});

// Override the default object parser to handle Base objects.
// We need to keep a reference to the previous implementation.
var objectParser = QUnit.jsDump.parsers.object;

QUnit.jsDump.setParser('object', function (obj, stack) {
    return (obj instanceof Base
            ? QUnit.jsDump.parsers.Base
            : objectParser).call(this, obj, stack);
});

function compareProperties(actual, expected, properties, message, options) {
    for (var i = 0, l = properties.length; i < l; i++) {
        var key = properties[i];
        equals(actual[key], expected[key], message + '.' + key, options);
    }
}

function compareItem(actual, expected, message, options, properties) {
    if (options && options.cloned)
        QUnit.notStrictEqual(actual.id, 'not ' + expected.id, message + '.id');
    QUnit.strictEqual(actual.constructor, expected.constructor,
            message + '.constructor');
    // When item was cloned and had a name, the name will be versioned
    equals(options && options.cloned && actual.name ? actual.name + ' 1'
            : actual.name, expected.name,
            message + '.name');
    compareProperties(actual, expected, ['children', 'bounds', 'position',
            'matrix', 'data', 'opacity', 'locked', 'visible', 'blendMode',
            'selected', 'fullySelected', 'clipMask', 'guide'],
            message, options);
    if (properties)
        compareProperties(actual, expected, properties, message, options);
    // Style
    compareProperties(actual.style, expected.style, ['fillColor', 'strokeColor',
            'strokeCap', 'strokeJoin', 'dashArray', 'dashOffset', 'miterLimit',
            'fontSize', 'font', 'leading', 'justification'],
            message + '.style', options);
}

// A list of comparator functions, based on `expected` type. See equals() for
// an explanation of how the type is determined.
var comparators = {
    Null: QUnit.strictEqual,
    Undefined: QUnit.strictEqual,
    Boolean: QUnit.strictEqual,

    Object: function(actual, expected, message, options) {
        QUnit.push(Base.equals(actual, expected), actual, expected, message);
    },

    Base: function(actual, expected, message, options) {
        comparators.Object(actual, expected, message, options);
    },

    Number: function(actual, expected, message, options) {
        // Compare with a default tolerance of Numerical.TOLERANCE:
        var ok = Math.abs(actual - expected)
                <= Base.pick(options && options.tolerance, Numerical.TOLERANCE);
        QUnit.push(ok, ok ? expected : actual, expected, message);
    },

    Array: function(actual, expected, message, options) {
        QUnit.strictEqual(actual.length, expected.length, message + '.length');
        for (var i = 0, l = actual.length; i < l; i++) {
            equals(actual[i], expected[i], (message || '') + '[' + i + ']',
                options);
        }
    },

    Point: function(actual, expected, message, options) {
        comparators.Number(actual.x, expected.x, message + '.x', options);
        comparators.Number(actual.y, expected.y, message + '.y', options);
    },

    Size: function(actual, expected, message, options) {
        comparators.Number(actual.width, expected.width, message + '.width',
                options);
        comparators.Number(actual.height, expected.height, message + '.height',
                options);
    },

    Rectangle: function(actual, expected, message, options) {
        comparators.Point(actual, expected, message, options);
        comparators.Size(actual, expected, message, options);
    },

    Matrix: function(actual, expected, message, options) {
        comparators.Array(actual.values, expected.values, message, options);
    },

    Color: function(actual, expected, message, options) {
        if (actual && expected) {
            equals(actual.type, expected.type, message + '.type', options);
            // NOTE: This also compares gradients, with identity checks and all.
            equals(actual.components, expected.components,
                    message + '.components', options);
        } else {
            QUnit.strictEqual(actual, expected, message);
        }
    },

    Symbol: function(actual, expected, message, options) {
        equals(actual.definition, expected.definition, message + '.definition',
                options);
    },

    Segment: function(actual, expected, message, options) {
        compareProperties(actual, expected, ['handleIn', 'handleOut', 'point',
                'selected'], message, options);
    },

    SegmentPoint: function(actual, expected, message, options) {
        comparators.Point(actual, expected, message, options);
        comparators.Boolean(actual.selected, expected.selected,
                message + '.selected', options);
    },

    Item: compareItem,

    Group: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options, ['clipped']);
    },

    Layer: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options);
        var sameProject = actual.project === expected.project;
        var sharedProject = !(options && options.dontShareProject);
        QUnit.push(sharedProject ? sameProject : !sameProject,
                actual.project,
                sharedProject ? expected.project : 'not ' + expected.project,
                message + '.project');
    },

    Path: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['segments', 'closed', 'clockwise', 'length']);
    },

    CompoundPath: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options);
    },

    Raster: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['size', 'width', 'height', 'ppi', 'source', 'image']);
        equals(actual.toDataURL(), expected.toDataURL(),
                message + '.toDataUrl()');
    },

    Shape: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['shape', 'size', 'radius']);
    },

    PlacedSymbol: function(actual, expected, message, options) {
        compareItem(actual, expected, message,
                // Cloning PlacedSymbols does not result in cloned Symbols
                options && options.cloned
                        ? new Base(options, { cloned: false })
                        : options,
                ['symbol']);
    },

    PointText: function(actual, expected, message, options) {
        compareItem(actual, expected, message, options,
                ['content', 'point']);
    },

    Project: function(actual, expected, message, options) {
        compareProperties(actual, expected, ['symbols', 'layers'],
                message, options);
    }
};

// A list of classes that should be identical after their owners were cloned.
var identicalAfterCloning = {
    Gradient: true,
    Symbol: true
};

function getFunctionMessage(func) {
    var message = func.toString().match(
        /^\s*function[^\{]*\{([\s\S]*)\}\s*$/)[1]
            .replace(/    /g, '')
            .replace(/^\s+|\s+$/g, '');
    if (/^return /.test(message)) {
        message = message
            .replace(/^return /, '')
            .replace(/;$/, '');
    }
    return message;
}

// Override equals to convert functions to message and execute them as tests()
function equals(actual, expected, message, options) {
    // Allow the use of functions for actual, which will get called and their
    // source content extracted for readable reports.
    if (typeof actual === 'function') {
        if (!message)
            message = getFunctionMessage(actual);
        actual = actual();
    }
    // Get the comparator based on the expected value's type only and ignore the
    // actual value's type.
    var type = typeof expected,
        cls;
    type = expected === null && 'Null'
            || type === 'number' && 'Number'
            || type === 'boolean' && 'Boolean'
            || type === 'undefined' && 'Undefined'
            || Array.isArray(expected) && 'Array'
            || (cls = expected && expected._class)
            || type === 'object' && 'Object';
    var comparator = type && comparators[type];
    if (!message) {
        message = type
                ? type.charAt(0).toLowerCase() + type.substring(1)
                : 'value';
    }
    if (comparator) {
        comparator(actual, expected, message, options);
    } else if (expected && expected.equals) {
        // Fall back to equals
        QUnit.push(expected.equals(actual), actual, expected, message);
    } else {
        // Finally perform a strict compare
        QUnit.push(actual === expected, actual, expected, message);
    }
    if (options && options.cloned && cls) {
        var identical = identicalAfterCloning[cls];
        QUnit.push(identical ? actual === expected : actual !== expected,
                actual, identical ? expected : 'not ' + expected,
                message + ': identical after cloning');
    }
}

function test(testName, expected) {
    return QUnit.test(testName, function() {
        var project = new Project();
        expected();
        project.remove();
    });
}

function asyncTest(testName, expected) {
    return QUnit.asyncTest(testName, function() {
        var project = new Project();
        expected(function() {
            project.remove();
            start();
        });
    });
}

// SVG

function createSVG(xml) {
    return new DOMParser().parseFromString(
        '<svg xmlns="http://www.w3.org/2000/svg">' + xml + '</svg>',
        'text/xml');
}
<|endoftext|>


<commit_before>var validate = require('../src/validator').master;

it("#01. Buyer should valid", function () {
    var Buyer = require('../src/master/buyer');
    validate.buyer(new Buyer());
});

it("#02. Product should valid", function () {
    var Product = require('../src/master/product');
    validate.product(new Product());
});

it("#03. Suppliers should valid", function () {
    var Supplier = require('../src/master/supplier');
    validate.supplier(new Supplier());
});

it("#04. uom should valid", function () {
    var uom = require('../src/master/uom');
    validate.uom(new uom());
});

it("#05. Unit should valid", function () {
    var Unit = require('../src/master/unit');
    validate.unit(new Unit());
});

it("#06. Category should valid", function () {
    var Category = require('../src/master/category');
    validate.category(new Category());
});

it("#07. Currency should valid", function () {
    var Currency = require('../src/master/currency');
    validate.currency(new Currency());
});

it("#08. Vat should valid", function () {
    var Vat = require('../src/master/vat');
    validate.vat(new Vat());
});

it("#09. Machine should valid", function () {
    var Machine = require('../src/master/machine');
    validate.machine(new Machine());
});

it("#10. Uster Classification should valid", function () {
    var Uster = require('../src/master/uster');
    validate.uster(new Uster());
});

it("#11. Lamp Standard should valid", function () {
    var LampStandard = require('../src/master/lamp-standard');
    validate.lampStandard(new LampStandard());
});

it("#12. Account Bank should valid", function () {
    var AccountBank = require('../src/master/account-bank');
    validate.accountBank(new AccountBank());
});

it("#13. Step should valid", function () {
    var Step = require('../src/master/step');
    validate.step(new Step());
});

it("#14. Instruction should valid", function () {
    var Instruction = require('../src/master/instruction');
    validate.instruction(new Instruction());
});

it("#15. Order Type should valid", function () {
    var OrderType = require('../src/master/order-type');
    validate.orderType(new OrderType());
});

it("#16. Process Type should valid", function () {
    var ProcessType = require('../src/master/process-type');
    validate.processType(new ProcessType());
});

it("#17. Color Type should valid", function () {
    var ColorType = require('../src/master/color-type');
    validate.colorType(new ColorType());
});

it("#18. Instruction should valid", function () {
    var Instruction = require('../src/master/instruction');
    validate.instruction(new Instruction());
});

it("#14. Order Type should valid", function () {
    var OrderType = require('../src/master/order-type');
    validate.orderType(new OrderType());
});

it("#15. Process Type should valid", function () {
    var ProcessType = require('../src/master/process-type');
    validate.processType(new ProcessType());
});

it("#16. Color Type should valid", function () {
    var ColorType = require('../src/master/color-type');
    validate.colorType(new ColorType());
});

it("#17. Step should valid", function () {
    var Step = require('../src/master/step');
    validate.step(new Step());
});

it("#18. Machine Type should valid", function () {
    var MachineType = require('../src/master/machine-type');
    validate.machineType(new MachineType());
});

it("#19. Machine Type Indicator should valid", function () {
    var MachineTypeIndicator = require('../src/master/machine-type-indicator');
    validate.machineTypeIndicator(new MachineTypeIndicator());
});

it("#20. Machine Spesification Standard should valid", function () {
    var MachineSpesificationStandard = require('../src/master/machine-spesification-standard');
    validate.machineSpesificationStandard(new MachineSpesificationStandard());
});

it("#21. Machine Event should valid", function () {
    var MachineEvent = require('../src/master/machine-event');
    validate.machineEvent(new MachineEvent());
});

it("#22. Material Contruction should valid", function () {
    var MaterialConstruction = require('../src/master/material-construction');
    validate.materialConstruction(new MaterialConstruction());
});

it("#23. Yarn Material should valid", function () {
    var YarnMaterial = require('../src/master/yarn-material');
    validate.yarnMaterial(new YarnMaterial());
});

it("#24. Finish Type should valid", function () {
    var FinishType = require('../src/master/finish-type');
    validate.finishType(new FinishType());
});

it("#25. Standard Test should valid", function () {
    var StandardTest = require('../src/master/standard-test');
    validate.standardTest(new StandardTest());
});

it("#26. Comodity should valid", function () {
    var Comodity = require('../src/master/comodity');
    validate.comodity(new Comodity());
});

it("#27. Quality should valid", function () {
    var Quality = require('../src/master/quality');
    validate.quality(new Quality());
});

it("#28. Array Step should valid", function () {
    var ArrayStep = require('../src/master/array-step');
    validate.arrayStep(new ArrayStep());
});

it("#29. Term of Payment should valid", function () {
    var TermOfPayment = require('../src/master/term-of-payment');
    validate.termOfPayment(new TermOfPayment());
});

it("#30. Design Motive should valid", function () {
    var DesignMotive = require('../src/master/design-motive');
    validate.designMotive(new DesignMotive());
});

it("#31. Storage should valid", function () {
    var Storage = require('../src/master/storage');
    validate.designMotive(new Storage());
});

it("#32. Company should valid", function () {
    var Company = require('../src/master/company');
    validate.company(new Company());
});

it("#33. Contact should valid", function () {
    var Contact = require('../src/master/contact');
    validate.contact(new Contact());
});

it("#34. Bad Output Reason should valid", function () {
    var BadOutputReason = require('../src/master/bad-output-reason');
    validate.badOutputReason(new BadOutputReason());
});

it("#35. Finishing Printing Duration Estimation should valid", function () {
    var Storage = require('../src/master/fp-duration-estimation');
    validate.finishingPrintingDurationEstimation(new Storage());
});

it("#36. Deal Tracking Reason should valid", function () {
    var DealTrackingReason = require('../src/master/deal-tracking-reason');
    validate.dealTrackingReason(new DealTrackingReason());
});

it("#37. Holiday should valid", function () {
    var Holiday = require('../src/master/holiday');
    validate.Holiday(new Holiday());
});<commit_msg>Update Master Test<commit_after>var validate = require('../src/validator').master;

it("#01. Buyer should valid", function () {
    var Buyer = require('../src/master/buyer');
    validate.buyer(new Buyer());
});

it("#02. Product should valid", function () {
    var Product = require('../src/master/product');
    validate.product(new Product());
});

it("#03. Suppliers should valid", function () {
    var Supplier = require('../src/master/supplier');
    validate.supplier(new Supplier());
});

it("#04. uom should valid", function () {
    var uom = require('../src/master/uom');
    validate.uom(new uom());
});

it("#05. Unit should valid", function () {
    var Unit = require('../src/master/unit');
    validate.unit(new Unit());
});

it("#06. Category should valid", function () {
    var Category = require('../src/master/category');
    validate.category(new Category());
});

it("#07. Currency should valid", function () {
    var Currency = require('../src/master/currency');
    validate.currency(new Currency());
});

it("#08. Vat should valid", function () {
    var Vat = require('../src/master/vat');
    validate.vat(new Vat());
});

it("#09. Machine should valid", function () {
    var Machine = require('../src/master/machine');
    validate.machine(new Machine());
});

it("#10. Uster Classification should valid", function () {
    var Uster = require('../src/master/uster');
    validate.uster(new Uster());
});

it("#11. Lamp Standard should valid", function () {
    var LampStandard = require('../src/master/lamp-standard');
    validate.lampStandard(new LampStandard());
});

it("#12. Account Bank should valid", function () {
    var AccountBank = require('../src/master/account-bank');
    validate.accountBank(new AccountBank());
});

it("#13. Step should valid", function () {
    var Step = require('../src/master/step');
    validate.step(new Step());
});

it("#14. Instruction should valid", function () {
    var Instruction = require('../src/master/instruction');
    validate.instruction(new Instruction());
});

it("#15. Order Type should valid", function () {
    var OrderType = require('../src/master/order-type');
    validate.orderType(new OrderType());
});

it("#16. Process Type should valid", function () {
    var ProcessType = require('../src/master/process-type');
    validate.processType(new ProcessType());
});

it("#17. Color Type should valid", function () {
    var ColorType = require('../src/master/color-type');
    validate.colorType(new ColorType());
});

it("#18. Instruction should valid", function () {
    var Instruction = require('../src/master/instruction');
    validate.instruction(new Instruction());
});

it("#14. Order Type should valid", function () {
    var OrderType = require('../src/master/order-type');
    validate.orderType(new OrderType());
});

it("#15. Process Type should valid", function () {
    var ProcessType = require('../src/master/process-type');
    validate.processType(new ProcessType());
});

it("#16. Color Type should valid", function () {
    var ColorType = require('../src/master/color-type');
    validate.colorType(new ColorType());
});

it("#17. Step should valid", function () {
    var Step = require('../src/master/step');
    validate.step(new Step());
});

it("#18. Machine Type should valid", function () {
    var MachineType = require('../src/master/machine-type');
    validate.machineType(new MachineType());
});

it("#19. Machine Type Indicator should valid", function () {
    var MachineTypeIndicator = require('../src/master/machine-type-indicator');
    validate.machineTypeIndicator(new MachineTypeIndicator());
});

it("#20. Machine Spesification Standard should valid", function () {
    var MachineSpesificationStandard = require('../src/master/machine-spesification-standard');
    validate.machineSpesificationStandard(new MachineSpesificationStandard());
});

it("#21. Machine Event should valid", function () {
    var MachineEvent = require('../src/master/machine-event');
    validate.machineEvent(new MachineEvent());
});

it("#22. Material Contruction should valid", function () {
    var MaterialConstruction = require('../src/master/material-construction');
    validate.materialConstruction(new MaterialConstruction());
});

it("#23. Yarn Material should valid", function () {
    var YarnMaterial = require('../src/master/yarn-material');
    validate.yarnMaterial(new YarnMaterial());
});

it("#24. Finish Type should valid", function () {
    var FinishType = require('../src/master/finish-type');
    validate.finishType(new FinishType());
});

it("#25. Standard Test should valid", function () {
    var StandardTest = require('../src/master/standard-test');
    validate.standardTest(new StandardTest());
});

it("#26. Comodity should valid", function () {
    var Comodity = require('../src/master/comodity');
    validate.comodity(new Comodity());
});

it("#27. Quality should valid", function () {
    var Quality = require('../src/master/quality');
    validate.quality(new Quality());
});

it("#28. Array Step should valid", function () {
    var ArrayStep = require('../src/master/array-step');
    validate.arrayStep(new ArrayStep());
});

it("#29. Term of Payment should valid", function () {
    var TermOfPayment = require('../src/master/term-of-payment');
    validate.termOfPayment(new TermOfPayment());
});

it("#30. Design Motive should valid", function () {
    var DesignMotive = require('../src/master/design-motive');
    validate.designMotive(new DesignMotive());
});

it("#31. Storage should valid", function () {
    var Storage = require('../src/master/storage');
    validate.designMotive(new Storage());
});

it("#32. Company should valid", function () {
    var Company = require('../src/master/company');
    validate.company(new Company());
});

it("#33. Contact should valid", function () {
    var Contact = require('../src/master/contact');
    validate.contact(new Contact());
});

it("#34. Bad Output Reason should valid", function () {
    var BadOutputReason = require('../src/master/bad-output-reason');
    validate.badOutputReason(new BadOutputReason());
});

it("#35. Finishing Printing Duration Estimation should valid", function () {
    var Storage = require('../src/master/fp-duration-estimation');
    validate.finishingPrintingDurationEstimation(new Storage());
});

it("#36. Deal Tracking Reason should valid", function () {
    var DealTrackingReason = require('../src/master/deal-tracking-reason');
    validate.dealTrackingReason(new DealTrackingReason());
});

it("#37. Holiday should valid", function () {
    var Holiday = require('../src/master/holiday');
    validate.holiday(new Holiday());
});<|endoftext|>