<commit_before>var debug = require('debug')('full');
var should = require('should');
var fs = require('fs');
var Path = require('path');
var URL = require('url');
var cookie = require('cookie');
var express = require('express');

var runner = require('../spawner');
var scope = require('../scope')({
	privateKey: fs.readFileSync(Path.join(__dirname, 'fixtures/private.pem')).toString(),
	publicKey: fs.readFileSync(Path.join(__dirname, 'fixtures/public.pem')).toString(),
	maxAge: 3600,
	issuer: "test",
	userProperty: "user"
});
var tag = require('../tag');

var ports = {
	app: 3000,
	ngx: 3001,
	memc: 3002
};

describe("Tag and Scope", function suite() {
	var servers, app;
	var testPath = '/full-scope-test';
	var testPathTag = '/full-scope-tag-test';
	var testPathNotGranted = '/full-scope-not-granted-test';
	var scopeDependentTag = '/scope-dependent-tag';
	var counters = {};

	function count(uri, inc) {
		if (typeof uri != "string") {
			if (uri.get) uri = uri.protocol + '://' + uri.get('Host') + uri.path;
			else uri = URL.format(Object.assign({
				protocol: 'http',
				hostname: 'localhost',
				pathname: uri.path
			}, uri));
		}
		var counter = counters[uri];
		if (counter == null) counter = counters[uri] = 0;
		if (inc) counters[uri] += inc;
		return counters[uri];
	}

	before(function(done) {
		servers = runner(ports, done);

		app = express();
		app.server = app.listen(ports.app);

		app.post('/login', function(req, res, next) {
			var givemeScope = req.query.scope;
			var userId = req.query && req.query.id || 44;
			var scopes = {
				[`user-${userId}`]: true,
				bookWriter: {
					write: true
				},
				bookReader: {
					read: true
				}
			};
			if (givemeScope) scopes = {[givemeScope]: true};
			var bearer = scope.login(res, {id: userId, scopes: scopes});
			res.send({
				bearer: bearer // convenient but not technically needed
			});
		});

		app.post('/logout', function(req, res, next) {
			scope.logout(res);
			res.sendStatus(204);
		});

		app.get(testPath, scope.restrict('bookReader', 'bookSecond'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.post(testPath, function(req, res, next) {
			res.sendStatus(204);
		});

		app.get(testPathTag, tag("full"), scope.restrict('bookReader', 'bookSecond'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.post(testPathTag, tag("full"), function(req, res, next) {
			res.sendStatus(204);
		});

		app.get(testPathNotGranted, tag("apart"), scope.restrict('bookReaderWhat'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.get(scopeDependentTag, scope.restrict('user-*'), function userTag(req, res, next) {
			tag('usertag' + req.user.id)(req, res, next);
		}, function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});
		app.post(scopeDependentTag, tag("usertag18"), function(req, res, next) {
			res.sendStatus(200);
		});
	});

	after(function(done) {
		app.server.close();
		servers.close(done);
	});

	beforeEach(function() {
		counters = {};
	});

	it("should get 401 when accessing a protected url with proxy", function() {
		var req = {
			port: ports.ngx,
			path: testPath
		};
		return runner.get(req).then(function(res) {
			res.statusCode.should.equal(401);
			count(req).should.equal(0);
		});
	});

	it("should log in and get read access to a url and hit the cache with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.headers.should.have.property('x-upcache-scope', 'bookReader, bookSecond');
			res.statusCode.should.equal(200);
			count(req).should.equal(1);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			// because it should be a cache hit
			count(req).should.equal(1);
		});
	});

	it("should log in and not get read access to another url with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPathNotGranted
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(403);
			count(req).should.equal(0);
		});
	});

	it("should log in, access, then log out, and be denied access with proxy", function() {
		var headers = {};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get({
				headers: headers,
				port: ports.ngx,
				path: testPath
			});
		}).then(function(res) {
			res.statusCode.should.equal(200);
			return runner.post({
				headers: headers,
				port: ports.ngx,
				path: "/logout"
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get({
				headers: headers,
				port: ports.ngx,
				path: testPath
			});
		}).then(function(res) {
			res.statusCode.should.equal(401);
		});
	});

	it("should log in with different scopes and cache each variant with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		var firstDate;
		return runner.post({
			port: ports.ngx,
			path: '/login?scope=bookReader'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			firstDate = res.body.date;
			return runner.post({
				port: ports.ngx,
				path: '/login?scope=bookSecond'
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.not.equal(firstDate);
		});
	});

	it("should log in, access url, hit the cache, invalidate the cache with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPathTag
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.headers.should.have.property('x-upcache-scope', 'bookReader, bookSecond');
			res.statusCode.should.equal(200);
			count(req).should.equal(1);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			// because it should be a cache hit
			count(req).should.equal(1);
			return runner.post(req);
		}).then(function(res) {
			return runner.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
		});
	});

	it("should cache with scope-dependent tags", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: scopeDependentTag
		};
		var firstDate, firstCookie;
		return runner.post({
			port: ports.ngx,
			path: '/login?id=17'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			firstCookie = headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			firstDate = res.body.date;
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.equal(firstDate);
			count(req).should.equal(1);
			return runner.post({
				port: ports.ngx,
				path: '/login?id=18'
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.not.equal(firstDate);
			count(req).should.equal(2);
			return runner.post(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			return runner.get(req);
		}).then(function(res) {
			count(req).should.equal(3);
			res.statusCode.should.equal(200);
			headers.Cookie = firstCookie;
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			count(req).should.equal(3);
		});
	});

});
<commit_msg>Test x-upcache<commit_after>var debug = require('debug')('full');
var should = require('should');
var fs = require('fs');
var Path = require('path');
var URL = require('url');
var cookie = require('cookie');
var express = require('express');

var runner = require('../spawner');
var scope = require('../scope')({
	privateKey: fs.readFileSync(Path.join(__dirname, 'fixtures/private.pem')).toString(),
	publicKey: fs.readFileSync(Path.join(__dirname, 'fixtures/public.pem')).toString(),
	maxAge: 3600,
	issuer: "test",
	userProperty: "user"
});
var tag = require('../tag');

var ports = {
	app: 3000,
	ngx: 3001,
	memc: 3002
};

describe("Tag and Scope", function suite() {
	var servers, app;
	var testPath = '/full-scope-test';
	var testPathTag = '/full-scope-tag-test';
	var testPathNotGranted = '/full-scope-not-granted-test';
	var scopeDependentTag = '/scope-dependent-tag';
	var counters = {};

	function count(uri, inc) {
		if (typeof uri != "string") {
			if (uri.get) uri = uri.protocol + '://' + uri.get('Host') + uri.path;
			else uri = URL.format(Object.assign({
				protocol: 'http',
				hostname: 'localhost',
				pathname: uri.path
			}, uri));
		}
		var counter = counters[uri];
		if (counter == null) counter = counters[uri] = 0;
		if (inc) counters[uri] += inc;
		return counters[uri];
	}

	before(function(done) {
		servers = runner(ports, done);

		app = express();
		app.server = app.listen(ports.app);

		app.post('/login', function(req, res, next) {
			var givemeScope = req.query.scope;
			var userId = req.query && req.query.id || 44;
			var scopes = {
				[`user-${userId}`]: true,
				bookWriter: {
					write: true
				},
				bookReader: {
					read: true
				}
			};
			if (givemeScope) scopes = {[givemeScope]: true};
			var bearer = scope.login(res, {id: userId, scopes: scopes});
			res.send({
				bearer: bearer // convenient but not technically needed
			});
		});

		app.post('/logout', function(req, res, next) {
			scope.logout(res);
			res.sendStatus(204);
		});

		app.get('/', function(req, res, next) {
			res.send(req.get('x-upcache') ? "ok" : "not ok");
		});

		app.get(testPath, scope.restrict('bookReader', 'bookSecond'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.post(testPath, function(req, res, next) {
			res.sendStatus(204);
		});

		app.get(testPathTag, tag("full"), scope.restrict('bookReader', 'bookSecond'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.post(testPathTag, tag("full"), function(req, res, next) {
			res.sendStatus(204);
		});

		app.get(testPathNotGranted, tag("apart"), scope.restrict('bookReaderWhat'), function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.get(scopeDependentTag, scope.restrict('user-*'), function userTag(req, res, next) {
			tag('usertag' + req.user.id)(req, res, next);
		}, function(req, res, next) {
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});
		app.post(scopeDependentTag, tag("usertag18"), function(req, res, next) {
			res.sendStatus(200);
		});
	});

	after(function(done) {
		app.server.close();
		servers.close(done);
	});

	beforeEach(function() {
		counters = {};
	});

	it("should set X-Upcache version in request header", function() {
		return runner.get({
			port: ports.ngx,
			path: '/'
		}).then(function(res) {
			should(res.body).be.equal('ok');
		});
	});

	it("should get 401 when accessing a protected url with proxy", function() {
		var req = {
			port: ports.ngx,
			path: testPath
		};
		return runner.get(req).then(function(res) {
			res.statusCode.should.equal(401);
			count(req).should.equal(0);
		});
	});

	it("should log in and get read access to a url and hit the cache with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.headers.should.have.property('x-upcache-scope', 'bookReader, bookSecond');
			res.statusCode.should.equal(200);
			count(req).should.equal(1);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			// because it should be a cache hit
			count(req).should.equal(1);
		});
	});

	it("should log in and not get read access to another url with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPathNotGranted
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(403);
			count(req).should.equal(0);
		});
	});

	it("should log in, access, then log out, and be denied access with proxy", function() {
		var headers = {};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get({
				headers: headers,
				port: ports.ngx,
				path: testPath
			});
		}).then(function(res) {
			res.statusCode.should.equal(200);
			return runner.post({
				headers: headers,
				port: ports.ngx,
				path: "/logout"
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get({
				headers: headers,
				port: ports.ngx,
				path: testPath
			});
		}).then(function(res) {
			res.statusCode.should.equal(401);
		});
	});

	it("should log in with different scopes and cache each variant with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		var firstDate;
		return runner.post({
			port: ports.ngx,
			path: '/login?scope=bookReader'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			firstDate = res.body.date;
			return runner.post({
				port: ports.ngx,
				path: '/login?scope=bookSecond'
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.not.equal(firstDate);
		});
	});

	it("should log in, access url, hit the cache, invalidate the cache with proxy", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPathTag
		};
		return runner.post({
			port: ports.ngx,
			path: '/login'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.headers.should.have.property('x-upcache-scope', 'bookReader, bookSecond');
			res.statusCode.should.equal(200);
			count(req).should.equal(1);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			// because it should be a cache hit
			count(req).should.equal(1);
			return runner.post(req);
		}).then(function(res) {
			return runner.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
		});
	});

	it("should cache with scope-dependent tags", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: scopeDependentTag
		};
		var firstDate, firstCookie;
		return runner.post({
			port: ports.ngx,
			path: '/login?id=17'
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			firstCookie = headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			firstDate = res.body.date;
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.equal(firstDate);
			count(req).should.equal(1);
			return runner.post({
				port: ports.ngx,
				path: '/login?id=18'
			});
		}).then(function(res) {
			res.headers.should.have.property('set-cookie');
			var cookies = cookie.parse(res.headers['set-cookie'][0]);
			headers.Cookie = cookie.serialize("bearer", cookies.bearer);
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			res.body.date.should.not.equal(firstDate);
			count(req).should.equal(2);
			return runner.post(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			return runner.get(req);
		}).then(function(res) {
			count(req).should.equal(3);
			res.statusCode.should.equal(200);
			headers.Cookie = firstCookie;
			return runner.get(req);
		}).then(function(res) {
			res.statusCode.should.equal(200);
			count(req).should.equal(3);
		});
	});

});
<|endoftext|>


<commit_before>import '../src'
import bufferEqual from 'buffer-equal'
import gulp from 'gulp'
import imageSize from 'image-size'
import timeout from 'timeout-then'
import rump from 'rump'
import {colors} from 'gulp-util'
import {readFile, stat, writeFile} from 'mz/fs'
import {sep} from 'path'
import {spy} from 'sinon'

const {stripColor} = colors

describe('tasks', function() {
  this.timeout(0)

  beforeEach(() => {
    rump.configure({paths: {
      source: {root: 'test/fixtures/src', images: ''},
      destination: {root: 'tmp', images: ''},
    }})
  })

  it('are added and defined', () => {
    const callback = spy()
    rump.on('gulp:main', callback)
    rump.on('gulp:images', callback)
    rump.addGulpTasks({prefix: 'spec'})
    callback.should.be.calledTwice()
    gulp.tasks['spec:info:images'].should.be.ok()
    gulp.tasks['spec:build:images'].should.be.ok()
    gulp.tasks['spec:watch:images'].should.be.ok()
  })

  it('display correct information in info task', () => {
    const logs = [],
          {log} = console
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.7.0',
      `Images from test${sep}fixtures${sep}src are copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info:prod')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.7.0',
      `Images from test${sep}fixtures${sep}src are minified and copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    rump.reconfigure({environment: 'development'})

    function newLog(...args) {
      logs.push(stripColor(args.join(' ')))
    }
  })

  describe('for building', () => {
    let original

    before(async() => {
      original = await readFile('test/fixtures/src/image1.png')
      await new Promise(resolve => {
        gulp.task('postbuild', ['spec:watch'], resolve)
        gulp.start('postbuild')
      })
    })

    beforeEach(() => timeout(1000))

    afterEach(() => writeFile('test/fixtures/src/image1.png', original))

    it('handles updates', async() => {
      let content = await readFile('tmp/image1.png')
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.true()
      content = await readFile('test/fixtures/new/image1.png')
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', content)
      await timeout(1000)
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.false()
    })

    it('handles retina images', () => {
      const {width, height} = imageSize('tmp/image2.jpg'),
            retinaSize = imageSize('tmp/image2@2x.jpg')
      retinaSize.width.should.equal(width * 2)
      retinaSize.height.should.equal(height * 2)
    })

    it('handles minification in production', async() => {
      let sourceStat = await stat('test/fixtures/src/image1.png'),
          destinationStat = await stat('tmp/image1.png')
      sourceStat.size.should.equal(destinationStat.size)
      rump.reconfigure({environment: 'production'})
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', original)
      await timeout(1000);
      [sourceStat, destinationStat] = await Promise.all([
        stat('test/fixtures/src/image1.png'),
        stat('tmp/image1.png'),
      ])
      sourceStat.size.should.be.above(destinationStat.size)
    })
  })
})
<commit_msg>Test for not displaying info if no files are available<commit_after>import '../src'
import bufferEqual from 'buffer-equal'
import gulp from 'gulp'
import imageSize from 'image-size'
import timeout from 'timeout-then'
import rump from 'rump'
import {colors} from 'gulp-util'
import {readFile, stat, writeFile} from 'mz/fs'
import {sep} from 'path'
import {spy} from 'sinon'

const {stripColor} = colors

describe('tasks', function() {
  this.timeout(0)

  afterEach(() => {
    rump.configure({paths: {
      source: {root: 'test/fixtures/src', images: ''},
      destination: {root: 'tmp', images: ''},
    }})
  })

  it('are added and defined', () => {
    const callback = spy()
    rump.on('gulp:main', callback)
    rump.on('gulp:images', callback)
    rump.addGulpTasks({prefix: 'spec'})
    callback.should.be.calledTwice()
    gulp.tasks['spec:info:images'].should.be.ok()
    gulp.tasks['spec:build:images'].should.be.ok()
    gulp.tasks['spec:watch:images'].should.be.ok()
  })

  it('display correct information in info task', () => {
    const logs = [],
          {log} = console
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.7.0',
      `Images from test${sep}fixtures${sep}src are copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info:prod')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.7.0',
      `Images from test${sep}fixtures${sep}src are minified and copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    rump.reconfigure({paths: {source: {images: 'nonexistant'}}})
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.length.should.not.be.above(4)

    function newLog(...args) {
      logs.push(stripColor(args.join(' ')))
    }
  })

  describe('for building', () => {
    let original

    before(async() => {
      original = await readFile('test/fixtures/src/image1.png')
      await new Promise(resolve => {
        gulp.task('postbuild', ['spec:watch'], resolve)
        gulp.start('postbuild')
      })
    })

    beforeEach(() => timeout(1000))

    afterEach(() => writeFile('test/fixtures/src/image1.png', original))

    it('handles updates', async() => {
      let content = await readFile('tmp/image1.png')
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.true()
      content = await readFile('test/fixtures/new/image1.png')
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', content)
      await timeout(1000)
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.false()
    })

    it('handles retina images', () => {
      const {width, height} = imageSize('tmp/image2.jpg'),
            retinaSize = imageSize('tmp/image2@2x.jpg')
      retinaSize.width.should.equal(width * 2)
      retinaSize.height.should.equal(height * 2)
    })

    it('handles minification in production', async() => {
      let sourceStat = await stat('test/fixtures/src/image1.png'),
          destinationStat = await stat('tmp/image1.png')
      sourceStat.size.should.equal(destinationStat.size)
      rump.reconfigure({environment: 'production'})
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', original)
      await timeout(1000);
      [sourceStat, destinationStat] = await Promise.all([
        stat('test/fixtures/src/image1.png'),
        stat('tmp/image1.png'),
      ])
      sourceStat.size.should.be.above(destinationStat.size)
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

require('should');
var request = require('supertest');
var AnyFetchProvider = require("anyfetch-provider");

process.env.ANYFETCH_SETTINGS_URL = 'http://localhost:1337';
var app = require('../app.js');

describe("GET /init/connect", function () {
  it("should redirect to option page", function(done) {
    request(app).get('/init/connect?code=123')
      .expect(302)
      .expect('Location', /\/init\/options\?code=123/)
      .end(done);
  });
});

describe("GET /init/options", function () {
  it("should ask the user to select the path of the directory", function(done) {
    request(app).get('/init/options?code=123')
      .expect(200)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('<form');
        res.text.should.include('value="123"');
        res.text.should.include('name="path"');

        done();
      });
  });
});

describe("GET /init/callback", function () {
  var frontServer = AnyFetchProvider.debug.createTestFrontServer();
  frontServer.listen(1337);

  it("should check for path param", function(done) {
    request(app).get('/init/callback?code=123')
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('Missing path');

        done();
      });
  });

  it("should check directory exists", function(done) {
    request(app).get('/init/callback?code=123&path=/lol-not-exist')
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('directory does not exist');

        done();
      });
  });

  it("should check path is not a file", function(done) {
    request(app).get('/init/callback?code=123&path=' + __filename)
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('is not a directory');

        done();
      });
  });

  it("should work with valid path", function(done) {
    request(app).get('/init/callback?code=123&path=' + __dirname)
      .expect(302)
      .end(done);
  });
});
<commit_msg>Removed legacy test<commit_after>'use strict';

require('should');
var request = require('supertest');
var AnyFetchProvider = require("anyfetch-provider");
var async = require('async');

process.env.ANYFETCH_SETTINGS_URL = 'http://localhost:1337';
var app = require('../app.js');

describe("GET /init/connect", function () {
  it("should redirect to option page", function(done) {
    request(app).get('/init/connect?code=123')
      .expect(302)
      .expect('Location', /\/init\/options\?code=123/)
      .end(done);
  });
});

describe("GET /init/options", function () {
  it("should ask the user to select the path of the directory", function(done) {
    request(app).get('/init/options?code=123')
      .expect(200)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('<form');
        res.text.should.include('value="123"');
        res.text.should.include('name="path"');

        done();
      });
  });
});

describe("GET /init/callback", function () {
  var frontServer = AnyFetchProvider.debug.createTestFrontServer();
  frontServer.listen(1337);

  it("should check for path param", function(done) {
    request(app).get('/init/callback?code=123')
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('Missing path');

        done();
      });
  });

  it("should check directory exists", function(done) {
    request(app).get('/init/callback?code=123&path=/lol-not-exist')
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('directory does not exist');

        done();
      });
  });

  it("should check path is not a file", function(done) {
    request(app).get('/init/callback?code=123&path=' + __filename)
      .expect(500)
      .end(function(err, res) {
        if(err) {
          throw err;
        }

        res.text.should.include('is not a directory');

        done();
      });
  });
});
<|endoftext|>


<commit_before>'use strict'

const qs = require('querystring')
const run = require('tapdance')
const deepEqual = require('fortune/lib/common/deep_equal')

const httpTest = require('./http_test')
const jsonSerializer = require('../lib/json_serializer')

const test = httpTest.bind(null, {
  serializers: [ jsonSerializer ]
})

run((assert, comment) => {
  comment('get index')
  return test('/', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(Object.keys(response.body.recordTypes), [ 'user', 'animal', '☯' ]),
      'response body is correct')
  })
})

run((assert, comment) => {
  comment('get empty collection')
  return test(encodeURI('/☯'), null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body, { records: [], count: 0 }), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records')
  return test('/user', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records.length === 3, 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records by ID')
  return test('/animal/1,%2Fwtf', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.id),
      [ 1, '/wtf' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records with fields')
  return test(`/animal?${qs.stringify({
    fields: [ 'name', 'owner' ]
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records
      .map(record => Object.keys(record).length),
      [ 4, 4, 4, 4 ]), 'response body fields are correct')
  })
})

run((assert, comment) => {
  comment('get records with match')
  return test(`/animal?${qs.stringify({
    'match.name': 'Babby'
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].name === 'Babby', 'match is correct')
  })
})

run((assert, comment) => {
  comment('get records with match by link')
  return test(`/animal?${qs.stringify({
    'match.owner': 1
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].name === 'Babby', 'match is correct')
  })
})

run((assert, comment) => {
  comment('get records with include')
  return test(`/animal/1?${qs.stringify({
    'include': [ 'owner', 'owner.spouse' ]
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].id === 1, 'ID is correct')
    assert(deepEqual(response.body.include.user.map(record => record.id),
      [ 1, 2 ]), 'IDs are correct')
  })
})

run((assert, comment) => {
  comment('get records with sort/limit/offset')
  return test(`/animal?${qs.stringify({
    sort: 'name',
    limit: 2,
    offset: 1
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ 'Babby', 'Kantorin' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('create records')
  return test(`/animal`, {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: [ {
      name: 'Ayy lmao',
      nicknames: [ 'ayy', 'lmao' ],
      owner: 1
    } ]
  }, response => {
    assert(response.status === 201, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ 'Ayy lmao' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('update records')
  return test(`/animal`, {
    method: 'patch',
    headers: { 'Content-Type': 'application/json' },
    body: [ {
      id: '/wtf',
      replace: { name: 1234 }
    } ]
  }, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ '1234' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('delete records')
  return test(`/animal/1,%2Fwtf`, {
    method: 'delete'
  }, response => {
    assert(response.status === 204, 'status is correct')
    assert(response.body.length === 0, 'body is empty')
  })
})

run((assert, comment) => {
  comment('respond to options: index')
  return test('/', { method: 'options' }, response => {
    assert(response.status === 204, 'status is correct')
    assert(response.headers['allow'] === 'GET',
      'allow header is correct')
  })
})
<commit_msg>Add additional test for empty body<commit_after>'use strict'

const qs = require('querystring')
const run = require('tapdance')
const deepEqual = require('fortune/lib/common/deep_equal')

const httpTest = require('./http_test')
const jsonSerializer = require('../lib/json_serializer')

const test = httpTest.bind(null, {
  serializers: [ jsonSerializer ]
})

run((assert, comment) => {
  comment('get index')
  return test('/', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(Object.keys(response.body.recordTypes), [ 'user', 'animal', '☯' ]),
      'response body is correct')
  })
})

run((assert, comment) => {
  comment('get empty collection')
  return test(encodeURI('/☯'), null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body, { records: [], count: 0 }), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records')
  return test('/user', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records.length === 3, 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records by ID')
  return test('/animal/1,%2Fwtf', null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.id),
      [ 1, '/wtf' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('get records with fields')
  return test(`/animal?${qs.stringify({
    fields: [ 'name', 'owner' ]
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records
      .map(record => Object.keys(record).length),
      [ 4, 4, 4, 4 ]), 'response body fields are correct')
  })
})

run((assert, comment) => {
  comment('get records with match')
  return test(`/animal?${qs.stringify({
    'match.name': 'Babby'
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].name === 'Babby', 'match is correct')
  })
})

run((assert, comment) => {
  comment('get records with match by link')
  return test(`/animal?${qs.stringify({
    'match.owner': 1
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].name === 'Babby', 'match is correct')
  })
})

run((assert, comment) => {
  comment('get records with include')
  return test(`/animal/1?${qs.stringify({
    'include': [ 'owner', 'owner.spouse' ]
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(response.body.records[0].id === 1, 'ID is correct')
    assert(deepEqual(response.body.include.user.map(record => record.id),
      [ 1, 2 ]), 'IDs are correct')
  })
})

run((assert, comment) => {
  comment('get records with sort/limit/offset')
  return test(`/animal?${qs.stringify({
    sort: 'name',
    limit: 2,
    offset: 1
  })}`, null, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ 'Babby', 'Kantorin' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('create records')
  return test(`/animal`, {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: [ {
      name: 'Ayy lmao',
      nicknames: [ 'ayy', 'lmao' ],
      owner: 1
    } ]
  }, response => {
    assert(response.status === 201, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ 'Ayy lmao' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('update records')
  return test(`/animal`, {
    method: 'patch',
    headers: { 'Content-Type': 'application/json' },
    body: [ {
      id: '/wtf',
      replace: { name: 1234 }
    } ]
  }, response => {
    assert(response.status === 200, 'status is correct')
    assert(~response.headers['content-type'].indexOf('application/json'),
      'content type is correct')
    assert(deepEqual(response.body.records.map(record => record.name),
      [ '1234' ]), 'response body is correct')
  })
})

run((assert, comment) => {
  comment('delete records')
  return test(`/animal/1,%2Fwtf`, {
    method: 'delete'
  }, response => {
    assert(response.status === 204, 'status is correct')
    assert(response.body.length === 0, 'body is empty')
  })
})

run((assert, comment) => {
  comment('respond to options: index')
  return test('/', { method: 'options' }, response => {
    assert(response.status === 204, 'status is correct')
    assert(response.body.length === 0, 'body is empty')
    assert(response.headers['allow'] === 'GET',
      'allow header is correct')
  })
})
<|endoftext|>


<commit_before>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("load method", function suite() {
	it("should initialize display if it was not on instantiation", function(done) {
		this.timeout(10000);
		var called = false;
		WebKit(0, function(err) {
			expect(err).to.not.be.ok();
			called = true;
		}).load('http://google.com', function(err) {
			expect(this.status).to.be(200);
			expect(err).to.not.be.ok();
			expect(called).to.be.ok();
			done();
		});
	});
	it("should load html content", function(done) {
		this.timeout(1000);
		WebKit().load("http://localhost", {content: '
test
'}, function(err) {
			expect(err).to.be(null);
		}).wait('ready').html(function(err, html) {
			expect(err).to.not.be.ok();
			expect(html).to.be("
test
");
		}).wait('idle', done);
	});
	it("should load html content and filter some requests", function(done) {
		this.timeout(1000);
		var haspng = false;
		var hasjs = false;
		WebKit().load("http://localhost", {
			content: ''
		}, function(err) {
			expect(err).to.be(null);
		})
		.on('request', function(req) {
			req.cancel = /\.png$/.test(req.uri) || req.headers.Accept == "*/*";
		})
		.on('response', function(res) {
			if (/\.png$/.test(res.uri)) {
				haspng = true;
			}
			if (/\.js$/.test(res.uri)) {
				hasjs = true;
			}
		}).wait('idle', function() {
			expect(haspng).to.not.be.ok();
			expect(hasjs).to.not.be.ok();
			done();
		});
	});
	it("should callback with error when url cannot be resolved", function(done) {
		this.timeout(10000);
		WebKit().load("http://atipepipapa-sdqdqsd.com", function(err) {
			expect(err).to.be.ok();
			done();
		});
	});
	it("should 404", function(done) {
		this.timeout(1000);
		WebKit().load("http://google.com/sdfsdfsdf", function(err) {
			expect(err).to.be(404);
			done();
		});
	});
	it("should allow to load another uri just after", function(done) {
		this.timeout(5000);
		WebKit().load('http://google.com').load('http://geoip.edagames.com', function() {
			this.once('response', function(res) {
				res.data(function(err, data) {
					expect(JSON.parse(data.toString()).country).to.be.ok();
					done();
				});
			});
		});
	});
	it("should filter requests by regexp and let the main request go", function(done) {
		this.timeout(5000);
		var onlyjs = /\.js/;
		var hadmain = false;
		WebKit().on('response', function(res) {
			if (res.uri == this.uri) hadmain = true;
		}).load('http://github.com', {allow: onlyjs}).wait('idle', function(err) {
			expect(err).to.not.be.ok();
			expect(hadmain).to.be(true);
			done();
		});
	});
	it("should time out", function(done) {
		this.timeout(500);
		WebKit().load('http://google.com', {timeout:50}, function(err) {
			expect(err).to.be.ok();
			expect(this.status).to.be(0);
			done();
		});
	});
	it("should time out then unload", function(done) {
		this.timeout(5000);
		WebKit().load('http://google.com', {timeout:50}, function(err) {
			expect(err).to.be.ok();
			expect(this.status).to.be(0);
			this.unload(function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});
	it("should not stop after a stop call", function(done) {
		this.timeout(21000);
		WebKit().load('http://google.com', function(err) {
			expect(err).to.not.be.ok();
			this.stop(function(err, wasLoading) {
				expect(err).to.not.be.ok();
				expect(wasLoading).to.be(true);
			});
		}).wait('load', function(err) {
			this.stop(function(err, wasLoading) {
				expect(wasLoading).to.be(false);
				done();
			});
		});
	});
	it("should fail gracefully", function(done) {
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 501;
			res.end("fail");
		}).listen(8011);
			WebKit().load("http://localhost:8011", function(err, view) {
			expect(err).to.be(501);
			setImmediate(function() {
				server.close();
				done();
			});
		});
	});
	it("should fail gracefully even with a timeout", function(done) {
		var server = require('http').createServer(function(req, res) {
			setTimeout(function() {
				res.statusCode = 501;
				res.end("fail");
			}, 1000);
		}).listen(8012);
			WebKit().load("http://localhost:8012", {timeout: 500}, function(err, view) {
			expect(err).not.to.be(501);
			this.stop(function(err, wasLoading) {
				expect(err).to.not.be.ok();
				expect(wasLoading).to.be(false);
			});
			setTimeout(function() {
				server.close();
				done();
			}, 1000);
		});
	});
	it("should set request headers", function(done) {
		var server = require('http').createServer(function(req, res) {
			expect(req.headers.custom).to.be("tada");
			expect(req.headers.accept).to.be("text/tomo");
			expect(req.headers.cookie).to.be(undefined)
			res.statusCode = 200;
			res.end("test");
		}).listen(8018);
		WebKit().load("http://localhost:8018").on('request', function(req) {
			req.headers.custom = "tada";
			req.headers.Accept = "text/tomo";
			req.headers.Cookie = 'abc="xyzzy!"; Expires=Tue, 18 Oct 2511 07:05:03 GMT; Path=/;';
		}).wait('ready', function(err) {
			setTimeout(function() {
				server.close();
				done();
			}, 100);
		});
	});
});
<commit_msg>Missing semicolon<commit_after>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("load method", function suite() {
	it("should initialize display if it was not on instantiation", function(done) {
		this.timeout(10000);
		var called = false;
		WebKit(0, function(err) {
			expect(err).to.not.be.ok();
			called = true;
		}).load('http://google.com', function(err) {
			expect(this.status).to.be(200);
			expect(err).to.not.be.ok();
			expect(called).to.be.ok();
			done();
		});
	});
	it("should load html content", function(done) {
		this.timeout(1000);
		WebKit().load("http://localhost", {content: '
test
'}, function(err) {
			expect(err).to.be(null);
		}).wait('ready').html(function(err, html) {
			expect(err).to.not.be.ok();
			expect(html).to.be("
test
");
		}).wait('idle', done);
	});
	it("should load html content and filter some requests", function(done) {
		this.timeout(1000);
		var haspng = false;
		var hasjs = false;
		WebKit().load("http://localhost", {
			content: ''
		}, function(err) {
			expect(err).to.be(null);
		})
		.on('request', function(req) {
			req.cancel = /\.png$/.test(req.uri) || req.headers.Accept == "*/*";
		})
		.on('response', function(res) {
			if (/\.png$/.test(res.uri)) {
				haspng = true;
			}
			if (/\.js$/.test(res.uri)) {
				hasjs = true;
			}
		}).wait('idle', function() {
			expect(haspng).to.not.be.ok();
			expect(hasjs).to.not.be.ok();
			done();
		});
	});
	it("should callback with error when url cannot be resolved", function(done) {
		this.timeout(10000);
		WebKit().load("http://atipepipapa-sdqdqsd.com", function(err) {
			expect(err).to.be.ok();
			done();
		});
	});
	it("should 404", function(done) {
		this.timeout(1000);
		WebKit().load("http://google.com/sdfsdfsdf", function(err) {
			expect(err).to.be(404);
			done();
		});
	});
	it("should allow to load another uri just after", function(done) {
		this.timeout(5000);
		WebKit().load('http://google.com').load('http://geoip.edagames.com', function() {
			this.once('response', function(res) {
				res.data(function(err, data) {
					expect(JSON.parse(data.toString()).country).to.be.ok();
					done();
				});
			});
		});
	});
	it("should filter requests by regexp and let the main request go", function(done) {
		this.timeout(5000);
		var onlyjs = /\.js/;
		var hadmain = false;
		WebKit().on('response', function(res) {
			if (res.uri == this.uri) hadmain = true;
		}).load('http://github.com', {allow: onlyjs}).wait('idle', function(err) {
			expect(err).to.not.be.ok();
			expect(hadmain).to.be(true);
			done();
		});
	});
	it("should time out", function(done) {
		this.timeout(500);
		WebKit().load('http://google.com', {timeout:50}, function(err) {
			expect(err).to.be.ok();
			expect(this.status).to.be(0);
			done();
		});
	});
	it("should time out then unload", function(done) {
		this.timeout(5000);
		WebKit().load('http://google.com', {timeout:50}, function(err) {
			expect(err).to.be.ok();
			expect(this.status).to.be(0);
			this.unload(function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});
	it("should not stop after a stop call", function(done) {
		this.timeout(21000);
		WebKit().load('http://google.com', function(err) {
			expect(err).to.not.be.ok();
			this.stop(function(err, wasLoading) {
				expect(err).to.not.be.ok();
				expect(wasLoading).to.be(true);
			});
		}).wait('load', function(err) {
			this.stop(function(err, wasLoading) {
				expect(wasLoading).to.be(false);
				done();
			});
		});
	});
	it("should fail gracefully", function(done) {
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 501;
			res.end("fail");
		}).listen(8011);
			WebKit().load("http://localhost:8011", function(err, view) {
			expect(err).to.be(501);
			setImmediate(function() {
				server.close();
				done();
			});
		});
	});
	it("should fail gracefully even with a timeout", function(done) {
		var server = require('http').createServer(function(req, res) {
			setTimeout(function() {
				res.statusCode = 501;
				res.end("fail");
			}, 1000);
		}).listen(8012);
			WebKit().load("http://localhost:8012", {timeout: 500}, function(err, view) {
			expect(err).not.to.be(501);
			this.stop(function(err, wasLoading) {
				expect(err).to.not.be.ok();
				expect(wasLoading).to.be(false);
			});
			setTimeout(function() {
				server.close();
				done();
			}, 1000);
		});
	});
	it("should set request headers", function(done) {
		var server = require('http').createServer(function(req, res) {
			expect(req.headers.custom).to.be("tada");
			expect(req.headers.accept).to.be("text/tomo");
			expect(req.headers.cookie).to.be(undefined);
			res.statusCode = 200;
			res.end("test");
		}).listen(8018);
		WebKit().load("http://localhost:8018").on('request', function(req) {
			req.headers.custom = "tada";
			req.headers.Accept = "text/tomo";
			req.headers.Cookie = 'abc="xyzzy!"; Expires=Tue, 18 Oct 2511 07:05:03 GMT; Path=/;';
		}).wait('ready', function(err) {
			setTimeout(function() {
				server.close();
				done();
			}, 100);
		});
	});
});
<|endoftext|>


<commit_before>/* jshint strict: false */
/* global before, after, describe, it */
var Buffer = require('buffer').Buffer,
    chai = require('chai'),
    File = require('gulp-util').File,
    fs = require('fs'),
    path = require('path'),
    uglify = require('../');

require('mocha');

var should = chai.should();

var isWindows = process.platform === 'win32';

var FILE_0_CONTENTS = 'function test1() { var asdf = 3; }',
    FILE_0_UGLIFIED = 'function test1(){}',
    FILE_0_UNCOMPRESSED = 'function test1(){var a=3}',
    FILE_0_ENCLOSED = '(function(){function a(){var a=3}})();',
    FILE_0_ENCLOSED_W_ARGS = '(function(a){function b(){var a=3}})(test);',
    FILE_0_ENCLOSED_W_MULTIPLE_ARGS = '(function(a,b){function a(){var a=3}})(test1,test2);',
    FILE_0_WRAPPED = '(function(a,b){b[\"test\"]=a;function c(){var a=3}})({},function(){return this}());',
    FILE_0_WRAPPED_W_EXPORT = '(function(a,b){b[\"test\"]=a;function c(){var a=3}a[\"test1\"]=c})({},function(){return this}());',
    FILE_0_UGLIFIED_WITH_SM = 'function test1(){}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map';

var FILE_1_CONTENTS = 'function test2() { var qwerty = \'keyboard\'; return qwerty; }';

var FILE_0_1_UGLIFIED = 'function test1(){}function test2(){var a="keyboard";return a}',
    FILE_0_1_UGLIFIED_WITH_SM = 'function test1(){}function test2(){var a=\"keyboard\";return a}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map',
    FILE_0_1_UNCOMPRESSED = 'function test1(){var a=3}function test2(){var a=\"keyboard\";return a}',
    FILE_0_1_UNMANGLED = 'function test1(){}function test2(){var qwerty=\"keyboard\";return qwerty}';

var FILE_0_SOURCE_MAP,
    FILE_0_1_SOURCE_MAP;

if (isWindows) {
  FILE_0_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE_0_1_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js","test\\\\file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
} else {
  FILE_0_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE_0_1_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js","test/file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
}

function testFiles(stream, contents, expectedContents, expectedPaths) {
  it('should uglify one or several files', function(done) {
    var index = 0;

    stream.on('data', function(uglifiedFile){
      should.exist(uglifiedFile);
      should.exist(uglifiedFile.path);
      should.exist(uglifiedFile.relative);
      should.exist(uglifiedFile.contents);

      var newFilePath = path.resolve(uglifiedFile.path);
      var expectedFilePath = path.resolve(expectedPaths[index]);
      newFilePath.should.equal(expectedFilePath);

      String(uglifiedFile.contents).should.equal(expectedContents[index]);
      Buffer.isBuffer(uglifiedFile.contents).should.equal(true);

      index++;
    });

    stream.on('end', function() {
      done();
    });

    contents.forEach(function(contents, i) {
      stream.write(new File({
        cwd: '.',
        base: '.',
        path: 'test/file' + i.toString() + '.js',
        contents: new Buffer(contents)
      }));
    });

    stream.end();
  });
}

describe('gulp-uglifyjs', function() {
  before(function() {
    fs.writeFileSync('test/file0.js', [FILE_0_CONTENTS]);
    fs.writeFileSync('test/file1.js', [FILE_1_CONTENTS]);
  });

  after(function() {
    fs.unlinkSync('test/file0.js');
    fs.unlinkSync('test/file1.js');
  });

  describe('uglify()', function() {
    testFiles(uglify(), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify(), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED], ['test/file0.js']);

    it('should not fail when no file is given', function() {
      var stream = uglify();
      stream.write(new File({ contents: null }));
      stream.end();
    });
  });

  describe('uglify(filename)', function() {
    testFiles(uglify('test.js'), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js'), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED], ['test.js']);
  });

  describe('uglify(filename, options)', function() {
    testFiles(uglify('test.js', { mangle: false }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js', { mangle: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNMANGLED], ['test.js']);
  });

  describe('uglify(options) with sourcemap', function() {
    testFiles(uglify({ outSourceMap: true }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED_WITH_SM, FILE_0_SOURCE_MAP], ['test/file0.js', 'test/file0.js.map']);
    testFiles(uglify({ outSourceMap: true }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED_WITH_SM, FILE_0_1_SOURCE_MAP], ['test/file0.js', 'test/file0.js.map']);
  });

  describe('uglify(options) - no compress', function() {
    testFiles(uglify({ compress: false }), [FILE_0_CONTENTS], [FILE_0_UNCOMPRESSED], ['test/file0.js', 'test/file0.js.map']);
    testFiles(uglify({ compress: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNCOMPRESSED], ['test/file0.js']);
  });

  describe('uglify(options) - no mangle', function() {
    testFiles(uglify({ mangle: false }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify({ mangle: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNMANGLED], ['test/file0.js']);
  });

  describe('uglify(options) - enclose', function() {
    testFiles(uglify({ enclose: true, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED], ['test/file0.js']);
    testFiles(uglify({ enclose: { test: 'test' }, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED_W_ARGS], ['test/file0.js']);
    testFiles(uglify({ enclose: { test1: 'test1', test2: 'test2' }, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED_W_MULTIPLE_ARGS], ['test/file0.js']);
  });

  describe('uglify(options) - wrap', function() {
    testFiles(uglify({ wrap: 'test', compress: false }), [FILE_0_CONTENTS], [FILE_0_WRAPPED], ['test/file0.js']);
    testFiles(uglify({ wrap: 'test', compress: false, exportAll: true }), [FILE_0_CONTENTS], [FILE_0_WRAPPED_W_EXPORT], ['test/file0.js']);
  });
});<commit_msg>Adding tests for sourceMapIncludeSources<commit_after>/* jshint strict: false */
/* global before, after, describe, it */
var Buffer = require('buffer').Buffer,
    chai = require('chai'),
    File = require('gulp-util').File,
    fs = require('fs'),
    path = require('path'),
    uglify = require('../');

require('mocha');

var should = chai.should();

var isWindows = process.platform === 'win32';

var FILE_0_CONTENTS = 'function test1() { var asdf = 3; }',
    FILE_0_UGLIFIED = 'function test1(){}',
    FILE_0_UNCOMPRESSED = 'function test1(){var a=3}',
    FILE_0_ENCLOSED = '(function(){function a(){var a=3}})();',
    FILE_0_ENCLOSED_W_ARGS = '(function(a){function b(){var a=3}})(test);',
    FILE_0_ENCLOSED_W_MULTIPLE_ARGS = '(function(a,b){function a(){var a=3}})(test1,test2);',
    FILE_0_WRAPPED = '(function(a,b){b[\"test\"]=a;function c(){var a=3}})({},function(){return this}());',
    FILE_0_WRAPPED_W_EXPORT = '(function(a,b){b[\"test\"]=a;function c(){var a=3}a[\"test1\"]=c})({},function(){return this}());',
    FILE_0_UGLIFIED_WITH_SM = 'function test1(){}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map';

var FILE_1_CONTENTS = 'function test2() { var qwerty = \'keyboard\'; return qwerty; }';

var FILE_0_1_UGLIFIED = 'function test1(){}function test2(){var a="keyboard";return a}',
    FILE_0_1_UGLIFIED_WITH_SM = 'function test1(){}function test2(){var a=\"keyboard\";return a}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map',
    FILE_0_1_UNCOMPRESSED = 'function test1(){var a=3}function test2(){var a=\"keyboard\";return a}',
    FILE_0_1_UNMANGLED = 'function test1(){}function test2(){var qwerty=\"keyboard\";return qwerty}';

var FILE_0_SOURCE_MAP,
    FILE_0_SOURCE_MAP_INCLUDE_SOURCES,
    FILE_0_1_SOURCE_MAP;

if (isWindows) {
  FILE_0_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE_0_SOURCE_MAP_INCLUDE_SOURCES = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js"],"names":["test1"],"mappings":"AAAA,QAASA","sourcesContent":["function test1() { var asdf = 3; }"]}';
  FILE_0_1_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js","test\\\\file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
} else {
  FILE_0_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE_0_SOURCE_MAP_INCLUDE_SOURCES = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js"],"names":["test1"],"mappings":"AAAA,QAASA","sourcesContent":["function test1() { var asdf = 3; }"]}';
  FILE_0_1_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js","test/file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
}

function testFiles(stream, contents, expectedContents, expectedPaths) {
  it('should uglify one or several files', function(done) {
    var index = 0;

    stream.on('data', function(uglifiedFile){
      should.exist(uglifiedFile);
      should.exist(uglifiedFile.path);
      should.exist(uglifiedFile.relative);
      should.exist(uglifiedFile.contents);

      var newFilePath = path.resolve(uglifiedFile.path);
      var expectedFilePath = path.resolve(expectedPaths[index]);
      newFilePath.should.equal(expectedFilePath);

      String(uglifiedFile.contents).should.equal(expectedContents[index]);
      Buffer.isBuffer(uglifiedFile.contents).should.equal(true);

      index++;
    });

    stream.on('end', function() {
      done();
    });

    contents.forEach(function(contents, i) {
      stream.write(new File({
        cwd: '.',
        base: '.',
        path: 'test/file' + i.toString() + '.js',
        contents: new Buffer(contents)
      }));
    });

    stream.end();
  });
}

describe('gulp-uglifyjs', function() {
  before(function() {
    fs.writeFileSync('test/file0.js', [FILE_0_CONTENTS]);
    fs.writeFileSync('test/file1.js', [FILE_1_CONTENTS]);
  });

  after(function() {
    fs.unlinkSync('test/file0.js');
    fs.unlinkSync('test/file1.js');
  });

  describe('uglify()', function() {
    testFiles(uglify(), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify(), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED], ['test/file0.js']);

    it('should not fail when no file is given', function() {
      var stream = uglify();
      stream.write(new File({ contents: null }));
      stream.end();
    });
  });

  describe('uglify(filename)', function() {
    testFiles(uglify('test.js'), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js'), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED], ['test.js']);
  });

  describe('uglify(filename, options)', function() {
    testFiles(uglify('test.js', { mangle: false }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js', { mangle: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNMANGLED], ['test.js']);
  });

  describe('uglify(options) with sourcemap', function() {
    testFiles(uglify({ outSourceMap: true }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED_WITH_SM, FILE_0_SOURCE_MAP], ['test/file0.js', 'test/file0.js.map']);
    testFiles(uglify({ outSourceMap: true }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UGLIFIED_WITH_SM, FILE_0_1_SOURCE_MAP], ['test/file0.js', 'test/file0.js.map']);
  });

  describe('uglify(options) - no compress', function() {
    testFiles(uglify({ compress: false }), [FILE_0_CONTENTS], [FILE_0_UNCOMPRESSED], ['test/file0.js', 'test/file0.js.map']);
    testFiles(uglify({ compress: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNCOMPRESSED], ['test/file0.js']);
  });

  describe('uglify(options) - no mangle', function() {
    testFiles(uglify({ mangle: false }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify({ mangle: false }), [FILE_0_CONTENTS, FILE_1_CONTENTS], [FILE_0_1_UNMANGLED], ['test/file0.js']);
  });

  describe('uglify(options) - enclose', function() {
    testFiles(uglify({ enclose: true, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED], ['test/file0.js']);
    testFiles(uglify({ enclose: { test: 'test' }, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED_W_ARGS], ['test/file0.js']);
    testFiles(uglify({ enclose: { test1: 'test1', test2: 'test2' }, compress: false }), [FILE_0_CONTENTS], [FILE_0_ENCLOSED_W_MULTIPLE_ARGS], ['test/file0.js']);
  });

  describe('uglify(options) - wrap', function() {
    testFiles(uglify({ wrap: 'test', compress: false }), [FILE_0_CONTENTS], [FILE_0_WRAPPED], ['test/file0.js']);
    testFiles(uglify({ wrap: 'test', compress: false, exportAll: true }), [FILE_0_CONTENTS], [FILE_0_WRAPPED_W_EXPORT], ['test/file0.js']);
  });

  describe('uglify(options) - sourceMapIncludeSources', function() {
    testFiles(uglify({ outSourceMap: true, sourceMapIncludeSources: true }), [FILE_0_CONTENTS], [FILE_0_UGLIFIED_WITH_SM, FILE_0_SOURCE_MAP_INCLUDE_SOURCES], ['test/file0.js', 'test/file0.js.map']);
  });
});<|endoftext|>


<commit_before>var URL = window.URL || window.webkitURL;

var lastFile = null;

var options = {
    quality: 0.9,
    width: 1000,
    height: 618
};

var resultImg = document.querySelector('#result'),
    sourceImg = document.querySelector('#source'),
    resultInfo = document.querySelector('#result-info'),
    sourceInfo = document.querySelector('#source-info');

var compress = function(file) {
    file = file || lastFile;

    if (!file) return;

    lastFile = file;

    URL.revokeObjectURL(sourceImg.src);
    URL.revokeObjectURL(resultImg.src);

    sourceImg.src = resultImg.src = '';
    sourceInfo.textContent = resultInfo.textContent = '';

    var compressor = new CanvasCompress(options);
    var startTime = Date.now();

    compressor.process(file).then(function(res) {
        var source = res.source,
            result = res.result;

        sourceImg.src = URL.createObjectURL(source.blob);
        resultImg.src = URL.createObjectURL(result.blob);

        sourceInfo.textContent = [
            'File size: ' + (source.blob.size / 1024 ).toFixed(2) + 'KB',
            'File type: ' + source.blob.type,
            'Dimensions: ' + source.width + ' * ' + source.height
        ].join('\n');

        resultInfo.textContent = [
            'File size: ' + (result.blob.size / 1024 ).toFixed(2) + 'KB',
            'File type: ' + result.blob.type,
            'Dimensions: ' + result.width + ' * ' + result.height,
            'Compress Rate: ' + ((1 - result.blob.size / source.blob.size) * 100).toFixed(2) + '%',
            'Compress duration: ' + (Date.now() - startTime)+ 'ms'
        ].join('\n');
    }).catch(alert);
}

Array.prototype.forEach.call(document.querySelectorAll('input[type="range"]'), function(input) {
    var value = input.nextElementSibling;
    var prop = input.name;

    input.value = options[prop];
    value.textContent = input.value;

    input.addEventListener('change', function() {
        options[prop] = value.textContent = input.value;
        compress();
    });
});

document.querySelector('#upload').addEventListener('change', function() {
    compress(this.files[0]);
});<commit_msg>update(demo): auto detect file type<commit_after>var URL = window.URL || window.webkitURL;

var lastFile = null;

var options = {
    quality: 0.9,
    width: 1000,
    height: 618
};

var resultImg = document.querySelector('#result'),
    sourceImg = document.querySelector('#source'),
    resultInfo = document.querySelector('#result-info'),
    sourceInfo = document.querySelector('#source-info');

var compress = function(file) {
    file = file || lastFile;

    if (!file) return;

    lastFile = file;

    URL.revokeObjectURL(sourceImg.src);
    URL.revokeObjectURL(resultImg.src);

    sourceImg.src = resultImg.src = '';
    sourceInfo.textContent = resultInfo.textContent = '';

    var compressor = new CanvasCompress(Object.assign({
        type: file.type,
    }, options));
    var startTime = Date.now();

    compressor.process(file).then(function(res) {
        var source = res.source,
            result = res.result;

        sourceImg.src = URL.createObjectURL(source.blob);
        resultImg.src = URL.createObjectURL(result.blob);

        sourceInfo.textContent = [
            'File size: ' + (source.blob.size / 1024 ).toFixed(2) + 'KB',
            'File type: ' + source.blob.type,
            'Dimensions: ' + source.width + ' * ' + source.height
        ].join('\n');

        resultInfo.textContent = [
            'File size: ' + (result.blob.size / 1024 ).toFixed(2) + 'KB',
            'File type: ' + result.blob.type,
            'Dimensions: ' + result.width + ' * ' + result.height,
            'Compress Rate: ' + ((1 - result.blob.size / source.blob.size) * 100).toFixed(2) + '%',
            'Compress duration: ' + (Date.now() - startTime)+ 'ms'
        ].join('\n');
    }).catch(alert);
}

Array.prototype.forEach.call(document.querySelectorAll('input[type="range"]'), function(input) {
    var value = input.nextElementSibling;
    var prop = input.name;

    input.value = options[prop];
    value.textContent = input.value;

    input.addEventListener('change', function() {
        options[prop] = value.textContent = input.value;
        compress();
    });
});

document.querySelector('#upload').addEventListener('change', function() {
    compress(this.files[0]);
});
<|endoftext|>


<commit_before>import { promisify } from 'util'

import test from 'ava'
import execa from 'execa'
import fetch from 'cross-fetch'
import { getBinPath } from 'get-bin-path'

const pSetTimeout = promisify(setTimeout)

const BINARY_PATH = getBinPath()
const EXAMPLE_DIR = `${__dirname}/../../examples`

test('Smoke test', async t => {
  const server = execa(await BINARY_PATH, {
    env: { NODE_ENV: 'dev' },
    cwd: EXAMPLE_DIR,
  })
  const [{ stdout, stderr }] = await Promise.all([
    getOutput(server),
    request(server),
  ])
  const message = normalizeStdout({ stdout })
  t.snapshot({ message, stderr })
})

const getOutput = async function(server) {
  try {
    await server
  } catch (error) {
    return error
  }
}

const request = async function(server) {
  await pSetTimeout(STARTUP_TIMEOUT)
  await fetch('http://localhost:5001/rest/pets/2')
  server.kill('SIGKILL')
}

const normalizeStdout = function({ stdout }) {
  // eslint-disable-next-line fp/no-mutating-methods
  return stdout
    .split('\n')
    .map(normalizeLine)
    .sort()
    .join('\n')
}

const normalizeLine = function(line) {
  return line
    .replace(START_LINE_REGEXP, '')
    .replace(PORT_REGEXP, '$1')
    .trim()
}

const STARTUP_TIMEOUT = 60e3

const START_LINE_REGEXP = /^.{98}/u
const PORT_REGEXP = /(Listening on).*/u
<commit_msg>Refactoring<commit_after>import { promisify } from 'util'

import test from 'ava'
import execa from 'execa'
import fetch from 'cross-fetch'
import { getBinPath } from 'get-bin-path'

const pSetTimeout = promisify(setTimeout)

const BINARY_PATH = getBinPath()
const EXAMPLE_DIR = `${__dirname}/../../examples`

test('Smoke test', async t => {
  const server = execa(await BINARY_PATH, {
    env: { NODE_ENV: 'dev' },
    cwd: EXAMPLE_DIR,
  })
  const [{ stdout, stderr }] = await Promise.all([
    getOutput(server),
    request(server),
  ])
  const message = normalizeStdout({ stdout })
  t.snapshot({ message, stderr })
})

const getOutput = async function(server) {
  try {
    await server
  } catch (error) {
    return error
  }
}

const request = async function(server) {
  await pSetTimeout(STARTUP_TIMEOUT)
  await fetch('http://localhost:5001/rest/pets/2')
  server.kill('SIGKILL')
}

const normalizeStdout = function({ stdout }) {
  // eslint-disable-next-line fp/no-mutating-methods
  return stdout
    .split('\n')
    .map(normalizeLine)
    .sort()
    .join('\n')
}

const normalizeLine = function(line) {
  return line
    .replace(START_LINE_REGEXP, '')
    .replace(PORT_REGEXP, '$1')
    .trim()
}

const STARTUP_TIMEOUT = 6e4

const START_LINE_REGEXP = /^.{98}/u
const PORT_REGEXP = /(Listening on).*/u
<|endoftext|>


<commit_before>/* eslint-disable no-console, no-duplicate-imports, import/no-duplicates */
import proxyquire from 'proxyquire';
import describe from '../src';
import { specStream } from '../src';

describe('RxT', (it) => {
    it('should run a simple given/when/then test', test => test
        .given('givenWhenThen')
        .whenObserving((testFile) => {
            const spec = proxyquire(`./samples/${testFile}`, {
                '../../src': {
                    default: specStream,
                },
            });
            return spec;
        })
        .then(result => result.should.have.keys('should capitalize just hello'))
    );
});
<commit_msg>Added more specific assertions.<commit_after>/* eslint-disable no-console, no-duplicate-imports, import/no-duplicates */
import proxyquire from 'proxyquire';
import describe from '../src';
import { specStream } from '../src';

describe('RxT', (it) => {
    it('should run a simple given/when/then test', test => test
        .given('givenWhenThen')
        .whenObserving((testFile) => {
            const spec = proxyquire(`./samples/${testFile}`, {
                '../../src': {
                    default: specStream,
                },
            });
            return spec;
        })
        .then((result) => {
            result.should.have.keys('should capitalize just hello');
            result['should capitalize just hello'].should.have.keys('result');
            result['should capitalize just hello'].result.should.equal('pass');
        })
    );
});
<|endoftext|>


<commit_before>var concat = require('../');
var should = require('should');
var path = require('path');
var assert = require('stream-assert');
var test = require('./test-stream');
var File = require('gulp-util').File;
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
require('mocha');

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

describe('gulp-concat', function() {
  describe('concat()', function() {
    it('should throw, when arguments is missing', function () {
      (function() {
        concat();
      }).should.throw('Missing file option for gulp-concat');
    });

    it('should ignore null files', function (done) {
      var stream = concat('test.js');
      stream
        .pipe(assert.length(0))
        .pipe(assert.end(done));
      stream.write(new File());
      stream.end();
    });

    it('should emit error on streamed file', function (done) {
      gulp.src(fixtures('*'), { buffer: false })
        .pipe(concat('test.js'))
        .on('error', function (err) {
          err.message.should.eql('Streaming not supported');
          done();
        });
    });

    it('should concat one file', function (done) {
      test('wadap')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap'); }))
        .pipe(assert.end(done));
    });

    it('should concat multiple files', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap\ndoe'); }))
        .pipe(assert.end(done));
    });

    it('should concatinate buffers', function (done) {
      test([65, 66], [67, 68], [69, 70])
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('AB\nCD\nEF'); }))
        .pipe(assert.end(done));
    });

    it('should preserve mode from files', function (done) {
      test('wadaup')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.stat.mode.should.eql(0666); }))
        .pipe(assert.end(done));
    });

    it('should take path from first file', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (newFile) {
          var newFilePath = path.resolve(newFile.path);
          var expectedFilePath = path.resolve('/home/contra/test/test.js');
          newFilePath.should.equal(expectedFilePath);
        }))
        .pipe(assert.end(done));
    });

    it('should preserve relative path from files', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.relative.should.eql('test.js'); }))
        .pipe(assert.end(done));
    });

    it('should support source maps', function (done) {
      gulp.src(fixtures('*'))
        .pipe(sourcemaps.init())
        .pipe(concat('all.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) {
          d.sourceMap.sources.should.have.length(2);
          d.sourceMap.file.should.eql('all.js');
        }))
        .pipe(assert.end(done));
    });

    it('should not fail if no files were input', function(done) {
      var stream = concat('test.js');
      stream.end();
      done();
    });

    describe('options', function () {
      it('should support newLine', function (done) {
        test('wadap', 'doe')
          .pipe(concat('test.js', {newLine: '\r\n'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap\r\ndoe'); }))
          .pipe(assert.end(done));
      })

      it('should support empty newLine', function (done) {
        test('wadap', 'doe')
          .pipe(concat('test.js', {newLine: ''}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadapdoe'); }))
          .pipe(assert.end(done));
      })
    });

    describe('with object as argument', function () {
      it('should throw without path', function () {
        (function() {
          concat({ path: undefined });
        }).should.throw('Missing path in file options for gulp-concat');
      });

      it('should create file based on path property', function (done) {
        test('wadap')
          .pipe(concat({path: 'new.txt'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.path.should.eql('new.txt'); }))
          .pipe(assert.end(done));
      });

      it('should calculate relative path from cwd and path in arguments', function (done) {
        test('wadap')
          .pipe(concat({cwd: '/home/contra', path: '/home/contra/test/new.txt'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.relative.should.eql('test/new.txt'); }))
          .pipe(assert.end(done));
      });
    });
  });
});
<commit_msg>Test for #85<commit_after>var concat = require('../');
var should = require('should');
var path = require('path');
var assert = require('stream-assert');
var test = require('./test-stream');
var File = require('gulp-util').File;
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
require('mocha');

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

describe('gulp-concat', function() {
  describe('concat()', function() {
    it('should throw, when arguments is missing', function () {
      (function() {
        concat();
      }).should.throw('Missing file option for gulp-concat');
    });

    it('should ignore null files', function (done) {
      var stream = concat('test.js');
      stream
        .pipe(assert.length(0))
        .pipe(assert.end(done));
      stream.write(new File());
      stream.end();
    });

    it('should emit error on streamed file', function (done) {
      gulp.src(fixtures('*'), { buffer: false })
        .pipe(concat('test.js'))
        .on('error', function (err) {
          err.message.should.eql('Streaming not supported');
          done();
        });
    });

    it('should concat one file', function (done) {
      test('wadap')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap'); }))
        .pipe(assert.end(done));
    });

    it('should concat multiple files', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap\ndoe'); }))
        .pipe(assert.end(done));
    });

    it('should concatinate buffers', function (done) {
      test([65, 66], [67, 68], [69, 70])
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.contents.toString().should.eql('AB\nCD\nEF'); }))
        .pipe(assert.end(done));
    });

    it('should preserve mode from files', function (done) {
      test('wadaup')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.stat.mode.should.eql(0666); }))
        .pipe(assert.end(done));
    });

    it('should take path from first file', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (newFile) {
          var newFilePath = path.resolve(newFile.path);
          var expectedFilePath = path.resolve('/home/contra/test/test.js');
          newFilePath.should.equal(expectedFilePath);
        }))
        .pipe(assert.end(done));
    });

    it('should preserve relative path from files', function (done) {
      test('wadap', 'doe')
        .pipe(concat('test.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) { d.relative.should.eql('test.js'); }))
        .pipe(assert.end(done));
    });

    it('should support source maps', function (done) {
      gulp.src(fixtures('*'))
        .pipe(sourcemaps.init())
        .pipe(concat('all.js'))
        .pipe(assert.length(1))
        .pipe(assert.first(function (d) {
          d.sourceMap.sources.should.have.length(2);
          d.sourceMap.file.should.eql('all.js');
        }))
        .pipe(assert.end(done));
    });

    describe('should not fail if no files were input', function () {
      it('when argument is a string', function(done) {
        var stream = concat('test.js');
        stream.end();
        done();
      });

      it('when argument is an object', function(done) {
        var stream = concat({path: 'new.txt'});
        stream.end();
        done();
      });
    });

    describe('options', function () {
      it('should support newLine', function (done) {
        test('wadap', 'doe')
          .pipe(concat('test.js', {newLine: '\r\n'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadap\r\ndoe'); }))
          .pipe(assert.end(done));
      })

      it('should support empty newLine', function (done) {
        test('wadap', 'doe')
          .pipe(concat('test.js', {newLine: ''}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.contents.toString().should.eql('wadapdoe'); }))
          .pipe(assert.end(done));
      })
    });

    describe('with object as argument', function () {
      it('should throw without path', function () {
        (function() {
          concat({ path: undefined });
        }).should.throw('Missing path in file options for gulp-concat');
      });

      it('should create file based on path property', function (done) {
        test('wadap')
          .pipe(concat({path: 'new.txt'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.path.should.eql('new.txt'); }))
          .pipe(assert.end(done));
      });

      it('should calculate relative path from cwd and path in arguments', function (done) {
        test('wadap')
          .pipe(concat({cwd: '/home/contra', path: '/home/contra/test/new.txt'}))
          .pipe(assert.length(1))
          .pipe(assert.first(function (d) { d.relative.should.eql('test/new.txt'); }))
          .pipe(assert.end(done));
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('child_process').exec;
var gutil = require('gulp-util');
var git = require('../');

describe('gulp-git', function(){
  var repo = 'https://github.com/agualbbus/gulp-git-deploy-test.git';

//  beforeEach(function(done){
//
//    exec('git clone '+repo, function(err){
//      if (err) return done(err);
//      done();
//    })
//  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<commit_msg>before and after describe<commit_after>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('exec-chainable');
var gutil = require('gulp-util');
var git = require('../');

describe('gulp-git', function(){
  var repo = 'https://github.com/agualbbus/gulp-git-deploy-test.git';

  before(function(done){
    exec('git checkout -b testing-branch ')
    .then(function(stdout){
      done();
    });

  });

  after(function(){
    exec('git branch -d testing-branch ')
  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<|endoftext|>


<commit_before>import { fileURLToPath } from 'url'
import { promisify } from 'util'

import test from 'ava'
import execa from 'execa'
import { getBinPath } from 'get-bin-path'
import got from 'got'

// TODO: replace with `timers/promises` `setTimeout()` after dropping support
// for Node <15.0.0
const pSetTimeout = promisify(setTimeout)

const EXAMPLE_DIR = fileURLToPath(new URL('../../examples', import.meta.url))

test('Smoke test', async (t) => {
  const binPath = await getBinPath()
  const server = execa('node', ['--no-warnings', binPath], {
    env: { NODE_ENV: 'dev' },
    cwd: EXAMPLE_DIR,
    reject: false,
  })
  const [{ stdout, stderr }] = await Promise.all([server, request(server)])
  const message = normalizeStdout(stdout)
  t.snapshot({ message, stderr })
})

const request = async function (server) {
  await pSetTimeout(STARTUP_TIMEOUT)
  await got('http://localhost:5001/rest/pets/2')
  server.kill('SIGKILL')
}

const normalizeStdout = function (stdout) {
  // eslint-disable-next-line fp/no-mutating-methods
  return stdout.split('\n').map(normalizeLine).sort().join('\n')
}

const normalizeLine = function (line) {
  return line.replace(START_LINE_REGEXP, '').replace(PORT_REGEXP, '$1').trim()
}

const STARTUP_TIMEOUT = 6e4

const START_LINE_REGEXP = /^.{98}/u
const PORT_REGEXP = /(Listening on).*/u
<commit_msg>Improve tests<commit_after>import { fileURLToPath } from 'url'
import { promisify } from 'util'

import test from 'ava'
import execa from 'execa'
import { getBinPath } from 'get-bin-path'
import got from 'got'

// TODO: replace with `timers/promises` `setTimeout()` after dropping support
// for Node <15.0.0
const pSetTimeout = promisify(setTimeout)

const EXAMPLE_DIR = fileURLToPath(new URL('../../examples', import.meta.url))

test('Smoke test', async (t) => {
  const binPath = await getBinPath()
  const server = execa('node', [binPath], {
    env: { NODE_ENV: 'dev' },
    cwd: EXAMPLE_DIR,
    reject: false,
  })
  const [{ stdout, stderr }] = await Promise.all([server, request(server)])
  const message = normalizeStdout(stdout)
  t.snapshot({ message, stderr })
})

const request = async function (server) {
  await pSetTimeout(STARTUP_TIMEOUT)
  await got('http://localhost:5001/rest/pets/2')
  server.kill('SIGKILL')
}

const normalizeStdout = function (stdout) {
  // eslint-disable-next-line fp/no-mutating-methods
  return stdout.split('\n').map(normalizeLine).sort().join('\n')
}

const normalizeLine = function (line) {
  return line.replace(START_LINE_REGEXP, '').replace(PORT_REGEXP, '$1').trim()
}

const STARTUP_TIMEOUT = 6e4

const START_LINE_REGEXP = /^.{98}/u
const PORT_REGEXP = /(Listening on).*/u
<|endoftext|>


<commit_before>(function() {
    'use strict';

    let mapa    = require('..'),
        test    = require('tape');

    let inc = i => () => ++i;

    test('map newly created array', t => {
        let result = mapa(inc(0), Array(5));

        t.deepEqual(result, [1,2,3,4,5]);
        t.end();
    });

    test('arguments: no fn', t => {
        t.throws(mapa, /fn should be function!/, 'should throw when no fn');
        t.end();
    });

    test('arguments: no lists', t => {
        let fn  = () => mapa(inc);

        t.throws(fn, /list should be an array!/, 'should throw when no list');
        t.end();
    });
})();
<commit_msg>test(mapa) add map array<commit_after>(function() {
    'use strict';

    let mapa    = require('..'),
        test    = require('tape');

    test('map array', t => {
        let inc     = i => ++i;
        let result  = mapa(inc, [1,2,3,4,5]);

        t.deepEqual(result, [2,3,4,5,6]);
        t.end();
    });

    test('map newly created array', t => {
        let inc = i => () => ++i;
        let result = mapa(inc(0), Array(5));

        t.deepEqual(result, [1,2,3,4,5]);
        t.end();
    });

    test('arguments: no fn', t => {
        t.throws(mapa, /fn should be function!/, 'should throw when no fn');
        t.end();
    });

    test('arguments: no lists', t => {
        let fn  = () => mapa(inc);

        t.throws(fn, /list should be an array!/, 'should throw when no list');
        t.end();
    });
})();
<|endoftext|>


<commit_before>var fs = require('fs');
var PlistParser = require('plist-parser');

var xml = fs.readFileSync('playlist.xml').toString();

// Create a new instance of the parser with your input
var plist = new PlistParser.PlistParser(xml);

// Validate the input
if(plist.validate()){
	// Parse the input, returning a JS object
	var result = plist.parse();
}

console.log(result['Playlists'][0]['Playlist Items']);<commit_msg>Removed console.log from Node.js test<commit_after>var fs = require('fs');
var PlistParser = require('plist-parser');

var xml = fs.readFileSync('playlist.xml').toString();

// Create a new instance of the parser with your input
var plist = new PlistParser.PlistParser(xml);

// Validate the input
if(plist.validate()){
	// Parse the input, returning a JS object
	var result = plist.parse();
}<|endoftext|>