<commit_before>var mongoose = require('mongoose');
var testConfig = require('./test.config');
var User = require('../server/models/user/user.model');
var Game = require('../server/models/game/game.model');
var dbConfig = require('../server/config/db.config');
var clearDB = require('mocha-mongoose')(dbConfig.DATABASE.test, {noClear: true});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // Done to accept self signed HTTPS certfificate
var init = require('../server/init/init');

function importTest (name, path) {
	describe(name, function () {
		require(path);
	});
}

describe('Starting tests', function () {
	before(function (done) {
		if (mongoose.connection.db) return done();
		mongoose.connect(dbConfig.DATABASE.test, function (err) {
			if (err) return done(err);
			clearDB(done);
		});
	});
	// MODELS
	importTest('Testing user.model', './models/user/user.model.test');
	importTest('Testing game.model', './models/game/game.model.test');
	importTest('Testing comment.model', './models/comment/comment.model.test');
	importTest('Testing rating.model', './models/rating/rating.model.test');
	importTest('Testing review.model', './models/review/review.model.test');
	importTest('Testing unpublishedGame.model', './models/unpublishedGame/unpublishedGame.model.test');
	// ROUTES
	importTest('Testing user.route', './routes/user/user.route.test');
	importTest('Testing game.route', './routes/game/game.route.test');
	importTest('Testing login.route', './routes/login/login.route.test');
	importTest('Testing review.route', './routes/review/review.route.test');
	importTest('Testing unpublishedGame.route', './routes/unpublishedGame/unpublishedGame.route.test');

	after(function (done) {
		mongoose.connection.db.dropDatabase(function (err) {
			if (err) return done(err);
			var testUser = new User(testConfig.USER_TESTUSER);
			testUser.save(function (err) {
				if (err) return done(err);
				var testUser2 = new User(testConfig.USER_TESTUSER2);
				testUser2.save(function (err) {
					if (err) return done(err);
					Game.ensureIndexes(function (err) {
						if (err) return done(err);
						var game = new Game(
							{title: 'test game',
							shortDescription: 'this is a short description',
							pieces: {
								singles: 4,
								doubles: 5,
								triples: 6
							},
							isPlayableWithMorePlayers: true,
							isPlayableWithTeams: true,
							sumOfVotes: 4,
							numberOfVotes: 1,
							rating: 4,
							numberOfPlayers: 3,
							images: ['http://www.magination.no/images/game1_crop.jpg',
									'http://www.magination.no/images/game2_crop.jpg',
									'http://www.magination.no/images/game3_crop.jpg'],
							otherObjects: ['cup', 'book'],
							rules: ['rule 1', 'rule 2'],
							alternativeRules: ['alt rule 1', 'alt rule 2'],
							owner: testUser._id});
						var game2 = new Game(
							{title: 'test game 2',
							shortDescription: 'this is a short description 2',
							pieces: {
								singles: 4,
								doubles: 5,
								triples: 6
							},
							isPlayableWithMorePlayers: true,
							isPlayableWithTeams: true,
							sumOfVotes: 3,
							numberOfVotes: 1,
							rating: 3,
							numberOfPlayers: 3,
							images: ['http://www.magination.no/images/game1_crop.jpg',
									'http://www.magination.no/images/game2_crop.jpg',
									'http://www.magination.no/images/game3_crop.jpg'],
							otherObjects: ['cup', 'book'],
							rules: ['rule 1', 'rule 2'],
							alternativeRules: ['alt rule 1', 'alt rule 2'],
							owner: testUser._id});
						game.save(function (err, user) {
							if (err) return done(err);
							game2.save(function (err, user) {
								if (err) return done(err);
								init.initFeaturedGames();
								init.initTopGames();
								return done();
							});
						});
					});
				});
			});
		});
	});
});
<commit_msg>fixed testdata typoes<commit_after>var mongoose = require('mongoose');
var testConfig = require('./test.config');
var User = require('../server/models/user/user.model');
var Game = require('../server/models/game/game.model');
var dbConfig = require('../server/config/db.config');
var clearDB = require('mocha-mongoose')(dbConfig.DATABASE.test, {noClear: true});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // Done to accept self signed HTTPS certfificate
var init = require('../server/init/init');

function importTest (name, path) {
	describe(name, function () {
		require(path);
	});
}

describe('Starting tests', function () {
	before(function (done) {
		if (mongoose.connection.db) return done();
		mongoose.connect(dbConfig.DATABASE.test, function (err) {
			if (err) return done(err);
			clearDB(done);
		});
	});
	// MODELS
	importTest('Testing user.model', './models/user/user.model.test');
	importTest('Testing game.model', './models/game/game.model.test');
	importTest('Testing comment.model', './models/comment/comment.model.test');
	importTest('Testing rating.model', './models/rating/rating.model.test');
	importTest('Testing review.model', './models/review/review.model.test');
	importTest('Testing unpublishedGame.model', './models/unpublishedGame/unpublishedGame.model.test');
	// ROUTES
	importTest('Testing user.route', './routes/user/user.route.test');
	importTest('Testing game.route', './routes/game/game.route.test');
	importTest('Testing login.route', './routes/login/login.route.test');
	importTest('Testing review.route', './routes/review/review.route.test');
	importTest('Testing unpublishedGame.route', './routes/unpublishedGame/unpublishedGame.route.test');

	after(function (done) {
		mongoose.connection.db.dropDatabase(function (err) {
			if (err) return done(err);
			var testUser = new User(testConfig.USER_TESTUSER);
			testUser.save(function (err) {
				if (err) return done(err);
				var testUser2 = new User(testConfig.USER_TESTUSER2);
				testUser2.save(function (err) {
					if (err) return done(err);
					Game.ensureIndexes(function (err) {
						if (err) return done(err);
						var game = new Game(
							{title: 'test game',
							shortDescription: 'this is a short description',
							pieces: {
								singles: 4,
								doubles: 5,
								triples: 6
							},
							isPlayableWithMorePlayers: true,
							isPlayableInTeams: true,
							sumOfVotes: 4,
							numberOfVotes: 1,
							rating: 4,
							numberOfPlayers: 3,
							images: ['http://www.magination.no/images/game1_crop.jpg',
									'http://www.magination.no/images/game2_crop.jpg',
									'http://www.magination.no/images/game3_crop.jpg'],
							otherObjects: ['cup', 'book'],
							rules: ['rule 1', 'rule 2'],
							alternativeRules: ['alt rule 1', 'alt rule 2'],
							owner: testUser._id});
						var game2 = new Game(
							{title: 'test game 2',
							shortDescription: 'this is a short description 2',
							pieces: {
								singles: 4,
								doubles: 5,
								triples: 6
							},
							isPlayableWithMorePlayers: true,
							isPlayableInTeams: true,
							sumOfVotes: 3,
							numberOfVotes: 1,
							rating: 3,
							numberOfPlayers: 3,
							images: ['http://www.magination.no/images/game1_crop.jpg',
									'http://www.magination.no/images/game2_crop.jpg',
									'http://www.magination.no/images/game3_crop.jpg'],
							otherObjects: ['cup', 'book'],
							rules: ['rule 1', 'rule 2'],
							alternativeRules: ['alt rule 1', 'alt rule 2'],
							owner: testUser._id});
						game.save(function (err, user) {
							if (err) return done(err);
							game2.save(function (err, user) {
								if (err) return done(err);
								init.initFeaturedGames();
								return done();
							});
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


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

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-shopify-settings-variables', function () {

    /* Write tests here */

    it('replace single variable in value', function (done) {
        test('a{ color: $(headline_color); }',
            'a{ color: {{ settings.headline_color }}; }', { }, done);
    });

    it('replace multiple variables in multiple values', function (done) {
        test('a{ color: $(headline_color); ' +
                'background-color: $(healine_bg_color); }',
             'a{ color: {{ settings.headline_color }}; ' +
                'background-color: {{ settings.healine_bg_color }}; }',
                { }, done);
    });

    it('replace single variable in value with pixel unit', function (done) {
        test('body{ font-size: $(headline_size)px; }',
             'body{ font-size: {{ settings.headline_size }}px; }', { }, done);
    });

    it('replace single variable in value with liquid filter', function (done) {
        test('a{ font-size: $(headline_size | divided_by: 2)px; }',
             'a{ font-size: {{ settings.headline_size | divided_by: 2 }}px; }',
                { }, done);
    });

    it('replace single variable in value with liquid string filter',
        function (done) {
            test('a{ font-family: $(font_family | replace: \'+\', \' \'); }',
                'a{ font-family: {{ settings.font_family ' +
                    '| replace: \'+\', \' \' }}; }',
                { }, done);
        });

    it('replace single variable in value which has multiple variables',
        function (done) {
            test('a{ border-bottom: 1px dotted $(border_color); }',
                'a{ border-bottom: 1px dotted {{ settings.border_color }}; }',
                { }, done);
        });

    it('replace single variable in value when there is quotes',
        function (done) {
            test('a{ font-family: "$(headline_google_webfont_font)"; }',
                'a{ font-family: ' +
                    '"{{ settings.headline_google_webfont_font }}"; }',
                { }, done);
        });

    it('replace single variable in value when there is parenthesis',
        function (done) {
            test('a{ background: rgba($(header_bg_color), 0.9); }',
                'a{ background: rgba({{ settings.header_bg_color }}, 0.9); }',
                { }, done);
        });

    describe('replace background url with asset_url filter', function () {
        it('no quote', function (done) {
            test('a{ background: url(logo.png); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('with space', function (done) {
            test('a{ background: url( logo.png ); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('single quote', function (done) {
            test('a{ background: url(\'logo.png\'); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('double quote', function (done) {
            test('a{ background: url("logo.png"); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('only replace url', function (done) {
            test('a{ background-image: url(logo.png) no-repeat; }',
                'a{ background-image: url({{ "logo.png" | asset_url }}) ' +
                    'no-repeat; }',
                { }, done);
        });

        it('multiple url', function (done) {
            test('a{ background: url("logo.png"), url(logo@2x.jpg); }',
                'a{ background: url({{ "logo.png" | asset_url }}), ' +
                    'url({{ "logo@2x.jpg" | asset_url }}); }',
                { }, done);
        });

        it('not replace url with full path', function (done) {
            test('a{ background: url("http://a.com/logo.png"); }',
                'a{ background: url("http://a.com/logo.png"); }',
                { }, done);
        });

        it('not replace url with data uri', function (done) {
            test('a{ background: url(data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7); }',
                'a{ background: url(data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7); }',
                { }, done);
        });
    });
});
<commit_msg>fix eslint error<commit_after>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-shopify-settings-variables', function () {

    /* Write tests here */

    it('replace single variable in value', function (done) {
        test('a{ color: $(headline_color); }',
            'a{ color: {{ settings.headline_color }}; }', { }, done);
    });

    it('replace multiple variables in multiple values', function (done) {
        test('a{ color: $(headline_color); ' +
                'background-color: $(healine_bg_color); }',
             'a{ color: {{ settings.headline_color }}; ' +
                'background-color: {{ settings.healine_bg_color }}; }',
                { }, done);
    });

    it('replace single variable in value with pixel unit', function (done) {
        test('body{ font-size: $(headline_size)px; }',
             'body{ font-size: {{ settings.headline_size }}px; }', { }, done);
    });

    it('replace single variable in value with liquid filter', function (done) {
        test('a{ font-size: $(headline_size | divided_by: 2)px; }',
             'a{ font-size: {{ settings.headline_size | divided_by: 2 }}px; }',
                { }, done);
    });

    it('replace single variable in value with liquid string filter',
        function (done) {
            test('a{ font-family: $(font_family | replace: \'+\', \' \'); }',
                'a{ font-family: {{ settings.font_family ' +
                    '| replace: \'+\', \' \' }}; }',
                { }, done);
        });

    it('replace single variable in value which has multiple variables',
        function (done) {
            test('a{ border-bottom: 1px dotted $(border_color); }',
                'a{ border-bottom: 1px dotted {{ settings.border_color }}; }',
                { }, done);
        });

    it('replace single variable in value when there is quotes',
        function (done) {
            test('a{ font-family: "$(headline_google_webfont_font)"; }',
                'a{ font-family: ' +
                    '"{{ settings.headline_google_webfont_font }}"; }',
                { }, done);
        });

    it('replace single variable in value when there is parenthesis',
        function (done) {
            test('a{ background: rgba($(header_bg_color), 0.9); }',
                'a{ background: rgba({{ settings.header_bg_color }}, 0.9); }',
                { }, done);
        });

    describe('replace background url with asset_url filter', function () {
        it('no quote', function (done) {
            test('a{ background: url(logo.png); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('with space', function (done) {
            test('a{ background: url( logo.png ); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('single quote', function (done) {
            test('a{ background: url(\'logo.png\'); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('double quote', function (done) {
            test('a{ background: url("logo.png"); }',
                'a{ background: url({{ "logo.png" | asset_url }}); }',
                { }, done);
        });

        it('only replace url', function (done) {
            test('a{ background-image: url(logo.png) no-repeat; }',
                'a{ background-image: url({{ "logo.png" | asset_url }}) ' +
                    'no-repeat; }',
                { }, done);
        });

        it('multiple url', function (done) {
            test('a{ background: url("logo.png"), url(logo@2x.jpg); }',
                'a{ background: url({{ "logo.png" | asset_url }}), ' +
                    'url({{ "logo@2x.jpg" | asset_url }}); }',
                { }, done);
        });

        it('not replace url with full path', function (done) {
            test('a{ background: url("http://a.com/logo.png"); }',
                'a{ background: url("http://a.com/logo.png"); }',
                { }, done);
        });

        it('not replace url with data uri', function (done) {
            test('a{ background: url(data:image/gif;base64,' +
                'R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o' +
                '/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
                'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVIC' +
                'SOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhw' +
                'FUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7); }',
                'a{ background: url(data:image/gif;base64,' +
                'R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o' +
                '/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
                'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVIC' +
                'SOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhw' +
                'FUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7); }',
                { }, done);
        });
    });
});
<|endoftext|>


<commit_before>import * as color from '../src/color'

const REPEAT = 100
const CANVAS = makeCanvas()
const CONTEXT = makeContext(CANVAS)
const HOLDER = document.createElement('div')

function makeCanvas() {
  const canvas = document.createElement('canvas')
  canvas.width = 1
  canvas.height = 1
  return canvas
}

function makeContext(canvas) {
  const context = canvas.getContext('2d')
  context.imageSmoothingEnabled = false
  return context
}

function getPixelFromURL(color) {
  return new Promise(function(resolve) {
    const image = new Image()
    image.addEventListener('load', function() {
      const canvas = makeCanvas()
      const context = makeContext(canvas)
      context.drawImage(image, 0, 0)
      const imageData = context.getImageData(0, 0, 1, 1)
      const data = imageData.data

      resolve(data)
    })
    image.src = `https://dummyimage.com/1x1/${color}/${color}.png`
  })
}

function getPixelFromCanvas(str) {
  CONTEXT.fillStyle = str
  CONTEXT.fillRect(0, 0, 1, 1)
  return CONTEXT.getImageData(0, 0, 1, 1).data
}

function getFillStyleFromCanvas(str) {
  CONTEXT.fillStyle = str
  return CONTEXT.fillStyle
}

function getStringFromDOM(hex) {
  HOLDER.style.backgroundColor = hex
  return window.getComputedStyle(HOLDER).backgroundColor
}

function rand255() {
  return Math.floor(Math.random() * 256)
}

function randSpace() {
  return Math.random() > 0.5 ? '' : ' '
}

function randomBoolean() {
  return Math.random() > 0.5 ? true : false
}

function makeString(r = rand255(), g = rand255(), b = rand255(), a) {
  const hasA = (a !== undefined) ? a : randomBoolean()
  let str =  `rgb${hasA ? 'a' : ''}(${randSpace()}${r}${randSpace()},${randSpace()}${g}${randSpace()},${randSpace()}${b}${randSpace()}`

  if (hasA) {
    str += `,${randSpace()}${Math.random()}${randSpace()}`
  }
  str += ')'
  return str
}

describe('color', function() {
  before(function() {
    document.body.appendChild(HOLDER)
  })

  after(function() {
    document.body.removeChild(HOLDER)
  })

  describe('stringToHex', function() {
    it('returns null when theres no match', function() {
      expect(color.stringToHex('')).to.be.null
    })

    it('converts rgb(x,x,x) and rgba(x,x,x,x) to #XXXXXX', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const str = makeString(r, g, b)
        const hex = color.stringToHex(str)
        const data = getPixelFromCanvas(hex)
        expect(data[0]).to.equal(r)
        expect(data[1]).to.equal(g)
        expect(data[2]).to.equal(b)
      }
    })
  })

  describe('rgbToUint', function() {
    it('converts seperate r, g, and b uints and converts to a single uint', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = uint.toString(16)
        const strR = str.slice(0, str.length - 4) || 0
        const strG = str.slice(str.length - 4, str.length - 2)
        const strB = str.slice(str.length - 2, str.length)
        expect(parseInt(`0x${strR}`)).to.equal(r)
        expect(parseInt(`0x${strG}`)).to.equal(g)
        expect(parseInt(`0x${strB}`)).to.equal(b)
      }
    })
  })

  describe('red, green, blue', function() {
    it('they get the appropriate color value from a uint as a uint', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        expect(color.red(uint)).to.equal(r)
        expect(color.green(uint)).to.equal(g)
        expect(color.blue(uint)).to.equal(b)
      }
    })
  })

  describe('uintToRGBString', function() {
    it('converts a uint to rgb(x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBString(uint)
        const data = getPixelFromCanvas(str)
        expect(data[0]).to.equal(r)
        expect(data[1]).to.equal(g)
        expect(data[2]).to.equal(b)
      }
    })
  })

  describe('uintToRGBAString', function() {
    it('converts a uint with alpha to rgba(x,x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const a = Math.random()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBAString(uint, a)
        const split = getStringFromDOM(str).split('(')[1].split(',')
        expect(parseInt(split[0])).to.equal(r)
        expect(parseInt(split[1])).to.equal(g)
        expect(parseInt(split[2])).to.equal(b)
        const newA = parseFloat(split[3] || 1)
        expect(Math.abs(newA - a)).to.be.below(0.004)
      }
    })

    it('converts a uint with default alpha to rgba(x,x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBAString(uint)
        const split = getStringFromDOM(str).split('(')[1].split(',')
        expect(parseInt(split[0])).to.equal(r)
        expect(parseInt(split[1])).to.equal(g)
        expect(parseInt(split[2])).to.equal(b)
        expect(parseInt(split[3])).to.be.NaN
      }
    })
  })

  describe('uintToHex', function() {
    it('converts a uint to #XXXXXX format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToHex(uint)
        const data = getPixelFromCanvas(str)

        expect(Math.abs(data[0] - r)).to.be.below(2)
        expect(Math.abs(data[1] - g)).to.be.below(2)
        expect(Math.abs(data[2] - b)).to.be.below(2)
      }
    })
  })

  describe('rgbToBrightness', function() {
    it('converts seperate r, g, and b values to a brightness ratio between 0 and 1', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const brightness = color.rgbToBrightness(r, g, b)

        expect((r + g + b) / (255 * 3)).to.equal(brightness)
      }
    })
  })
})
<commit_msg>add hexToUint method<commit_after>import * as color from '../src/color'

const REPEAT = 100
const CANVAS = makeCanvas()
const CONTEXT = makeContext(CANVAS)
const HOLDER = document.createElement('div')

function makeCanvas() {
  const canvas = document.createElement('canvas')
  canvas.width = 1
  canvas.height = 1
  return canvas
}

function makeContext(canvas) {
  const context = canvas.getContext('2d')
  context.imageSmoothingEnabled = false
  return context
}

function getPixelFromURL(color) {
  return new Promise(function(resolve) {
    const image = new Image()
    image.addEventListener('load', function() {
      const canvas = makeCanvas()
      const context = makeContext(canvas)
      context.drawImage(image, 0, 0)
      const imageData = context.getImageData(0, 0, 1, 1)
      const data = imageData.data

      resolve(data)
    })
    image.src = `https://dummyimage.com/1x1/${color}/${color}.png`
  })
}

function getPixelFromCanvas(str) {
  CONTEXT.fillStyle = str
  CONTEXT.fillRect(0, 0, 1, 1)
  return CONTEXT.getImageData(0, 0, 1, 1).data
}

function getFillStyleFromCanvas(str) {
  CONTEXT.fillStyle = str
  return CONTEXT.fillStyle
}

function getStringFromDOM(hex) {
  HOLDER.style.backgroundColor = hex
  return window.getComputedStyle(HOLDER).backgroundColor
}

function rand255() {
  return Math.floor(Math.random() * 256)
}

function randSpace() {
  return Math.random() > 0.5 ? '' : ' '
}

function randomBoolean() {
  return Math.random() > 0.5 ? true : false
}

function makeString(r = rand255(), g = rand255(), b = rand255(), a) {
  const hasA = (a !== undefined) ? a : randomBoolean()
  let str =  `rgb${hasA ? 'a' : ''}(${randSpace()}${r}${randSpace()},${randSpace()}${g}${randSpace()},${randSpace()}${b}${randSpace()}`

  if (hasA) {
    str += `,${randSpace()}${Math.random()}${randSpace()}`
  }
  str += ')'
  return str
}

describe('color', function() {
  before(function() {
    document.body.appendChild(HOLDER)
  })

  after(function() {
    document.body.removeChild(HOLDER)
  })

  describe('stringToHex', function() {
    it('returns null when theres no match', function() {
      expect(color.stringToHex('')).to.be.null
    })

    it('converts rgb(x,x,x) and rgba(x,x,x,x) to #XXXXXX', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const str = makeString(r, g, b)
        const hex = color.stringToHex(str)
        const data = getPixelFromCanvas(hex)
        expect(data[0]).to.equal(r)
        expect(data[1]).to.equal(g)
        expect(data[2]).to.equal(b)
      }
    })
  })

  describe('rgbToUint', function() {
    it('converts seperate r, g, and b uints and converts to a single uint', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = uint.toString(16)
        const strR = str.slice(0, str.length - 4) || 0
        const strG = str.slice(str.length - 4, str.length - 2)
        const strB = str.slice(str.length - 2, str.length)
        expect(parseInt(`0x${strR}`)).to.equal(r)
        expect(parseInt(`0x${strG}`)).to.equal(g)
        expect(parseInt(`0x${strB}`)).to.equal(b)
      }
    })
  })

  describe('red, green, blue', function() {
    it('they get the appropriate color value from a uint as a uint', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        expect(color.red(uint)).to.equal(r)
        expect(color.green(uint)).to.equal(g)
        expect(color.blue(uint)).to.equal(b)
      }
    })
  })

  describe('uintToRGBString', function() {
    it('converts a uint to rgb(x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBString(uint)
        const data = getPixelFromCanvas(str)
        expect(data[0]).to.equal(r)
        expect(data[1]).to.equal(g)
        expect(data[2]).to.equal(b)
      }
    })
  })

  describe('uintToRGBAString', function() {
    it('converts a uint with alpha to rgba(x,x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const a = Math.random()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBAString(uint, a)
        const split = getStringFromDOM(str).split('(')[1].split(',')
        expect(parseInt(split[0])).to.equal(r)
        expect(parseInt(split[1])).to.equal(g)
        expect(parseInt(split[2])).to.equal(b)
        const newA = parseFloat(split[3] || 1)
        expect(Math.abs(newA - a)).to.be.below(0.004)
      }
    })

    it('converts a uint with default alpha to rgba(x,x,x,x) format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToRGBAString(uint)
        const split = getStringFromDOM(str).split('(')[1].split(',')
        expect(parseInt(split[0])).to.equal(r)
        expect(parseInt(split[1])).to.equal(g)
        expect(parseInt(split[2])).to.equal(b)
        expect(parseInt(split[3])).to.be.NaN
      }
    })
  })

  describe('uintToHex', function() {
    it('converts a uint to #XXXXXX format', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const uint = color.rgbToUint(r, g, b)
        const str = color.uintToHex(uint)
        const data = getPixelFromCanvas(str)

        expect(Math.abs(data[0] - r)).to.be.below(2)
        expect(Math.abs(data[1] - g)).to.be.below(2)
        expect(Math.abs(data[2] - b)).to.be.below(2)
      }
    })
  })

  describe('rgbToBrightness', function() {
    it('converts seperate r, g, and b values to a brightness ratio between 0 and 1', function() {
      for(let i = 0; i < REPEAT; i++) {
        const r = rand255()
        const g = rand255()
        const b = rand255()
        const brightness = color.rgbToBrightness(r, g, b)

        expect((r + g + b) / (255 * 3)).to.equal(brightness)
      }
    })
  })

  describe('hexToUint', function() {
    it('converts a hex string into a uint', function() {
      for(let i = 0; i < REPEAT; i++) {
        const red = rand255()
        const green = rand255()
        const blue = rand255()
        const uint = color.rgbToUint(red, green, blue)
        let hex = color.uintToHex(uint)
        if (i % 3 === 1) {
          hex = hex.replace('#', '')
        } else if (i % 3 === 2) {
          hex = hex.replace('#', '0x')
        }
        expect(color.hexToUint(hex)).to.equal(uint)
      }
    })
  })
})
<|endoftext|>


<commit_before>if (typeof window === 'undefined') {
  var expect = require('expect.js');
  var GeoJSON = require('../geojson');
}

describe('GeoJSON', function() {

  describe('#defaults', function(){
    it('exists as a public object of GeoJSON', function(){
      expect(typeof GeoJSON.defaults).to.eql('object');
    });

    it('is initially empty', function() {
      var count = 0;
      for(var key in GeoJSON.defaults) {
        if(GeoJSON.defaults.hasOwnProperty(key)) {
          count++;
        }
      }

      expect(count).to.be(0);
    });
  });

  describe('#parse', function(){
    var data;

    before(function() {
      // Sample Data
      data = [
        { name: 'Location A', category: 'Store', lat: 39.984, lng: -75.343, street: 'Market' },
        { name: 'Location B', category: 'House', lat: 39.284, lng: -75.833, street: 'Broad' },
        { name: 'Location C', category: 'Office', lat: 39.123, lng: -74.534, street: 'South' }
      ];
    });

    it('returns output with the same number of features as the input', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      expect(output.features.length).to.be(3);
    });

    it('doesn\'t include geometry fields in feature properties', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      output.features.forEach(function(feature){
        expect(feature.properties.lat).to.not.be.ok();
        expect(feature.properties.lng).to.not.be.ok();
      });
    });

    it('includes all properties besides geometry attributes when include or exclude isn\'t set', function() {
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.category).to.be.ok();
        expect(feature.properties.street).to.be.ok();
      });
    });

    it('only includes attributes that are listed in the include parameter', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], include: ['name']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.category).to.not.be.ok();
        expect(feature.properties.street).to.not.be.ok();
      });
    });

    it('does not include attributes listed in the exclude parameter', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], exclude: ['name']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.not.be.ok();
        expect(feature.properties.category).to.be.ok();
        expect(feature.properties.street).to.be.ok();
      });
    });

    it('handles Point geom with x,y stored in one or two attributes', function(){
      var twoAttrs = [{ name: 'test location', y: -74, x: 39.0, foo: 'bar' }];

      var geoTwoAttrs = GeoJSON.parse(twoAttrs, {Point: ['x', 'y']});

      expect(geoTwoAttrs.features[0].geometry.coordinates[0]).to.be(-74);
      expect(geoTwoAttrs.features[0].geometry.coordinates[1]).to.be(39.0);

      var oneAttr = [{ name: 'test location', coords: [-74, 39], foo: 'bar'}];

      var geoOneAttr = GeoJSON.parse(oneAttr, {Point: 'coords'});

      expect(geoOneAttr.features[0].geometry.coordinates[0]).to.be(-74);
      expect(geoOneAttr.features[0].geometry.coordinates[1]).to.be(39.0);
    });

    it('parses data with different geometry types', function(){
      // Based off example spec at http://geojson.org/geojson-spec.html
      var data2 = [
        {
          x: 0.5,
          y: 102.0,
          prop0: 'value0'
        },
        {
          line: [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]],
          prop0: 'value0',
          prop1: 0.0
        },
        {
          polygon: [
            [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
          ],
          prop0: 'value0',
          prop1: {"this": "that"}
        }
      ];

      var output = GeoJSON.parse(data2, {'Point': ['x', 'y'], 'LineString': 'line', 'Polygon': 'polygon'});

      expect(output.features.length).to.be(3);

      output.features.forEach(function(feature){
        if(feature.geometry.type === 'Point') {
          expect(feature.geometry.coordinates[1]).to.be(0.5);
          expect(feature.geometry.coordinates[0]).to.be(102);
          expect(feature.properties.prop0).to.be("value0");
        } else if (feature.geometry.type === 'LineString') {
          expect(feature.geometry.coordinates.length).to.be(4);
          expect(feature.geometry.coordinates[0][1]).to.be(0);
          expect(feature.geometry.coordinates[0][0]).to.be(102);
          expect(feature.geometry.coordinates[3][1]).to.be(1);
          expect(feature.geometry.coordinates[3][0]).to.be(105);
          expect(feature.properties.prop0).to.be("value0");
          expect(feature.properties.prop1).to.be(0);
        } else if (feature.geometry.type === 'Polygon') {
          expect(feature.geometry.coordinates[0].length).to.be(5);
          expect(feature.geometry.coordinates[0][0][1]).to.be(0);
          expect(feature.geometry.coordinates[0][0][0]).to.be(100);
          expect(feature.geometry.coordinates[0][4][1]).to.be(0);
          expect(feature.geometry.coordinates[0][4][0]).to.be(100);
          expect(feature.properties.prop0).to.be("value0");
          expect(feature.properties.prop1['this']).to.be('that');
        }
      });
    });

    it('uses the default settings when they have been specified', function(){
      GeoJSON.defaults = {
        Point: ['lat', 'lng'],
        include: ['name'],
        crs: 'urn:ogc:def:crs:EPSG::4326'
      };

      var output = GeoJSON.parse(data);

      expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.lat).to.not.be.ok();
        expect(feature.properties.lng).to.not.be.ok();
        expect(feature.geometry.coordinates[0]).to.be.ok();
        expect(feature.geometry.coordinates[1]).to.be.ok();
      });

      it('only applies default settings that haven\'t been set in params', function(){
        var output = GeoJSON.parse(data, {include: ['category', 'street']});

        expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

        output.features.forEach(function(feature){
          expect(feature.properties.name).to.not.be.ok();
          expect(feature.properties.category).to.be.ok();
          expect(feature.properties.street).to.be.ok();
        });
      });

      it('keeps the default settings until they have been explicity reset', function(){
        var output = GeoJSON.parse(data);

        expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

        output.features.forEach(function(feature){
          expect(feature.properties.name).to.be.ok();
          expect(feature.properties.lat).to.not.be.ok();
          expect(feature.properties.lng).to.not.be.ok();
          expect(feature.geometry.coordinates[0]).to.be.ok();
          expect(feature.geometry.coordinates[1]).to.be.ok();
        });
      });

      GeoJSON.defaults = {};
    });

    it("adds 'bbox' and/or 'crs' to the output if either is specified in the parameters", function(){
      var output = GeoJSON.parse(data, {
        Point: ['lat', 'lng'],
        bbox: [-75, 39, -76, 40],
        crs: 'urn:ogc:def:crs:EPSG::4326'});

      expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');
      expect(output.bbox[0]).to.be(-75);
      expect(output.bbox[1]).to.be(39);
      expect(output.bbox[2]).to.be(-76);
      expect(output.bbox[3]).to.be(40);
    });

    it("adds extra attributes if extra param is set", function() {
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], extra: { 'foo':'bar', 'bar':'foo'}});

      output.features.forEach(function(feature){
        expect(feature.properties.foo).to.be('bar');
        expect(feature.properties.bar).to.be('foo');
      });

      var output2 = GeoJSON.parse(data, {
        Point: ['lat', 'lng'],
        extra: {
          style: {
            "color": "#ff7800",
            "weight": 5,
            "opacity": 0.65
          }
        }
      });

      output2.features.forEach(function(feature) {
        expect(feature.properties.style.color).to.be('#ff7800');
        expect(feature.properties.style.weight).to.be(5);
        expect(feature.properties.style.opacity).to.be(0.65);
      });
    });

    it("throws an error if the objects parameter is empty", function(){
      var data = [];

      expect(function(){ GeoJSON.parse(data); }).to.throwException(/No data found/);
    });

    it("throws an error if no geometry attributes have been specified", function() {
      expect(function(){ GeoJSON.parse(data); }).to.throwException(/No geometry attributes specified/);
    });

  });
});<commit_msg>Added a few more expects<commit_after>if (typeof window === 'undefined') {
  var expect = require('expect.js');
  var GeoJSON = require('../geojson');
}

describe('GeoJSON', function() {

  describe('#defaults', function(){
    it('exists as a public object of GeoJSON', function(){
      expect(typeof GeoJSON.defaults).to.eql('object');
    });

    it('is initially empty', function() {
      var count = 0;
      for(var key in GeoJSON.defaults) {
        if(GeoJSON.defaults.hasOwnProperty(key)) {
          count++;
        }
      }

      expect(count).to.be(0);
    });
  });

  describe('#parse', function(){
    var data;

    before(function() {
      // Sample Data
      data = [
        { name: 'Location A', category: 'Store', lat: 39.984, lng: -75.343, street: 'Market' },
        { name: 'Location B', category: 'House', lat: 39.284, lng: -75.833, street: 'Broad' },
        { name: 'Location C', category: 'Office', lat: 39.123, lng: -74.534, street: 'South' }
      ];
    });

    it('returns output with the same number of features as the input', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      expect(output.features.length).to.be(3);
    });

    it('doesn\'t include geometry fields in feature properties', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      output.features.forEach(function(feature){
        expect(feature.properties.lat).to.not.be.ok();
        expect(feature.properties.lng).to.not.be.ok();
        expect(feature.geometry.coordinates[0]).to.be.ok();
        expect(feature.geometry.coordinates[1]).to.be.ok();
      });
    });

    it('includes all properties besides geometry attributes when include or exclude isn\'t set', function() {
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.category).to.be.ok();
        expect(feature.properties.street).to.be.ok();
      });
    });

    it('only includes attributes that are listed in the include parameter', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], include: ['name']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.category).to.not.be.ok();
        expect(feature.properties.street).to.not.be.ok();
      });
    });

    it('does not include attributes listed in the exclude parameter', function(){
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], exclude: ['name']});

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.not.be.ok();
        expect(feature.properties.category).to.be.ok();
        expect(feature.properties.street).to.be.ok();
      });
    });

    it('handles Point geom with x,y stored in one or two attributes', function(){
      var twoAttrs = [{ name: 'test location', y: -74, x: 39.0, foo: 'bar' }];

      var geoTwoAttrs = GeoJSON.parse(twoAttrs, {Point: ['x', 'y']});

      expect(geoTwoAttrs.features[0].geometry.coordinates[0]).to.be(-74);
      expect(geoTwoAttrs.features[0].geometry.coordinates[1]).to.be(39.0);

      var oneAttr = [{ name: 'test location', coords: [-74, 39], foo: 'bar'}];

      var geoOneAttr = GeoJSON.parse(oneAttr, {Point: 'coords'});

      expect(geoOneAttr.features[0].geometry.coordinates[0]).to.be(-74);
      expect(geoOneAttr.features[0].geometry.coordinates[1]).to.be(39.0);
    });

    it('parses data with different geometry types', function(){
      // Based off example spec at http://geojson.org/geojson-spec.html
      var data2 = [
        {
          x: 0.5,
          y: 102.0,
          prop0: 'value0'
        },
        {
          line: [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]],
          prop0: 'value0',
          prop1: 0.0
        },
        {
          polygon: [
            [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
          ],
          prop0: 'value0',
          prop1: {"this": "that"}
        }
      ];

      var output = GeoJSON.parse(data2, {'Point': ['x', 'y'], 'LineString': 'line', 'Polygon': 'polygon'});

      expect(output.features.length).to.be(3);

      output.features.forEach(function(feature){
        if(feature.geometry.type === 'Point') {
          expect(feature.geometry.coordinates[1]).to.be(0.5);
          expect(feature.geometry.coordinates[0]).to.be(102);
          expect(feature.properties.prop0).to.be("value0");
        } else if (feature.geometry.type === 'LineString') {
          expect(feature.geometry.coordinates.length).to.be(4);
          expect(feature.geometry.coordinates[0][1]).to.be(0);
          expect(feature.geometry.coordinates[0][0]).to.be(102);
          expect(feature.geometry.coordinates[3][1]).to.be(1);
          expect(feature.geometry.coordinates[3][0]).to.be(105);
          expect(feature.properties.prop0).to.be("value0");
          expect(feature.properties.prop1).to.be(0);
        } else if (feature.geometry.type === 'Polygon') {
          expect(feature.geometry.coordinates[0].length).to.be(5);
          expect(feature.geometry.coordinates[0][0][1]).to.be(0);
          expect(feature.geometry.coordinates[0][0][0]).to.be(100);
          expect(feature.geometry.coordinates[0][4][1]).to.be(0);
          expect(feature.geometry.coordinates[0][4][0]).to.be(100);
          expect(feature.properties.prop0).to.be("value0");
          expect(feature.properties.prop1['this']).to.be('that');
        }
      });
    });

    it('uses the default settings when they have been specified', function(){
      GeoJSON.defaults = {
        Point: ['lat', 'lng'],
        include: ['name'],
        crs: 'urn:ogc:def:crs:EPSG::4326'
      };

      var output = GeoJSON.parse(data);

      expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

      output.features.forEach(function(feature){
        expect(feature.properties.name).to.be.ok();
        expect(feature.properties.lat).to.not.be.ok();
        expect(feature.properties.lng).to.not.be.ok();
        expect(feature.geometry.coordinates[0]).to.be.ok();
        expect(feature.geometry.coordinates[1]).to.be.ok();
      });

      it('only applies default settings that haven\'t been set in params', function(){
        var output = GeoJSON.parse(data, {include: ['category', 'street']});

        expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

        output.features.forEach(function(feature){
          expect(feature.properties.name).to.not.be.ok();
          expect(feature.properties.category).to.be.ok();
          expect(feature.properties.street).to.be.ok();
        });
      });

      it('keeps the default settings until they have been explicity reset', function(){
        var output = GeoJSON.parse(data);

        expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');

        output.features.forEach(function(feature){
          expect(feature.properties.name).to.be.ok();
          expect(feature.properties.lat).to.not.be.ok();
          expect(feature.properties.lng).to.not.be.ok();
          expect(feature.geometry.coordinates[0]).to.be.ok();
          expect(feature.geometry.coordinates[1]).to.be.ok();
        });
      });

      GeoJSON.defaults = {};
    });

    it("adds 'bbox' and/or 'crs' to the output if either is specified in the parameters", function(){
      var output = GeoJSON.parse(data, {
        Point: ['lat', 'lng'],
        bbox: [-75, 39, -76, 40],
        crs: 'urn:ogc:def:crs:EPSG::4326'});

      expect(output.crs.properties.name).to.be('urn:ogc:def:crs:EPSG::4326');
      expect(output.bbox[0]).to.be(-75);
      expect(output.bbox[1]).to.be(39);
      expect(output.bbox[2]).to.be(-76);
      expect(output.bbox[3]).to.be(40);
    });

    it("adds extra attributes if extra param is set", function() {
      var output = GeoJSON.parse(data, {Point: ['lat', 'lng'], extra: { 'foo':'bar', 'bar':'foo'}});

      output.features.forEach(function(feature){
        expect(feature.properties.foo).to.be('bar');
        expect(feature.properties.bar).to.be('foo');
      });

      var output2 = GeoJSON.parse(data, {
        Point: ['lat', 'lng'],
        extra: {
          style: {
            "color": "#ff7800",
            "weight": 5,
            "opacity": 0.65
          }
        }
      });

      output2.features.forEach(function(feature) {
        expect(feature.properties.style.color).to.be('#ff7800');
        expect(feature.properties.style.weight).to.be(5);
        expect(feature.properties.style.opacity).to.be(0.65);
      });
    });

    it("throws an error if the objects parameter is empty", function(){
      var data = [];

      expect(function(){ GeoJSON.parse(data); }).to.throwException(/No data found/);
    });

    it("throws an error if no geometry attributes have been specified", function() {
      expect(function(){ GeoJSON.parse(data); }).to.throwException(/No geometry attributes specified/);
    });

  });
});<|endoftext|>


<commit_before>;(function() {
  var marks = {
    openingBrackets: '‘“（〔［｛〈《「『【｟〘〖«〝'.split('')
  , closeingBrackets: '’”）〕］｝〉》」』】｠〙〗»	〟'.split('')
  , middleDots: '・'.split('')
  , fullStops: '。．'.split('')
  , commas: '、，：；'.split('')

  , middleBefore: ['M']
  , middleAfter: ['M']
  , headBefore: ['']
  , headAfter: ['M']
  , endBefore: ['M']
  , endAfter: ['']
  }

  var rules = [
    {
      name: 'a'
    , detail: '\
        When closing brackets (cl-02) come immediately after commas (cl-07) \
        or full stops (cl-06), remove the default half em space between them \
        and, in principle, add a half em space after the closing brackets \
        (see Fig. 3.13 ①).'
    , patterns: [
        {
          pairs: ['fullStops', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['commas', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }
  , {
      name: 'b'
    , detail: '\
        When commas (cl-07) come immediately after closing brackets (cl-02), \
        remove the default half em space between them and, in principle, \
        add a half em space after the comma. When full stops (cl-06) come \
        immediately after closing brackets (cl-02), remove the default half em space \
        between them and, in middle of a line, add a half em space after the full stop; \
        at the end of a line, in principle, add a half em space after the full \
        stop (see Fig. 3.13 ②).'
    , patterns: [
        {
          pairs: ['closeingBrackets', 'commas']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['closeingBrackets', 'commas']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'c'
    , detail: '\
        When opening brackets (cl-01) come immediately after commas (cl-07), \
        in principle, add a half em space between them (see Fig. 3.13 ③). \
        When opening brackets (cl-01) come immediately after full stops (cl-06) \
        in the middle of a line, add a half em space between them. \
        Note that when full stops (cl-06) come in the bottom of lines, \
        in principle, insert a half space after full stops (cl-06). \
        '
    , patterns: [
        {
          pairs: ['commas', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['fullStops', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }
  , {
      name: 'd'
    , detail: '\
        When opening brackets (cl-01) come immediately after \
        closing brackets (cl-02), in principle, add a half em space between \
        them (see Fig. 3.13 ④). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'e'
    , detail: '\
        When opening brackets (cl-01) come immediately after other opening \
        brackets (cl-01), set them solid and, in principle, add a half em space \
        before the first one (see Fig. 3.13 ⑤). \
        '
    , patterns: [
        {
          pairs: ['openingBrackets', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'f'
    , detail: '\
        When closing brackets (cl-02) come immediately after \
        other closing brackets (cl-02), set them solid and, in principle, \
        add a half em space after the last closing bracket (see Fig. 3.13 ⑥). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'g'
    , detail: '\
        When middle dots (cl-05) come immediately after closing brackets (cl-02), \
        in principle, add a quarter em space before the following middle dot \
        (see Fig. 3.13 ⑦). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'middleDots']
        , assetWidth: '1.25' // em
        }
      ]
    }

  , {
      name: 'h'
    , detail: '\
        When opening brackets (cl-01) come immediately after middle dots (cl-05), \
        in principle, add a quarter em space after the preceding middle dot \
        (see Fig. 3.13 ⑦). \
        '
    , patterns: [
        {
          pairs: ['middleDots', 'openingBrackets']
        , assetWidth: '1.25' // em
        }
      , {
          pairs: ['closeingBrackets', 'middleDots', 'openingBrackets']
        , assetWidth: '2' // em
        }
      ]
    }
  ]

  var testContainer = $('#rules-list')
    , combinationTmpl =
          '' +
            '{{COMB}}' +
          ''
  function appendRules() {
    _.each(rules, appendRule.bind(this, testContainer))
  }

  function appendRule(el, rule) {
    var ruleContainer = $('
')
                .append($('
').text(rule.detail))
                .append($('
'))
    ruleContainer.appendTo(el)

    _.each(rule.patterns, appendPattern.bind(this, ruleContainer.find('p')))
  }
  function appendPattern(el, pattern) {
    var pairs = _.map(pattern.pairs, function(markClassName) {
          return _.clone(marks[markClassName])
        })
    var combinations = getAllCombinations(pairs)

    el.attr('data-asset', pattern.assetWidth)

    _.each(combinations, appendCombination.bind(this, el))
  }

  function appendCombination(el, combination) {
    el.append(
      combinationTmpl.replace('{{COMB}}', combination.join('')))
  }

  function getAllCombinations(pairs) {
    if (pairs.length === 1) {
      return _.clone(pairs[0])
    }

    var combinations = []
    var subCombinations = getAllCombinations(pairs.slice(1))
    _.each(pairs[0], function(pair) {
      _.each(subCombinations, function(subCombination) {
        combinations.push([pair].concat(subCombination))
      })
    })
    return combinations
  }

  var emInPx = 20
    , tolerantInPx = 5
    , total = 0
    , passedCnt = 0
    , testEl = $('#test')
  function test() {
    testEl.find('span.wrap').each(function(i, el) {
      total += 1
      el = $(el)
      var asset = el.closest('[data-asset]').data('asset')
        , passed = Math.abs(el.width() - asset * emInPx) < tolerantInPx
      if (passed) {
        el.addClass('passed')
        passedCnt += 1
      }
    })

    testEl.find('[name=passed-count]').text(passedCnt)
    testEl.find('[name=failed-count]').text(total - passedCnt)
  }

  appendRules()
  // Wait for web font's loading
  setTimeout(test, 1000)
}())
<commit_msg>make TODO case failed.<commit_after>;(function() {
  var marks = {
    openingBrackets: '‘“（〔［｛〈《「『【｟〘〖«〝'.split('')
  , closeingBrackets: '’”）〕］｝〉》」』】｠〙〗»〟'.split('')
  , middleDots: '・'.split('')
  , fullStops: '。．'.split('')
  , commas: '、，：；'.split('')

  , middleBefore: ['M']
  , middleAfter: ['M']
  , headBefore: ['']
  , headAfter: ['M']
  , endBefore: ['M']
  , endAfter: ['']
  }

  var rules = [
    {
      name: 'a'
    , detail: '\
        When closing brackets (cl-02) come immediately after commas (cl-07) \
        or full stops (cl-06), remove the default half em space between them \
        and, in principle, add a half em space after the closing brackets \
        (see Fig. 3.13 ①).'
    , patterns: [
        {
          pairs: ['fullStops', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['commas', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }
  , {
      name: 'b'
    , detail: '\
        When commas (cl-07) come immediately after closing brackets (cl-02), \
        remove the default half em space between them and, in principle, \
        add a half em space after the comma. When full stops (cl-06) come \
        immediately after closing brackets (cl-02), remove the default half em space \
        between them and, in middle of a line, add a half em space after the full stop; \
        at the end of a line, in principle, add a half em space after the full \
        stop (see Fig. 3.13 ②).'
    , patterns: [
        {
          pairs: ['closeingBrackets', 'commas']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['closeingBrackets', 'commas']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'c'
    , detail: '\
        When opening brackets (cl-01) come immediately after commas (cl-07), \
        in principle, add a half em space between them (see Fig. 3.13 ③). \
        When opening brackets (cl-01) come immediately after full stops (cl-06) \
        in the middle of a line, add a half em space between them. \
        Note that when full stops (cl-06) come in the bottom of lines, \
        in principle, insert a half space after full stops (cl-06). \
        '
    , patterns: [
        {
          pairs: ['commas', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      , {
          pairs: ['fullStops', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }
  , {
      name: 'd'
    , detail: '\
        When opening brackets (cl-01) come immediately after \
        closing brackets (cl-02), in principle, add a half em space between \
        them (see Fig. 3.13 ④). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'e'
    , detail: '\
        When opening brackets (cl-01) come immediately after other opening \
        brackets (cl-01), set them solid and, in principle, add a half em space \
        before the first one (see Fig. 3.13 ⑤). \
        '
    , patterns: [
        {
          pairs: ['openingBrackets', 'openingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'f'
    , detail: '\
        When closing brackets (cl-02) come immediately after \
        other closing brackets (cl-02), set them solid and, in principle, \
        add a half em space after the last closing bracket (see Fig. 3.13 ⑥). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'closeingBrackets']
        , assetWidth: '1.5' // em
        }
      ]
    }

  , {
      name: 'g'
    , detail: '\
        When middle dots (cl-05) come immediately after closing brackets (cl-02), \
        in principle, add a quarter em space before the following middle dot \
        (see Fig. 3.13 ⑦). \
        '
    , patterns: [
        {
          pairs: ['closeingBrackets', 'middleDots']
        //, assetWidth: '1.25' // em
        , assetWidth: '0' // Let it failed.
        }
      ]
    }

  , {
      name: 'h'
    , detail: '\
        When opening brackets (cl-01) come immediately after middle dots (cl-05), \
        in principle, add a quarter em space after the preceding middle dot \
        (see Fig. 3.13 ⑦). \
        '
    , patterns: [
        {
          pairs: ['middleDots', 'openingBrackets']
        //, assetWidth: '1.25' // em
        , assetWidth: '0' // Let it failed.
        }
      , {
          pairs: ['closeingBrackets', 'middleDots', 'openingBrackets']
        //, assetWidth: '2' // em
        , assetWidth: '0' // Let it failed.
        }
      ]
    }
  ]

  var testContainer = $('#rules-list')
    , combinationTmpl =
          '' +
            '{{COMB}}' +
          ''
  function appendRules() {
    _.each(rules, appendRule.bind(this, testContainer))
  }

  function appendRule(el, rule) {
    var ruleContainer = $('
')
                .append($('
').text(rule.detail))
                .append($('
'))
    ruleContainer.appendTo(el)

    _.each(rule.patterns, appendPattern.bind(this, ruleContainer.find('p')))
  }
  function appendPattern(el, pattern) {
    var pairs = _.map(pattern.pairs, function(markClassName) {
          return _.clone(marks[markClassName])
        })
    var combinations = getAllCombinations(pairs)

    el.attr('data-asset', pattern.assetWidth)

    _.each(combinations, appendCombination.bind(this, el))
  }

  function appendCombination(el, combination) {
    el.append(
      combinationTmpl.replace('{{COMB}}', combination.join('')))
  }

  function getAllCombinations(pairs) {
    if (pairs.length === 1) {
      return _.clone(pairs[0])
    }

    var combinations = []
    var subCombinations = getAllCombinations(pairs.slice(1))
    _.each(pairs[0], function(pair) {
      _.each(subCombinations, function(subCombination) {
        combinations.push([pair].concat(subCombination))
      })
    })
    return combinations
  }

  var emInPx = 20
    , tolerantInPx = 5
    , total = 0
    , passedCnt = 0
    , testEl = $('#test')
  function test() {
    testEl.find('span.wrap').each(function(i, el) {
      total += 1
      el = $(el)
      var asset = el.closest('[data-asset]').data('asset')
        , passed = Math.abs(el.width() - asset * emInPx) < tolerantInPx
      if (passed) {
        el.addClass('passed')
        passedCnt += 1
      }
    })

    testEl.find('[name=passed-count]').text(passedCnt)
    testEl.find('[name=failed-count]').text(total - passedCnt)
  }

  appendRules()
  // Wait for web font's loading
  setTimeout(test, 1000)
}())
<|endoftext|>


<commit_before>var fs = require('fs')
  , child = require('child_process')
  , expect = require('expect.js')

var dir = __dirname +  '/fixture'
  , bin = __dirname + '/../bin/node-dev'
  , msgFile = dir + '/message.js'
  , msg = 'module.exports = "Please touch message.js now"\n'

function touch() {
  fs.writeFileSync(msgFile, msg)
}

function spawn(cmd, cb) {
  var ps = child.spawn('node', [bin].concat(cmd.split(' ')), { cwd: dir })
    , out = ''

  if (cb) ps.stdout.on('data', function(data) {
    out += data.toString()
    var ret = cb.call(ps, out)
    if (typeof ret == 'function') cb = ret
    else if (ret && ret.exit) {
      ps.stdout.removeAllListeners('data')
      ps.on('exit', function() { setTimeout(ret.exit, 1000) })
      ps.kill()
    }
  })
  return ps
}

function run(cmd, done) {
  spawn(cmd, function(out) {
    if (out.match(/touch message.js/)) {
      setTimeout(touch, 500)
      return function(out) {
        if (out.match(/Restarting/)) {
          return { exit: done }
        }
      }
    }
  })
}

describe('node-dev', function() {

  it('should restart the server', function(done) {
    run('server.js', done)
  })

  it('should restart the server twice', function(done) {
    spawn('server.js', function(out) {
      if (out.match(/touch message.js/)) {
        setTimeout(touch, 500)
        return function(out) {
          if (out.match(/Restarting/)) {
            setTimeout(touch, 500)
            return function(out) {
              if (out.match(/Restarting/)) {
                return { exit: done }
              }
            }
          }
        }
      }
    })
  })

  it('should restart the cluster', function(done) {
    run('cluster.js', done)
  })

  it('should support vm functions', function(done) {
    run('vmtest.js', done)
  })

  it('should support coffee-script', function(done) {
    run('server.coffee', done)
  })

  it('should restart when a file is renamed', function(done) {
    var tmp = dir + '/message.tmp'
    fs.writeFileSync(tmp, msg)
    spawn('log.js', function(out) {
      if (out.match(/touch message.js/)) {
        fs.renameSync(tmp, msgFile)
        return function(out) {
          if (out.match(/Restarting/)) {
            return { exit: done }
          }
        }
      }
    })
  })

  it('should handle errors', function(done) {
    spawn('error.js', function(out) {
      if (out.match(/ERROR/)) {
        setTimeout(touch, 500)
        return function(out) {
          if (out.match(/Restarting/)) {
            return { exit: done }
          }
        }
      }
    })
  })

  it('should watch if no such module', function(done) {
    spawn('noSuchModule.js', function(out) {
      expect(out).to.match(/ERROR/)
      return { exit: done }
    })
  })

  it('should ignore caught errors', function(done) {
    spawn('catchNoSuchModule.js', function(out) {
      expect(out).to.match(/Caught/)
      return { exit: done }
    })
  })

  it('should not show up in argv', function(done) {
    spawn('argv.js foo', function(out) {
      var argv = JSON.parse(out.replace(/'/g, '"'))
      expect(argv[0]).to.match(/.*?node(\.exe)?$/)
      expect(argv[1]).to.equal('argv.js')
      expect(argv[2]).to.equal('foo')
      return { exit: done }
    })
  })

  it('should pass through the exit code', function(done) {
    spawn('exit.js').on('exit', function(code) {
      expect(code).to.be(101)
      done()
    })
  })

  it('should conceil the wrapper', function(done) {
    // require.main should be main.js not wrap.js!
    spawn('main.js').on('exit', function(code) {
      expect(code).to.be(0)
      done()
    })
  })

  it('should relay stdin', function(done) {
    spawn('echo.js', function(out) {
      expect(out).to.equal('foo')
      return { exit: done }
    }).stdin.write('foo')
  })

  it('should kill the forked processes', function(done) {
    spawn('pid.js', function(out) {
      var pid = parseInt(out, 10)
      this.on('exit', function() {
        setTimeout(function() {
          try {
            process.kill(pid)
            done('child must no longer run')
          }
          catch(e) {
            done()
          }
        }, 500)
      })
      return { exit: done }
    })
  })

})
<commit_msg>the node binary is called nodejs in some distros<commit_after>var fs = require('fs')
  , child = require('child_process')
  , expect = require('expect.js')

var dir = __dirname +  '/fixture'
  , bin = __dirname + '/../bin/node-dev'
  , msgFile = dir + '/message.js'
  , msg = 'module.exports = "Please touch message.js now"\n'

function touch() {
  fs.writeFileSync(msgFile, msg)
}

function spawn(cmd, cb) {
  var ps = child.spawn('node', [bin].concat(cmd.split(' ')), { cwd: dir })
    , out = ''

  if (cb) ps.stdout.on('data', function(data) {
    out += data.toString()
    var ret = cb.call(ps, out)
    if (typeof ret == 'function') cb = ret
    else if (ret && ret.exit) {
      ps.stdout.removeAllListeners('data')
      ps.on('exit', function() { setTimeout(ret.exit, 1000) })
      ps.kill()
    }
  })
  return ps
}

function run(cmd, done) {
  spawn(cmd, function(out) {
    if (out.match(/touch message.js/)) {
      setTimeout(touch, 500)
      return function(out) {
        if (out.match(/Restarting/)) {
          return { exit: done }
        }
      }
    }
  })
}

describe('node-dev', function() {

  it('should restart the server', function(done) {
    run('server.js', done)
  })

  it('should restart the server twice', function(done) {
    spawn('server.js', function(out) {
      if (out.match(/touch message.js/)) {
        setTimeout(touch, 500)
        return function(out) {
          if (out.match(/Restarting/)) {
            setTimeout(touch, 500)
            return function(out) {
              if (out.match(/Restarting/)) {
                return { exit: done }
              }
            }
          }
        }
      }
    })
  })

  it('should restart the cluster', function(done) {
    run('cluster.js', done)
  })

  it('should support vm functions', function(done) {
    run('vmtest.js', done)
  })

  it('should support coffee-script', function(done) {
    run('server.coffee', done)
  })

  it('should restart when a file is renamed', function(done) {
    var tmp = dir + '/message.tmp'
    fs.writeFileSync(tmp, msg)
    spawn('log.js', function(out) {
      if (out.match(/touch message.js/)) {
        fs.renameSync(tmp, msgFile)
        return function(out) {
          if (out.match(/Restarting/)) {
            return { exit: done }
          }
        }
      }
    })
  })

  it('should handle errors', function(done) {
    spawn('error.js', function(out) {
      if (out.match(/ERROR/)) {
        setTimeout(touch, 500)
        return function(out) {
          if (out.match(/Restarting/)) {
            return { exit: done }
          }
        }
      }
    })
  })

  it('should watch if no such module', function(done) {
    spawn('noSuchModule.js', function(out) {
      expect(out).to.match(/ERROR/)
      return { exit: done }
    })
  })

  it('should ignore caught errors', function(done) {
    spawn('catchNoSuchModule.js', function(out) {
      expect(out).to.match(/Caught/)
      return { exit: done }
    })
  })

  it('should not show up in argv', function(done) {
    spawn('argv.js foo', function(out) {
      var argv = JSON.parse(out.replace(/'/g, '"'))
      expect(argv[0]).to.match(/.*?node(js|\.exe)?$/)
      expect(argv[1]).to.equal('argv.js')
      expect(argv[2]).to.equal('foo')
      return { exit: done }
    })
  })

  it('should pass through the exit code', function(done) {
    spawn('exit.js').on('exit', function(code) {
      expect(code).to.be(101)
      done()
    })
  })

  it('should conceil the wrapper', function(done) {
    // require.main should be main.js not wrap.js!
    spawn('main.js').on('exit', function(code) {
      expect(code).to.be(0)
      done()
    })
  })

  it('should relay stdin', function(done) {
    spawn('echo.js', function(out) {
      expect(out).to.equal('foo')
      return { exit: done }
    }).stdin.write('foo')
  })

  it('should kill the forked processes', function(done) {
    spawn('pid.js', function(out) {
      var pid = parseInt(out, 10)
      this.on('exit', function() {
        setTimeout(function() {
          try {
            process.kill(pid)
            done('child must no longer run')
          }
          catch(e) {
            done()
          }
        }, 500)
      })
      return { exit: done }
    })
  })

})
<|endoftext|>


<commit_before>const should = require('should');
const User = require('../lib/index');

const timeout = 15 * 1000;

const token = 'process.env.TOKEN';
if (!token) {
    console.error('Error: Token is required');
    process.exit(1);
}

const baseUrl = 'process.env.BASE_URL';
if (!baseUrl) {
    console.error('Error: Custom base url is required');
    process.exit(1);
}

const bot = new User({
  token: token,
  baseUrl: baseUrl
});

describe('module.exports', function() {
    it('Exposes a function', function() {
        should(User).be.a.Function();
    });
});

describe('bot', function() {
    it('Is an instance of user', function() {
        should(bot).be.an.instanceof(User);
    });
});

describe('Errors', function() {
    it('Undefined error', function(done) {
        bot.sendMessage('nouserexistswiththisaccount', 'ok').then(ctx => {
            should(ctx).eql(undefined)
            return done();
        })
    })
})

describe('Methods', function() {
    it('sendMessage', function(done) {
        this.timeout(timeout)
        bot.sendMessage('kamikazechaser', '**Test**', {parse_mode: 'Markdown'}).then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('setTyping', function(done) {
        this.timeout(timeout)
        bot.setTyping('kamikazechaser', 'sendMessageTypingAction').then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('setUploadTyping', function(done) {
        this.timeout(timeout)
        bot.setUploadTyping('kamikazechaser', 'sendMessageUploadAudioAction', 25).then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('forwardMessage', function(done) {
        this.timeout(timeout)
        bot.forwardMessage('kamikazechaser', '72175').then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
});
<commit_msg>[Fix] ENV<commit_after>const should = require('should');
const User = require('../lib/index');

const timeout = 15 * 1000;

const bot = new User({
  token: process.env.TOKEN,
  baseUrl: process.env.BASE_URL
});

describe('module.exports', function() {
    it('Exposes a function', function() {
        should(User).be.a.Function();
    });
});

describe('bot', function() {
    it('Is an instance of user', function() {
        should(bot).be.an.instanceof(User);
    });
});

describe('Errors', function() {
    it('Undefined error', function(done) {
        bot.sendMessage('nouserexistswiththisaccount', 'ok').then(ctx => {
            should(ctx).eql(undefined)
            return done();
        })
    })
})

describe('Methods', function() {
    it('sendMessage', function(done) {
        this.timeout(timeout)
        bot.sendMessage('kamikazechaser', '**Test**', {parse_mode: 'Markdown'}).then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('setTyping', function(done) {
        this.timeout(timeout)
        bot.setTyping('kamikazechaser', 'sendMessageTypingAction').then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('setUploadTyping', function(done) {
        this.timeout(timeout)
        bot.setUploadTyping('kamikazechaser', 'sendMessageUploadAudioAction', 25).then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
    it('forwardMessage', function(done) {
        this.timeout(timeout)
        bot.forwardMessage('kamikazechaser', '72175').then(ctx => {
            should(ctx.ok).eql(true);
            return done();
        })
    });
});
<|endoftext|>


<commit_before>'use strict';

/* deps: mocha */
var util = require('util');
var assert = require('assert');
var union = require('union-value');
var get = require('get-value');
var forOwn = require('for-own');
var groupArray = require('../');
require('should');

describe('errors', function () {
  it('should throw an error when invalid args are passed:', function () {
    (function () {
      groupArray('');
    }).should.throw('group-array expects an array.');
  });
});

describe('group-array', function () {
  it('should return an empty array when an empty array is passed:', function () {
    groupArray([]).should.eql([]);
  });

  it('should return the original array when no grouping properties are passed:', function () {
    groupArray(['a', 'b', 'c']).should.eql(['a', 'b', 'c']);
  });

  it('should create groups based on the value of the specified property', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {tag: 'one', content: 'B'},
      {tag: 'two', content: 'C'},
      {tag: 'two', content: 'D'},
      {tag: 'three', content: 'E'},
      {tag: 'three', content: 'F'}
    ];

    var actual = groupArray(arr, 'tag');

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'},
        {tag: 'one', content: 'B'}
      ],
      two: [
        {tag: 'two', content: 'C'},
        {tag: 'two', content: 'D'}
      ],
      three: [
        {tag: 'three', content: 'E'},
        {tag: 'three', content: 'F'}
      ],
    });
  });

  it('should support passing the property as an array:', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {tag: 'one', content: 'B'},
      {tag: 'two', content: 'C'},
      {tag: 'two', content: 'D'},
      {tag: 'three', content: 'E'},
      {tag: 'three', content: 'F'}
    ];

    var actual = groupArray(arr, ['tag']);

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'},
        {tag: 'one', content: 'B'}
      ],
      two: [
        {tag: 'two', content: 'C'},
        {tag: 'two', content: 'D'}
      ],
      three: [
        {tag: 'three', content: 'E'},
        {tag: 'three', content: 'F'}
      ],
    });
  });

  it('should create groups based on the value of nested properties', function () {
    var arr = [
      { data: { tag: 'one' }, content: 'A'},
      { data: { tag: 'one' }, content: 'B'},
      { data: { tag: 'two' }, content: 'C'},
      { data: { tag: 'two' }, content: 'D'},
      { data: { tag: 'three' }, content: 'E'},
      { data: { tag: 'three' }, content: 'F'}
    ];

    var actual = groupArray(arr, 'data.tag');

    assert.deepEqual(actual, {
      one: [
        {data: {tag: 'one'}, content: 'A'},
        {data: {tag: 'one'}, content: 'B'}
      ],
      two: [
        {data: {tag: 'two'}, content: 'C'},
        {data: {tag: 'two'}, content: 'D'}
      ],
      three: [
        {data: {tag: 'three'}, content: 'E'},
        {data: {tag: 'three'}, content: 'F'}
      ],
    });
  });

  it('should create groups from properties with object values:', function () {
    var arr = [
      { data: { categories: { one: [ 'one' ], four: ['five', 'six'] }}, content: 'A'},
      { data: { categories: { one: [ 'one' ] }}, content: 'B'},
      { data: { categories: { one: [ 'two' ], four: ['five', 'six'] }}, content: 'C'},
      { data: { categories: { two: [ 'two' ], four: ['five', 'six'] }}, content: 'D'},
      { data: { categories: { two: [ 'three' ], four: ['five', 'six'] }}, content: 'E'},
      { data: { categories: { two: [ 'three' ] }}, content: 'F'}
    ];

    function getChildren(prop) {
      return function (obj) {
        var val = get(obj, prop);
        var self = this;

        forOwn(val, function (arr) {
          arr.forEach(function (key) {
            union(self, key, [obj]);
          });
        });
      };
    }

    var actual = groupArray(arr, 'data.categories', getChildren('data.categories'));
    assert.deepEqual(Object.keys(actual), ['one', 'four', 'two']);
  });

  it('should create groups and ignore objects without matching property values:', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {content: 'B'},
      {tag: 'two', content: 'C'},
      {content: 'D'},
      {tag: 'three', content: 'E'},
      {content: 'F'}
    ];

    var actual = groupArray(arr, 'tag');

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'}
      ],
      two: [
        {tag: 'two', content: 'C'}
      ],
      three: [
        {tag: 'three', content: 'E'}
      ],
    });
  });

  it('should support properties with array values:', function () {
    var fixture = require('./fixtures/tags-array.js');
    var actual = groupArray(fixture, 'tags');
    assert.deepEqual(actual, require('./expected/tags-array.js'));
  });

  it('should group nested properties with array values that are created by a function:', function () {
    var fixture = require('./fixtures/categories-tags.js');
    var actual = groupArray(fixture, 'categories', function  (obj) {
      obj.tags = [];
      for (var key in obj.categories) {
        if (obj.categories.hasOwnProperty(key)) {
          var tags = obj.categories[key];
          tags.forEach(function (tag) {
            if (obj.tags.indexOf(tag) === -1) {
              obj.tags.push(tag);
            }
          });
        }
      }
      return obj.tags;
    });
    assert.deepEqual(actual, require('./expected/categories-tags.js'));
  });

  it('should create multiple, nested groups:', function () {
    var fixture = require('./fixtures/nested.js');
    var actual = groupArray(fixture, 'data.tag', 'data.month');
    assert.deepEqual(actual, require('./expected/nested.js'));
  });

  it('should create multiple, deeply nested groups:', function () {
    var fixture = require('./fixtures/deeply-nested.js');
    var actual = groupArray(fixture, 'data.tag', 'data.month', 'data.day');
    assert.deepEqual(actual, require('./expected/deeply-nested.js'));
  });

  it('should create multiple, insanely nested groups:', function () {
    var fixture = require('./fixtures/insanely-nested.js');
    var actual = groupArray(fixture, 'data.year', 'data.tag', 'data.month', 'data.day');
    assert.deepEqual(actual, require('./expected/insanely-nested.js'));
  });

  it('should support properties as an array:', function () {
    var fixture = require('./fixtures/insanely-nested.js');
    var actual = groupArray(fixture, ['data.year', 'data.tag', 'data.month', 'data.day']);
    assert.deepEqual(actual, require('./expected/insanely-nested.js'));
  });
});
<commit_msg>update test to return tags by category key<commit_after>'use strict';

/* deps: mocha */
var util = require('util');
var assert = require('assert');
var union = require('union-value');
var get = require('get-value');
var forOwn = require('for-own');
var groupArray = require('../');
require('should');

describe('errors', function () {
  it('should throw an error when invalid args are passed:', function () {
    (function () {
      groupArray('');
    }).should.throw('group-array expects an array.');
  });
});

describe('group-array', function () {
  it('should return an empty array when an empty array is passed:', function () {
    groupArray([]).should.eql([]);
  });

  it('should return the original array when no grouping properties are passed:', function () {
    groupArray(['a', 'b', 'c']).should.eql(['a', 'b', 'c']);
  });

  it('should create groups based on the value of the specified property', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {tag: 'one', content: 'B'},
      {tag: 'two', content: 'C'},
      {tag: 'two', content: 'D'},
      {tag: 'three', content: 'E'},
      {tag: 'three', content: 'F'}
    ];

    var actual = groupArray(arr, 'tag');

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'},
        {tag: 'one', content: 'B'}
      ],
      two: [
        {tag: 'two', content: 'C'},
        {tag: 'two', content: 'D'}
      ],
      three: [
        {tag: 'three', content: 'E'},
        {tag: 'three', content: 'F'}
      ],
    });
  });

  it('should support passing the property as an array:', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {tag: 'one', content: 'B'},
      {tag: 'two', content: 'C'},
      {tag: 'two', content: 'D'},
      {tag: 'three', content: 'E'},
      {tag: 'three', content: 'F'}
    ];

    var actual = groupArray(arr, ['tag']);

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'},
        {tag: 'one', content: 'B'}
      ],
      two: [
        {tag: 'two', content: 'C'},
        {tag: 'two', content: 'D'}
      ],
      three: [
        {tag: 'three', content: 'E'},
        {tag: 'three', content: 'F'}
      ],
    });
  });

  it('should create groups based on the value of nested properties', function () {
    var arr = [
      { data: { tag: 'one' }, content: 'A'},
      { data: { tag: 'one' }, content: 'B'},
      { data: { tag: 'two' }, content: 'C'},
      { data: { tag: 'two' }, content: 'D'},
      { data: { tag: 'three' }, content: 'E'},
      { data: { tag: 'three' }, content: 'F'}
    ];

    var actual = groupArray(arr, 'data.tag');

    assert.deepEqual(actual, {
      one: [
        {data: {tag: 'one'}, content: 'A'},
        {data: {tag: 'one'}, content: 'B'}
      ],
      two: [
        {data: {tag: 'two'}, content: 'C'},
        {data: {tag: 'two'}, content: 'D'}
      ],
      three: [
        {data: {tag: 'three'}, content: 'E'},
        {data: {tag: 'three'}, content: 'F'}
      ],
    });
  });

  it('should create groups from properties with object values:', function () {
    var arr = [
      { data: { categories: { one: [ 'one' ], four: ['five', 'six'] }}, content: 'A'},
      { data: { categories: { one: [ 'one' ] }}, content: 'B'},
      { data: { categories: { one: [ 'two' ], four: ['five', 'six'] }}, content: 'C'},
      { data: { categories: { two: [ 'two' ], four: ['five', 'six'] }}, content: 'D'},
      { data: { categories: { two: [ 'three' ], four: ['five', 'six'] }}, content: 'E'},
      { data: { categories: { two: [ 'three' ] }}, content: 'F'}
    ];

    function getChildren(prop) {
      return function (obj) {
        var val = get(obj, prop);
        var self = this;

        forOwn(val, function (arr) {
          arr.forEach(function (key) {
            union(self, key, [obj]);
          });
        });
      };
    }

    var actual = groupArray(arr, 'data.categories', getChildren('data.categories'));
    assert.deepEqual(Object.keys(actual), ['one', 'four', 'two']);
  });

  it('should create groups and ignore objects without matching property values:', function () {
    var arr = [
      {tag: 'one', content: 'A'},
      {content: 'B'},
      {tag: 'two', content: 'C'},
      {content: 'D'},
      {tag: 'three', content: 'E'},
      {content: 'F'}
    ];

    var actual = groupArray(arr, 'tag');

    assert.deepEqual(actual, {
      one: [
        {tag: 'one', content: 'A'}
      ],
      two: [
        {tag: 'two', content: 'C'}
      ],
      three: [
        {tag: 'three', content: 'E'}
      ],
    });
  });

  it('should support properties with array values:', function () {
    var fixture = require('./fixtures/tags-array.js');
    var actual = groupArray(fixture, 'tags');
    assert.deepEqual(actual, require('./expected/tags-array.js'));
  });

  it('should group nested properties with array values that are created by a function:', function () {
    var fixture = require('./fixtures/categories-tags.js');
    var actual = groupArray(fixture, 'categories', function  (obj, key) {
      return obj.categories[key];
    });
    assert.deepEqual(actual, require('./expected/categories-tags.js'));
  });

  it('should create multiple, nested groups:', function () {
    var fixture = require('./fixtures/nested.js');
    var actual = groupArray(fixture, 'data.tag', 'data.month');
    assert.deepEqual(actual, require('./expected/nested.js'));
  });

  it('should create multiple, deeply nested groups:', function () {
    var fixture = require('./fixtures/deeply-nested.js');
    var actual = groupArray(fixture, 'data.tag', 'data.month', 'data.day');
    assert.deepEqual(actual, require('./expected/deeply-nested.js'));
  });

  it('should create multiple, insanely nested groups:', function () {
    var fixture = require('./fixtures/insanely-nested.js');
    var actual = groupArray(fixture, 'data.year', 'data.tag', 'data.month', 'data.day');
    assert.deepEqual(actual, require('./expected/insanely-nested.js'));
  });

  it('should support properties as an array:', function () {
    var fixture = require('./fixtures/insanely-nested.js');
    var actual = groupArray(fixture, ['data.year', 'data.tag', 'data.month', 'data.day']);
    assert.deepEqual(actual, require('./expected/insanely-nested.js'));
  });
});
<|endoftext|>


<commit_before>'use strict';

var pluginPath = '../index';
var checktextdomain = require(pluginPath);
var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs-extra');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './temp', glob); }

var keywords = [
	'__:1,2d',
	'_e:1,2d',
	'_x:1,2c,3d',
	'esc_html__:1,2d',
	'esc_html_e:1,2d',
	'esc_html_x:1,2c,3d',
	'esc_attr__:1,2d',
	'esc_attr_e:1,2d',
	'esc_attr_x:1,2c,3d',
	'_ex:1,2c,3d',
	'_n:1,2,4d',
	'_nx:1,2,4c,5d',
	'_n_noop:1,2,3d',
	'_nx_noop:1,2,3c,4d'
];

var fixtures = function(glob) { return path.join(__dirname, './temp', glob); }

function fileExists(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
}

describe('gulp-checktextdomain', function() {

  var tmpFolder = path.join(__dirname, 'temp');

  beforeEach(function(done) {
    var folder = path.join(__dirname, './fixtures/');
    fs.copy(folder, tmpFolder, function(err) {
      done();
    });
  });

  // We'll delete it when we're done.
  afterEach(function(done) {
    fs.remove(tmpFolder, done);
  });

  it('1) Domain should have been corrected', function(done) {

      var actual;
      var corrected;
      var expected;
      var options = {
        force: true,
        text_domain: 'my-domain',
        correct_domain: true,
        create_report_file: true,
        keywords: keywords
      };

      gulp.src(fixtures('incorrect-domain-autocorrect.php'))
      .pipe(checktextdomain(options))
      .pipe(sassert.first(function(d) {
        //There are 14 missing domains
        actual = JSON.parse(fs.readFileSync( '.incorrect-domain-autocorrect.json' ) );
        actual[path.join(__dirname, 'temp/incorrect-domain-autocorrect.php')].length.should.equal(14);

        //Test corrected file
        corrected = fs.readFileSync( 'test/temp/incorrect-domain-autocorrect.php' ).toString();
        expected = fs.readFileSync( 'test/expected/incorrect-domain-autocorrect.php' ).toString();
        corrected.should.equal(expected);

        //Clean up: Delete report file
        fs.remove( '.incorrect-domain-autocorrect.json' );
      }))
      .pipe(sassert.end(done));

  });

  xit('2) variable_domain_autocomplete', function(done) {

  });

  xit('3) missing_domain', function(done) {

  });

  xit('4) missing_domain_ignore_missing', function(done) {

  });

  xit('5) correct_domain', function(done) {

  });

  xit('6) plurals', function(done) {

  });

});
<commit_msg>test(test.js): enable test number 2<commit_after>'use strict';

var pluginPath = '../index';
var checktextdomain = require(pluginPath);
var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs-extra');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './temp', glob); }

var keywords = [
	'__:1,2d',
	'_e:1,2d',
	'_x:1,2c,3d',
	'esc_html__:1,2d',
	'esc_html_e:1,2d',
	'esc_html_x:1,2c,3d',
	'esc_attr__:1,2d',
	'esc_attr_e:1,2d',
	'esc_attr_x:1,2c,3d',
	'_ex:1,2c,3d',
	'_n:1,2,4d',
	'_nx:1,2,4c,5d',
	'_n_noop:1,2,3d',
	'_nx_noop:1,2,3c,4d'
];

var fixtures = function(glob) { return path.join(__dirname, './temp', glob); }

function fileExists(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
}

describe('gulp-checktextdomain', function() {

  var tmpFolder = path.join(__dirname, 'temp');

  beforeEach(function(done) {
    var folder = path.join(__dirname, './fixtures/');
    fs.copy(folder, tmpFolder, function(err) {
      done();
    });
  });

  // We'll delete it when we're done.
  afterEach(function(done) {
    fs.remove(tmpFolder, done);
  });

  it('1) Domain should have been corrected', function(done) {

      var actual;
      var corrected;
      var expected;
      var options = {
        force: true,
        text_domain: 'my-domain',
        correct_domain: true,
        create_report_file: true,
        keywords: keywords
      };

      gulp.src(fixtures('incorrect-domain-autocorrect.php'))
      .pipe(checktextdomain(options))
      .pipe(sassert.first(function(d) {
        //There are 14 missing domains
        actual = JSON.parse(fs.readFileSync( '.incorrect-domain-autocorrect.json' ) );
        actual[path.join(__dirname, 'temp/incorrect-domain-autocorrect.php')].length.should.equal(14);

        //Test corrected file
        corrected = fs.readFileSync( 'test/temp/incorrect-domain-autocorrect.php' ).toString();
        expected = fs.readFileSync( 'test/expected/incorrect-domain-autocorrect.php' ).toString();
        corrected.should.equal(expected);

        //Clean up: Delete report file
        fs.remove( '.incorrect-domain-autocorrect.json' );
      }))
      .pipe(sassert.end(done));

  });

  it('2) Domain should have been corrected', function(done) {
      var actual;
      var corrected;
      var expected;
      var options = {
        force: true,
        text_domain: 'my-domain',
        correct_domain: true,
        create_report_file: true,
        keywords: keywords
      };

      gulp.src(fixtures('variable-domain-autocorrect.php'))
      .pipe(checktextdomain(options))
      .pipe(sassert.first(function(d) {
        //There are 14 missing domains
        actual = JSON.parse(fs.readFileSync( '.variable-domain-autocorrect.json' ) );
        actual[path.join(__dirname, 'temp/variable-domain-autocorrect.php')].length.should.equal(14);

        //Test corrected file
        corrected = fs.readFileSync( 'test/temp/variable-domain-autocorrect.php' ).toString();
        expected = fs.readFileSync( 'test/expected/variable-domain-autocorrect.php' ).toString();
        corrected.should.equal(expected);

        //Clean up: Delete report file
        fs.remove( '.variable-domain-autocorrect.json' );
      }))
      .pipe(sassert.end(done));
  });

  xit('3) missing_domain', function(done) {

  });

  xit('4) missing_domain_ignore_missing', function(done) {

  });

  xit('5) correct_domain', function(done) {

  });

  xit('6) plurals', function(done) {

  });

});
<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here.
	// For the complete reference:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		{ name: 'forms' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons, provided by the standard plugins, which we don't
	// need to have in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Se the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre';

	// Make dialogs simpler.
	config.removeDialogTabs = 'image:advanced;link:advanced';
};
<commit_msg>updated ckeditor config<commit_after>/**
 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here.
	// For the complete reference:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		{ name: 'forms' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons, provided by the standard plugins, which we don't
	// need to have in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Se the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre';

	// Make dialogs simpler.
	config.removeDialogTabs = 'image:advanced;link:advanced';
};
<|endoftext|>