<commit_before>'use strict'

// Dependencies (tests)
const chai = require('chai');
chai.should();

// Dependencies (application)
const Wrapper = require('../src/wrapper');
const Linker = require('../src/linker');
const Parser = require('../src/parser');
const ReaderError = require('../src/error');
const cloneDeep = require('lodash.clonedeep');
const url = require('url');

// Dependencies (local)
let reader;
const data = require('./mocha.data');
const Mitm = require('mitm');
const mitm = Mitm();

// mock data
const mockData = require('./stubs');
const entryType = mockData.entry.sys.contentType.sys.id;
const assetType = mockData.asset.fields.file.contentType;
const entryId = mockData.entry.sys.id;
const assetId = mockData.asset.sys.id;
const entryTitle = mockData.entry.fields.title;
const rand = Date.now();

// create reader and mock server to use for tests
before(done => {

    mitm.on('request', (req, res) => {

        const $url = url.parse(req.url);
        let pathParts = $url.pathname.split('/');
        pathParts.shift();
        const part = pathParts[2];

        function end(data) {
            return res.end(JSON.stringify(data));
        }

        if (req.url.indexOf('qaEntryNOPE') > -1 || req.url.indexOf('image%2Fnope') > -1) {
            res.statusCode = 400;
            return end(mockData.error);
        } else if (req.url.indexOf('emptyArray') > -1) {
            return end(mockData.emptyArray);
        } else if (part === 'entries') {
            return end(mockData.entries);
        } else if (part === 'assets') {
            return end(mockData.assets);
        } else {
            return end(mockData.space);
        }
    });

    reader = new Wrapper(
        'spaceid',
        'prodkey');

    // Throwaway
    new Wrapper(
        'spaceid',
        'prevkey',
        true);

    done();
});

// clean up the mock server
after(() => {
    //xhr.restore();
});

describe('Wrapper', () => {

    describe('getSpace', () => {

        it('should return data about the registered space', done => {
            return reader.getSpace().then(res => {
                res.sys.id.should.equal(mockData.space.sys.id);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getEntries', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getEntries().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.getEntries({
                content_type: entryType
            }).then(res => {
                res.should.have.property('items');
                res.total.should.equal(1);
                res.items[0].sys.contentType.sys.should.have.property('id', entryType);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntries({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getAssets', () => {

        it('should return all assets when no criteria is passed', done => {
            return reader.getAssets().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return assets that match criteria specified', done => {
            return reader.getAssets({
                'fields.file.contentType': assetType
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                res.items[0].fields.file.contentType.should.equal(assetType);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getEntries({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getEntry', () => {

        it('should return first entry when no criteria is passed', done => {
            return reader.getEntry().then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first entry that matches criteria specified', done => {
            return reader.getEntry({
                content_type: entryType
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntry({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getAsset', () => {

        it('should return first asset when no criteria is passed', done => {
            return reader.getAsset().then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first asset that matches criteria specified', done => {
            const assetCriteria = assetType;
            return reader.getAsset({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getAsset({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getEntryById', () => {

        it('should return a single entry when requesting by id', done => {
            return reader.getEntryById(entryId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(entryId);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getAssetById', () => {

        it('should return a single asset when requesting by id', done => {
            return reader.getAssetById(assetId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(assetId);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('getEntriesByType', () => {
        it('should return entries by content type', done => {
            return reader.getEntriesByType(entryType).then(entries => {
                entries.should.have.property('items');
                entries.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('findEntryByType', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.findEntryByType(entryType).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.findEntryByType(entryType, {
                title: entryTitle
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                res.fields.title.should.equal(entryTitle);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntryByType(entryType, {
                title: 'emptyArray'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('findEntriesByType', () => {

        it('should return all entries that match the criteria', done => {
            return reader.findEntriesByType(entryType, {
                title: entryTitle
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntriesByType(entryType, {
                title: 'emptyArray'
            }).then(res => {
                res.total.should.equal(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

});

describe('Parser', () => {

    describe('one', () => {

        it('should parse a single object', () => {
            const parsed = Parser.one(cloneDeep(data.unparsed));
            parsed.should.deep.equal(data.parsed);
        });

        it('should reject an array', () => {
            const parsed = Parser.one(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.unparsedArr);
        });

    });

    describe('all', () => {

        it('should parse an array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.parsedArr);
        });

        it('should put a single object in the form of a parsed array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsed));
            parsed.meta.should.have.property('total').that.equals(1);
            parsed.should.have.property('items').that.is.an('array');
            parsed.items[0].should.deep.equal(data.parsed);
        });

        it('should not interfere with regular objects', () => {
            const obj = {test: {is: true}};
            const parsed = Parser.all(obj);
            parsed.should.deep.equal(obj);
        });

    });

    describe('it', () => {

        it('should parse a single object', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

        it('should parse an array', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

    });

});

describe('Linker', () => {

    describe('then', () => {

        it('should still run then functions', done => {
            return new Linker(Promise.resolve(rand)).then(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('catch', () => {

        it('should still run catch statements with then statements', done => {
            return new Linker(Promise.reject(rand)).then(res => {
                // shouldn't get here...
            }, err => {
                err.should.equal(rand);
                done();
            });
        });

        it('should still run catch statements standalone', done => {
            return new Linker(Promise.reject(rand)).catch(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('parse', () => {

        it('should parse in place of then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should parse as a chain before then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse().then(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should be able to parse a circularly referenced object', done => {
            return reader.getEntryById(entryId).parse(entry => {
                let nested = entry.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref;
                nested.id.should.equal(entryId);
                nested.should.not.have.property('sys');
                done();
            }, err => {
                done(err);
            });
        });

        it('should fail to parse a bad object as a chain', done => {
            return new Linker(Promise.resolve(data.badparse)).parse().then(data => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

        it('should fail to parse a bad object in place of then', done => {
            return new Linker(Promise.resolve(data.badparse)).parse(data => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

});

describe('Error', () => {

    describe('ReaderError', () => {

        var err = new ReaderError(rand);

        it('should be of custom type', () => {
            err.constructor.name.should.equal('ReaderError');
        });

        it('should have a message', () => {
            err.message.should.equal(rand);
        });

    });

});
<commit_msg>Adding catch<commit_after>'use strict'

// Dependencies (tests)
const chai = require('chai');
chai.should();

// Dependencies (application)
const Wrapper = require('../src/wrapper');
const Linker = require('../src/linker');
const Parser = require('../src/parser');
const ReaderError = require('../src/error');
const cloneDeep = require('lodash.clonedeep');
const url = require('url');

// Dependencies (local)
let reader;
const data = require('./mocha.data');
const Mitm = require('mitm');
const mitm = Mitm();

// mock data
const mockData = require('./stubs');
const entryType = mockData.entry.sys.contentType.sys.id;
const assetType = mockData.asset.fields.file.contentType;
const entryId = mockData.entry.sys.id;
const assetId = mockData.asset.sys.id;
const entryTitle = mockData.entry.fields.title;
const rand = Date.now();

// create reader and mock server to use for tests
before(done => {

    mitm.on('request', (req, res) => {

        const $url = url.parse(req.url);
        let pathParts = $url.pathname.split('/');
        pathParts.shift();
        const part = pathParts[2];

        function end(data) {
            return res.end(JSON.stringify(data));
        }

        if (req.url.indexOf('qaEntryNOPE') > -1 || req.url.indexOf('image%2Fnope') > -1) {
            res.statusCode = 400;
            return end(mockData.error);
        } else if (req.url.indexOf('emptyArray') > -1) {
            return end(mockData.emptyArray);
        } else if (part === 'entries') {
            return end(mockData.entries);
        } else if (part === 'assets') {
            return end(mockData.assets);
        } else {
            return end(mockData.space);
        }
    });

    reader = new Wrapper(
        'spaceid',
        'prodkey');

    // Throwaway
    new Wrapper(
        'spaceid',
        'prevkey',
        true);

    done();
});

// clean up the mock server
after(() => {
    //xhr.restore();
});

describe('Wrapper', () => {

    describe('getSpace', () => {

        it('should return data about the registered space', done => {
            return reader.getSpace().then(res => {
                res.sys.id.should.equal(mockData.space.sys.id);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('getEntries', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getEntries().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.getEntries({
                content_type: entryType
            }).then(res => {
                res.should.have.property('items');
                res.total.should.equal(1);
                res.items[0].sys.contentType.sys.should.have.property('id', entryType);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntries({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('getAssets', () => {

        it('should return all assets when no criteria is passed', done => {
            return reader.getAssets().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return assets that match criteria specified', done => {
            return reader.getAssets({
                'fields.file.contentType': assetType
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                res.items[0].fields.file.contentType.should.equal(assetType);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getEntries({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });
    });

    describe('getEntry', () => {

        it('should return first entry when no criteria is passed', done => {
            return reader.getEntry().then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return first entry that matches criteria specified', done => {
            return reader.getEntry({
                content_type: entryType
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntry({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });
    });

    describe('getAsset', () => {

        it('should return first asset when no criteria is passed', done => {
            return reader.getAsset().then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return first asset that matches criteria specified', done => {
            const assetCriteria = assetType;
            return reader.getAsset({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getAsset({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('getEntryById', () => {

        it('should return a single entry when requesting by id', done => {
            return reader.getEntryById(entryId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(entryId);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('getAssetById', () => {

        it('should return a single asset when requesting by id', done => {
            return reader.getAssetById(assetId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(assetId);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });
    });

    describe('getEntriesByType', () => {
        it('should return entries by content type', done => {
            return reader.getEntriesByType(entryType).then(entries => {
                entries.should.have.property('items');
                entries.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });
    });

    describe('findEntryByType', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.findEntryByType(entryType).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.findEntryByType(entryType, {
                title: entryTitle
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                res.fields.title.should.equal(entryTitle);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntryByType(entryType, {
                title: 'emptyArray'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });
    });

    describe('findEntriesByType', () => {

        it('should return all entries that match the criteria', done => {
            return reader.findEntriesByType(entryType, {
                title: entryTitle
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntriesByType(entryType, {
                title: 'emptyArray'
            }).then(res => {
                res.total.should.equal(0);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });
    });

});

describe('Parser', () => {

    describe('one', () => {

        it('should parse a single object', () => {
            const parsed = Parser.one(cloneDeep(data.unparsed));
            parsed.should.deep.equal(data.parsed);
        });

        it('should reject an array', () => {
            const parsed = Parser.one(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.unparsedArr);
        });

    });

    describe('all', () => {

        it('should parse an array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.parsedArr);
        });

        it('should put a single object in the form of a parsed array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsed));
            parsed.meta.should.have.property('total').that.equals(1);
            parsed.should.have.property('items').that.is.an('array');
            parsed.items[0].should.deep.equal(data.parsed);
        });

        it('should not interfere with regular objects', () => {
            const obj = {test: {is: true}};
            const parsed = Parser.all(obj);
            parsed.should.deep.equal(obj);
        });

    });

    describe('it', () => {

        it('should parse a single object', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

        it('should parse an array', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

    });

});

describe('Linker', () => {

    describe('then', () => {

        it('should still run then functions', done => {
            return new Linker(Promise.resolve(rand)).then(res => {
                res.should.equal(rand);
                done();
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('catch', () => {

        it('should still run catch statements with then statements', done => {
            return new Linker(Promise.reject(rand)).then(res => {
                // shouldn't get here...
            }, err => {
                err.should.equal(rand);
                done();
            }).catch(err => {
                done(err);
            });
        });

        it('should still run catch statements standalone', done => {
            return new Linker(Promise.reject(rand)).catch(res => {
                res.should.equal(rand);
                done();
            }).catch(err => {
                done(err);
            });
        });

    });

    describe('parse', () => {

        it('should parse in place of then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should parse as a chain before then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse().then(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should be able to parse a circularly referenced object', done => {
            return reader.getEntryById(entryId).parse(entry => {
                let nested = entry.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref;
                nested.id.should.equal(entryId);
                nested.should.not.have.property('sys');
                done();
            }, err => {
                done(err);
            }).catch(err => {
                done(err);
            });
        });

        it('should fail to parse a bad object as a chain', done => {
            return new Linker(Promise.resolve(data.badparse)).parse().then(data => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });

        it('should fail to parse a bad object in place of then', done => {
            return new Linker(Promise.resolve(data.badparse)).parse(data => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            }).catch(err => {
                done(err);
            });
        });

    });

});

describe('Error', () => {

    describe('ReaderError', () => {

        var err = new ReaderError(rand);

        it('should be of custom type', () => {
            err.constructor.name.should.equal('ReaderError');
        });

        it('should have a message', () => {
            err.message.should.equal(rand);
        });

    });

});
<|endoftext|>


<commit_before>var expect = require('chai').expect;
const polyglot = require('../lib').default;

describe('Translate Mesh which appears later in search (Pubmed -> *)', () => {
	it('translate `Language[Majr]` -> OV `exp *Language/`', ()=> {
		expect(polyglot.translate(
			'Title[ti] and Language[Majr]', 'Ovid MEDLINE'
		)).to.equal(
			'Title.ti. AND exp *Language/'
		);
	});
	it('translate `"Practice Guidelines as Topic"[Majr]` -> OV `exp *"Practice Guidelines as Topic"/`', ()=> {
		expect(polyglot.translate(
			'Title[ti] and "Practice Guidelines as Topic"[Majr]', 'Ovid MEDLINE'
		)).to.equal(
			'Title.ti. AND exp *"Practice Guidelines as Topic"/'
		);
	});
})

describe('Translate MeSH major terms (PubMed -> *)', ()=> {

	it('translate `term[Majr]` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('term[Majr]', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `term[Majr]` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `term[Majr]` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `term[Majr]` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `term[Majr]` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('term[Majr]', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `term[Majr]` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('term[Majr]', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `term[Majr]` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `term[Majr]` -> WS `term`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Web of Science')).to.equal('term');
	});

});

describe('Translate Translate MeSH major terms (PubMed (long) -> *)', ()=> {

	it('translate `term[MeSH Major Topic]` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `term[MeSH Major Topic]` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `term[MeSH Major Topic]` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `term[MeSH Major Topic]` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `term[MeSH Major Topic]` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `term[MeSH Major Topic]` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `term[MeSH Major Topic]` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `term[MeSH Major Topic]` -> WS `term`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Web of Science')).to.equal('term');
	});

});

describe('Translate Translate MeSH major terms (Ovid MEDLINE -> *)', ()=> {

	it('translate `exp *term/` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('exp *term/', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `exp *term/` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('exp *term/', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `termexp *term/` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('exp *term/', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `exp *term/` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('exp *term/', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `exp *term/` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('exp *term/', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `exp *term/` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('exp *term/', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `exp *term/` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('exp *term/', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `exp *term/` -> WS `term`', ()=> {
		expect(polyglot.translate('exp *term/', 'Web of Science')).to.equal('term');
	});

});
<commit_msg>test: Add sandwiched mesh case<commit_after>var expect = require('chai').expect;
const polyglot = require('../lib').default;

describe('Translate Mesh which appears later in search (Pubmed -> *)', () => {
	it('translate `Language[Majr]` -> OV `exp *Language/`', ()=> {
		expect(polyglot.translate(
			'Title[ti] and Language[Majr]', 'Ovid MEDLINE'
		)).to.equal(
			'Title.ti. AND exp *Language/'
		);
	});
	it('translate `"Practice Guidelines as Topic"[Majr]` -> OV `exp *"Practice Guidelines as Topic"/`', ()=> {
		expect(polyglot.translate(
			'Title[ti] and "Practice Guidelines as Topic"[Majr]', 'Ovid MEDLINE'
		)).to.equal(
			'Title.ti. AND exp *"Practice Guidelines as Topic"/'
		);
	});
	it.only('translate `Sandwiched mesh` -> OV', ()=> {
		expect(polyglot.translate(
			'"Practice Guidelines as Topic"[Majr] OR Guideline[ti] OR "Guideline Adherence"[Majr]', 'Ovid MEDLINE'
		)).to.equal(
			'exp *"Practice Guidelines as Topic"/ OR Guideline.ti. OR exp *"Guideline Adherence"/'
		);
	});
})

describe('Translate MeSH major terms (PubMed -> *)', ()=> {

	it('translate `term[Majr]` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('term[Majr]', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `term[Majr]` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `term[Majr]` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `term[Majr]` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `term[Majr]` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('term[Majr]', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `term[Majr]` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('term[Majr]', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `term[Majr]` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `term[Majr]` -> WS `term`', ()=> {
		expect(polyglot.translate('term[Majr]', 'Web of Science')).to.equal('term');
	});

});

describe('Translate Translate MeSH major terms (PubMed (long) -> *)', ()=> {

	it('translate `term[MeSH Major Topic]` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `term[MeSH Major Topic]` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `term[MeSH Major Topic]` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `term[MeSH Major Topic]` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `term[MeSH Major Topic]` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `term[MeSH Major Topic]` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `term[MeSH Major Topic]` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `term[MeSH Major Topic]` -> WS `term`', ()=> {
		expect(polyglot.translate('term[MeSH Major Topic]', 'Web of Science')).to.equal('term');
	});

});

describe('Translate Translate MeSH major terms (Ovid MEDLINE -> *)', ()=> {

	it('translate `exp *term/` -> PM `term[Majr]`', ()=> {
		expect(polyglot.translate('exp *term/', 'PubMed abbreviation')).to.equal('term[Majr]');
	});

	it('translate `exp *term/` -> OV `exp *term/`', ()=> {
		expect(polyglot.translate('exp *term/', 'Ovid MEDLINE')).to.equal('exp *term/');
	});

	it('translate `termexp *term/` -> CO `[mh term]`', ()=> {
		expect(polyglot.translate('exp *term/', 'Cochrane Library')).to.equal('[mh term]');
	});

	it('translate `exp *term/` -> EM `term/exp/mj`', ()=> {
		expect(polyglot.translate('exp *term/', 'Embase (Elsevier)')).to.equal("term/exp/mj");
	});

	it('translate `exp *term/` -> CI `(MM term+)`', ()=> {
		expect(polyglot.translate('exp *term/', 'CINAHL (Ebsco)')).to.equal('(MM term+)');
	});

	it('translate `exp *term/` -> PY `exp *term/`', ()=> {
		expect(polyglot.translate('exp *term/', 'PsycInfo (Ovid)')).to.equal('exp *term/');
	});

	it('translate `exp *term/` -> SC `((INDEXTERMS(term))`', ()=> {
		expect(polyglot.translate('exp *term/', 'Scopus (advanced search)')).to.equal('INDEXTERMS(term)');
	});

	it('translate `exp *term/` -> WS `term`', ()=> {
		expect(polyglot.translate('exp *term/', 'Web of Science')).to.equal('term');
	});

});
<|endoftext|>


<commit_before>var libxml = require('../index');

module.exports.create = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(null, elem.namespace());
    assert.equal(null, ns.prefix());
    assert.equal('http://my-namespace.com', ns.href());
    assert.done();
};

// assign namespace to a node
module.exports.set = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');

    // this will set a namespace on the node
    var ns = elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());
    assert.equal(null, elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());
    assert.done();
};

module.exports.with_prefix = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('pref', 'http://my-namespace.com');
    assert.equal(null, elem.namespace());
    assert.equal('pref', ns.prefix());
    assert.equal('http://my-namespace.com', ns.href());

    // this should detect existing namespace object
    var ns2 = elem.namespace('pref', 'http://my-namespace.com');
    assert.ok(ns2);
    assert.equal(ns, ns2);
    assert.equal(ns, elem.namespace());
    assert.equal('pref', elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());
    assert.done();
};

module.exports.from_parsing = function(assert) {
    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<name1 xmlns="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(elem.namespace());
    assert.equal(null, elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());

    // no prefix from parsing
    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<name1 xmlns:pref="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(!elem.namespace());

    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<pref:name1 xmlns:pref="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(elem.namespace());
    assert.equal('pref', elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());

    assert.done();
};

module.exports.existing = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('http://my-namespace.com');
    elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());

    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('pref', 'http://my-namespace.com');
    elem.namespace('pref', 'http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());
    assert.done();
};

module.exports.remove = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.ok(ns == elem.namespace());
    elem.namespace(null);
    assert.ok(!elem.namespace());
    assert.done();
};

module.exports.all = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');
    var list = [];

    list.push(root.namespace('com', 'http://example.com'));
    list.push(root.namespace('net', 'http://example.net'));
    list.push(root.namespace('http://example.org'));

    assert.ok(root.namespaces().every(function(ns, index) {
        return ns.href() === list[index].href() && ns.prefix() === list[index].prefix();
    }));
    assert.equal(root.namespaces().length, list.length);

    assert.done();
};

module.exports.empty = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');

    assert.equal(root.namespaces().length, 0);

    assert.done();
};

module.exports.nested = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');

    root.namespace('com', 'http://example.com');
    assert.equal(root.namespaces().length, 1);

    var child = root.node('child');
    child.namespace('net', 'http://example.net');
    assert.equal(child.namespaces().length, 2); // <child xmlns:net="http://example.net"/> + root

    root.namespace('http://example.org');
    assert.equal(child.namespaces().length, 3); // child's namespace + root's two namespaces

    assert.done();
};

module.exports.xmlns = function(assert) {
  var str = '
BACON

ROCKS

WUT?
';
  var doc = libxml.parseXmlString(str);
  //throw because we don't specify the url
  //assert.throws(function() {
    //doc.find('//xmlns:div');
  //});
  var divs = doc.find('//xmlns:div', 'http://www.w3.org/1999/xhtml');
  assert.equal(divs.length, 2);

  var div = doc.get('//xmlns:div', 'http://www.w3.org/1999/xhtml');
  var exp = doc.root().child(2).child(0);
  assert.ok(div != null);
  assert.ok(exp != null);
  assert.equal(div.toString(), exp.toString());
  assert.done();
}

module.exports.custom_ns = function(assert) {
  var str = '
BACON

ROCKS

WUT?
';
  var doc = libxml.parseXmlString(str);
  //throw because we don't specify the url
  //assert.throws(function() {
    //doc.find('//xmlns:div');
  //});
  var divs = doc.find('//bacon:div', 'http://www.example.com/fake/uri');
  assert.equal(divs.length, 2);

  var div = doc.get('//bacon:div', 'http://www.example.com/fake/uri');
  var exp = doc.root().child(2).child(0);
  assert.ok(div != null);
  assert.ok(exp != null);
  assert.equal(div.toString(), exp.toString());
  assert.done();
}
<commit_msg>Fixed up namespace tests to exemplify custom ns usage with find and get.<commit_after>var libxml = require('../index');

module.exports.create = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(null, elem.namespace());
    assert.equal(null, ns.prefix());
    assert.equal('http://my-namespace.com', ns.href());
    assert.done();
};

// assign namespace to a node
module.exports.set = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');

    // this will set a namespace on the node
    var ns = elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());
    assert.equal(null, elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());
    assert.done();
};

module.exports.with_prefix = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('pref', 'http://my-namespace.com');
    assert.equal(null, elem.namespace());
    assert.equal('pref', ns.prefix());
    assert.equal('http://my-namespace.com', ns.href());

    // this should detect existing namespace object
    var ns2 = elem.namespace('pref', 'http://my-namespace.com');
    assert.ok(ns2);
    assert.equal(ns, ns2);
    assert.equal(ns, elem.namespace());
    assert.equal('pref', elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());
    assert.done();
};

module.exports.from_parsing = function(assert) {
    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<name1 xmlns="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(elem.namespace());
    assert.equal(null, elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());

    // no prefix from parsing
    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<name1 xmlns:pref="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(!elem.namespace());

    var doc = libxml.parseXml('<?xml version="1.0" encoding="UTF-8"?>' +
        '<pref:name1 xmlns:pref="http://my-namespace.com"/>');
    var elem = doc.root();
    assert.ok(elem.namespace());
    assert.equal('pref', elem.namespace().prefix());
    assert.equal('http://my-namespace.com', elem.namespace().href());

    assert.done();
};

module.exports.existing = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('http://my-namespace.com');
    elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());

    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.defineNamespace('pref', 'http://my-namespace.com');
    elem.namespace('pref', 'http://my-namespace.com');
    assert.ok(ns);
    assert.equal(ns, elem.namespace());
    assert.done();
};

module.exports.remove = function(assert) {
    var doc = libxml.Document();
    var elem = doc.node('name1');
    var ns = elem.namespace('http://my-namespace.com');
    assert.ok(ns);
    assert.ok(ns == elem.namespace());
    elem.namespace(null);
    assert.ok(!elem.namespace());
    assert.done();
};

module.exports.all = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');
    var list = [];

    list.push(root.namespace('com', 'http://example.com'));
    list.push(root.namespace('net', 'http://example.net'));
    list.push(root.namespace('http://example.org'));

    assert.ok(root.namespaces().every(function(ns, index) {
        return ns.href() === list[index].href() && ns.prefix() === list[index].prefix();
    }));
    assert.equal(root.namespaces().length, list.length);

    assert.done();
};

module.exports.empty = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');

    assert.equal(root.namespaces().length, 0);

    assert.done();
};

module.exports.nested = function(assert) {
    var document = libxml.Document();
    var root = document.node('root');

    root.namespace('com', 'http://example.com');
    assert.equal(root.namespaces().length, 1);

    var child = root.node('child');
    child.namespace('net', 'http://example.net');
    assert.equal(child.namespaces().length, 2); // <child xmlns:net="http://example.net"/> + root

    root.namespace('http://example.org');
    assert.equal(child.namespaces().length, 3); // child's namespace + root's two namespaces

    assert.done();
};

module.exports.xmlns = function(assert) {
  var str = '
BACON

ROCKS

WUT?
';
  var doc = libxml.parseXmlString(str);

  var divs = doc.find('//xmlns:div', 'http://www.w3.org/1999/xhtml');
  assert.equal(divs.length, 2);

  var div = doc.get('//xmlns:div', 'http://www.w3.org/1999/xhtml');
  assert.ok(div != null);
  var exp = doc.root().child(1).child(0);
  assert.ok(exp != null);
  assert.equal(div.toString(), exp.toString());
  assert.done();
}

module.exports.custom_ns = function(assert) {
  var str = '<bacon:div>BACON</bacon:div><bacon:div>ROCKS</bacon:div>
WUT?
';
  var doc = libxml.parseXmlString(str);

  var divs = doc.find('//bacon:div', {'bacon': 'http://www.example.com/fake/uri'});
  assert.equal(divs.length, 2);

  var div = doc.get('//bacon:div', {'bacon': 'http://www.example.com/fake/uri'});
  assert.ok(div != null);
  var exp = doc.root().child(1).child(0);
  assert.ok(exp != null);
  assert.equal(div.toString(), exp.toString());
  assert.done();
}
<|endoftext|>


<commit_before>
var EventEmitter = require('events').EventEmitter
  , request = require('../../')
  , express = require('express')
  , assert = require('assert')
  , app = express();

app.all('/echo', function(req, res){
  res.writeHead(200, req.headers);
  req.pipe(res);
});

app.get('/json', function(req, res){
  res.send({ name: 'manny' });
});

app.get('/no-content', function(req, res){
  res.status(204);
  res.end();
});

app.get('/json-hal', function(req, res){
  res.set('content-type', 'application/hal+json');
  res.send({ name: 'hal 5000' });
});

app.get('/collection-json', function(req, res){
  res.set('content-type', 'application/vnd.collection+json');
  res.send({ name: 'chewbacca' });
});

app.listen(3005);

describe('req.send(Object) as "json"', function(){
  it('should default to json', function(done){
    request
    .post('http://localhost:3005/echo')
    .send({ name: 'tobi' })
    .end(function(res){
      res.should.be.json
      res.text.should.equal('{"name":"tobi"}');
      done();
    });
  })

  it('should work with arrays', function(done){
    request
    .post('http://localhost:3005/echo')
    .send([1,2,3])
    .end(function(res){
      res.should.be.json
      res.text.should.equal('[1,2,3]');
      done();
    });
  })

  it('should work with GET', function(done){
    request
    .get('http://localhost:3005/echo')
    .send({ tobi: 'ferret' })
    .end(function(res){
      res.should.be.json
      res.text.should.equal('{"tobi":"ferret"}');
      done();
    });
  });

  describe('when called several times', function(){
    it('should merge the objects', function(done){
      request
      .post('http://localhost:3005/echo')
      .send({ name: 'tobi' })
      .send({ age: 1 })
      .end(function(res){
        res.should.be.json
        res.text.should.equal('{"name":"tobi","age":1}');
        done();
      });
    })
  })
})

describe('res.body', function(){
  describe('application/json', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/json')
      .end(function(res){
        res.text.should.equal('{"name":"manny"}');
        res.body.should.eql({ name: 'manny' });
        done();
      });
    })
  })

  describe('HEAD requests', function(){
    it('should not throw a parse error', function(done){
      request
      .head('http://localhost:3005/json')
      .end(function(err, res){
        assert(err === null);
        assert(res.text === undefined)
        assert(Object.keys(res.body).length === 0)
        done();
      });
    });
  });

  describe('No content', function(){
    it('should not throw a parse error', function(done){
      request
      .get('http://localhost:3005/no-content')
      .end(function(err, res){
        assert(err === null);
        assert(res.text === undefined);
        assert(Object.keys(res.body).length === 0);
        done();
      });
    });
  });

  describe('application/json+hal', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/json-hal')
      .end(function(err, res){
        if (err) return done(err);
        res.text.should.equal('{"name":"hal 5000"}');
        res.body.should.eql({ name: 'hal 5000' });
        done();
      });
    })
  })

  describe('vnd.collection+json', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/collection-json')
      .end(function(err, res){
        res.text.should.equal('{"name":"chewbacca"}');
        res.body.should.eql({ name: 'chewbacca' });
        done();
      });
    })
  })
})
<commit_msg>Add tests for falsy json values<commit_after>
var EventEmitter = require('events').EventEmitter
  , request = require('../../')
  , express = require('express')
  , assert = require('assert')
  , app = express();

app.all('/echo', function(req, res){
  res.writeHead(200, req.headers);
  req.pipe(res);
});

app.get('/json', function(req, res){
  res.send({ name: 'manny' });
});

app.get('/no-content', function(req, res){
  res.status(204);
  res.end();
});

app.get('/json-hal', function(req, res){
  res.set('content-type', 'application/hal+json');
  res.send({ name: 'hal 5000' });
});

app.get('/collection-json', function(req, res){
  res.set('content-type', 'application/vnd.collection+json');
  res.send({ name: 'chewbacca' });
});

app.listen(3005);

describe('req.send(Object) as "json"', function(){
  it('should default to json', function(done){
    request
    .post('http://localhost:3005/echo')
    .send({ name: 'tobi' })
    .end(function(res){
      res.should.be.json
      res.text.should.equal('{"name":"tobi"}');
      done();
    });
  })

  it('should work with arrays', function(done){
    request
    .post('http://localhost:3005/echo')
    .send([1,2,3])
    .end(function(res){
      res.should.be.json
      res.text.should.equal('[1,2,3]');
      done();
    });
  });

  it('should work with value null', function(done){
    request
    .post('http://localhost:3005/echo')
    .type('json')
    .send('null')
    .end(function(res){
      res.should.be.json
      assert(res.body === null);
      done();
    });
  });

  it('should work with value false', function(done){
    request
    .post('http://localhost:3005/echo')
    .type('json')
    .send('false')
    .end(function(res){
      res.should.be.json
      res.body.should.equal(false);
      done();
    });
  });

  it('should work with value 0', function(done){
    request
    .post('http://localhost:3005/echo')
    .type('json')
    .send('0')
    .end(function(res){
      res.should.be.json
      res.body.should.equal(0);
      done();
    });
  });

  it('should work with empty string value', function(done){
    request
    .post('http://localhost:3005/echo')
    .type('json')
    .send('""')
    .end(function(res){
      res.should.be.json
      res.body.should.equal("");
      done();
    });
  });

  it('should work with GET', function(done){
    request
    .get('http://localhost:3005/echo')
    .send({ tobi: 'ferret' })
    .end(function(res){
      res.should.be.json
      res.text.should.equal('{"tobi":"ferret"}');
      done();
    });
  });

  describe('when called several times', function(){
    it('should merge the objects', function(done){
      request
      .post('http://localhost:3005/echo')
      .send({ name: 'tobi' })
      .send({ age: 1 })
      .end(function(res){
        res.should.be.json
        res.text.should.equal('{"name":"tobi","age":1}');
        done();
      });
    })
  })
})

describe('res.body', function(){
  describe('application/json', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/json')
      .end(function(res){
        res.text.should.equal('{"name":"manny"}');
        res.body.should.eql({ name: 'manny' });
        done();
      });
    })
  })

  describe('HEAD requests', function(){
    it('should not throw a parse error', function(done){
      request
      .head('http://localhost:3005/json')
      .end(function(err, res){
        assert(err === null);
        assert(res.text === undefined)
        assert(Object.keys(res.body).length === 0)
        done();
      });
    });
  });

  describe('No content', function(){
    it('should not throw a parse error', function(done){
      request
      .get('http://localhost:3005/no-content')
      .end(function(err, res){
        assert(err === null);
        assert(res.text === undefined);
        assert(Object.keys(res.body).length === 0);
        done();
      });
    });
  });

  describe('application/json+hal', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/json-hal')
      .end(function(err, res){
        if (err) return done(err);
        res.text.should.equal('{"name":"hal 5000"}');
        res.body.should.eql({ name: 'hal 5000' });
        done();
      });
    })
  })

  describe('vnd.collection+json', function(){
    it('should parse the body', function(done){
      request
      .get('http://localhost:3005/collection-json')
      .end(function(err, res){
        res.text.should.equal('{"name":"chewbacca"}');
        res.body.should.eql({ name: 'chewbacca' });
        done();
      });
    })
  })
})
<|endoftext|>


<commit_before>var test = require("tap").test;
var rps = require("../index.js")
var path = require("path")

test("npa-basic", function (t) {
  t.setMaxListeners(999)

  var tests = {
    "foo@1.2": {
      name: "foo",
      type: "range",
      spec: ">=1.2.0 <1.3.0",
      raw: "foo@1.2",
      rawSpec: "1.2"
    },

    "@foo/bar": {
      raw: "@foo/bar",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "",
      spec: "*",
      type: "range"
    },

    "@foo/bar@": {
      raw: "@foo/bar@",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "",
      spec: "*",
      type: "range"
    },

    "@foo/bar@baz": {
      raw: "@foo/bar@baz",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "baz",
      spec: "baz",
      type: "tag"
    },

    "@f fo o al/ a d s ;f ": {
      raw: "@f fo o al/ a d s ;f",
      name: null,
      rawSpec: "@f fo o al/ a d s ;f",
      spec: path.resolve("@f fo o al/ a d s ;f"),
      type: "local"
    },

    "foo@1.2.3": {
      name: "foo",
      type: "version",
      spec: "1.2.3",
      raw: "foo@1.2.3"
    },

    "foo@=v1.2.3": {
      name: "foo",
      type: "version",
      spec: "1.2.3",
      raw: "foo@=v1.2.3",
      rawSpec: "=v1.2.3"
    },

    "git+ssh://git@notgithub.com/user/foo#1.2.3": {
      name: null,
      type: "git",
      spec: "ssh://git@notgithub.com/user/foo#1.2.3",
      raw: "git+ssh://git@notgithub.com/user/foo#1.2.3"
    },

    "git+file://path/to/repo#1.2.3": {
      name: null,
      type: "git",
      spec: "file://path/to/repo#1.2.3",
      raw: "git+file://path/to/repo#1.2.3"
    },

    "git://notgithub.com/user/foo": {
      name: null,
      type: "git",
      spec: "git://notgithub.com/user/foo",
      raw: "git://notgithub.com/user/foo"
    },

    "@foo/bar@git+ssh://notgithub.com/user/foo": {
      name: "@foo/bar",
      scope: "@foo",
      spec: "ssh://notgithub.com/user/foo",
      rawSpec: "git+ssh://notgithub.com/user/foo",
      raw: "@foo/bar@git+ssh://notgithub.com/user/foo"
    },

    "/path/to/foo": {
      name: null,
      type: "local",
      spec: "/path/to/foo",
      raw: "/path/to/foo"
    },

    "file:path/to/foo": {
      name: null,
      type: "local",
      spec: path.resolve("path/to/foo"),
      raw: "file:path/to/foo"
    },

    "file:~/path/to/foo": {
      name: null,
      type: "local",
      spec: path.resolve("~/path/to/foo"),
      raw: "file:~/path/to/foo"
    },

    "file:../path/to/foo": {
      name: null,
      type: "local",
      spec: path.resolve("../path/to/foo"),
      raw: "file:../path/to/foo"
    },

    "file:///path/to/foo": {
      name: null,
      type: "local",
      spec: "/path/to/foo",
      raw: "file:///path/to/foo"
    },

    "https://server.com/foo.tgz": {
      name: null,
      type: "remote",
      spec: "https://server.com/foo.tgz",
      raw: "https://server.com/foo.tgz"
    },

    "foo@latest": {
      name: "foo",
      type: "tag",
      spec: "latest",
      raw: "foo@latest"
    },

    "foo": {
      name: "foo",
      type: "range",
      spec: "*",
      raw: "foo"
    }
  }

  t.plan( 2 + Object.keys(tests).length * 3 )

  Object.keys(tests).forEach(function (arg) {
    rps(arg, path.resolve(__dirname,'..'), function(err, res) {
      t.notOk(err, arg + " no error")
      t.type(res, "Result", arg + " got right result time")
      t.has(res, tests[arg], arg + " result has correct values")
    })
  })

  // Completely unreasonable invalid garbage throws an error
  rps("this is not a \0 valid package name or url", path.resolve(__dirname,'..'), function (err) {
    t.ok(err, "error")
  })

  rps("gopher://yea right", path.resolve(__dirname,'..'), function (err) {
    t.ok(err, "Unsupported URL Type: gopher://yea right")
  })

})
<commit_msg>Fix path checks to work regardless of where the test is run from<commit_after>var test = require("tap").test;
var rps = require("../index.js")
var path = require("path")

test("npa-basic", function (t) {
  t.setMaxListeners(999)

  var tests = {
    "foo@1.2": {
      name: "foo",
      type: "range",
      spec: ">=1.2.0 <1.3.0",
      raw: "foo@1.2",
      rawSpec: "1.2"
    },

    "@foo/bar": {
      raw: "@foo/bar",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "",
      spec: "*",
      type: "range"
    },

    "@foo/bar@": {
      raw: "@foo/bar@",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "",
      spec: "*",
      type: "range"
    },

    "@foo/bar@baz": {
      raw: "@foo/bar@baz",
      name: "@foo/bar",
      scope: "@foo",
      rawSpec: "baz",
      spec: "baz",
      type: "tag"
    },

    "@f fo o al/ a d s ;f ": {
      raw: "@f fo o al/ a d s ;f",
      name: null,
      rawSpec: "@f fo o al/ a d s ;f",
      spec: path.resolve("@f fo o al/ a d s ;f"),
      type: "local"
    },

    "foo@1.2.3": {
      name: "foo",
      type: "version",
      spec: "1.2.3",
      raw: "foo@1.2.3"
    },

    "foo@=v1.2.3": {
      name: "foo",
      type: "version",
      spec: "1.2.3",
      raw: "foo@=v1.2.3",
      rawSpec: "=v1.2.3"
    },

    "git+ssh://git@notgithub.com/user/foo#1.2.3": {
      name: null,
      type: "git",
      spec: "ssh://git@notgithub.com/user/foo#1.2.3",
      raw: "git+ssh://git@notgithub.com/user/foo#1.2.3"
    },

    "git+file://path/to/repo#1.2.3": {
      name: null,
      type: "git",
      spec: "file://path/to/repo#1.2.3",
      raw: "git+file://path/to/repo#1.2.3"
    },

    "git://notgithub.com/user/foo": {
      name: null,
      type: "git",
      spec: "git://notgithub.com/user/foo",
      raw: "git://notgithub.com/user/foo"
    },

    "@foo/bar@git+ssh://notgithub.com/user/foo": {
      name: "@foo/bar",
      scope: "@foo",
      spec: "ssh://notgithub.com/user/foo",
      rawSpec: "git+ssh://notgithub.com/user/foo",
      raw: "@foo/bar@git+ssh://notgithub.com/user/foo"
    },

    "/path/to/foo": {
      name: null,
      type: "local",
      spec: "/path/to/foo",
      raw: "/path/to/foo"
    },
    "file:path/to/foo": {
      name: null,
      type: "local",
      spec: path.resolve(__dirname,"..","path/to/foo"),
      raw: "file:path/to/foo"
    },
    "file:../path/to/foo": {
      name: null,
      type: "local",
      spec: path.resolve(__dirname,"..","../path/to/foo"),
      raw: "file:../path/to/foo"
    },
    "file:///path/to/foo": {
      name: null,
      type: "local",
      spec: "/path/to/foo",
      raw: "file:///path/to/foo"
    },

    "https://server.com/foo.tgz": {
      name: null,
      type: "remote",
      spec: "https://server.com/foo.tgz",
      raw: "https://server.com/foo.tgz"
    },

    "foo@latest": {
      name: "foo",
      type: "tag",
      spec: "latest",
      raw: "foo@latest"
    },

    "foo": {
      name: "foo",
      type: "range",
      spec: "*",
      raw: "foo"
    }
  }

  t.plan( 2 + Object.keys(tests).length * 3 )

  Object.keys(tests).forEach(function (arg) {
    rps(arg, path.resolve(__dirname,'..'), function(err, res) {
      t.notOk(err, arg + " no error")
      t.type(res, "Result", arg + " got right result time")
      t.has(res, tests[arg], arg + " result has correct values")
    })
  })

  // Completely unreasonable invalid garbage throws an error
  rps("this is not a \0 valid package name or url", path.resolve(__dirname,'..'), function (err) {
    t.ok(err, "error")
  })

  rps("gopher://yea right", path.resolve(__dirname,'..'), function (err) {
    t.ok(err, "Unsupported URL Type: gopher://yea right")
  })

})
<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const Wait = require('./../index').Wait
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

describe('page load', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  beforeEach(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  afterEach(function (done) {
    service.stop().then(() => {
        done()
    })
  })

  it('undefined strategy should not wait for page load', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=5', pageLoadStrategy: 'none'}).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(1000)

  it('undefined strategy should not wait for page refresh', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=5', pageLoadStrategy: 'none'}).then(() => {
        return new Wait({parent: driver, timeout: 10000}).until(ExpectedConditions.isNodePresent('#greeting'))
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'none'})
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('loading strategy should not wait for resources', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'loading'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('interactive strategy should not wait for resources', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('loading strategy should not wait for resources on refresh', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'loading'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'loading'})
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('interactive strategy should not wait for resources on refresh', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'interactive'})
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(5000)

  it('interactive strategy should wait for document to be loaded', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=3', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('body')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(4000)

  it('default strategy should wait for the document to be loaded', function(done) {
      driver.navigate(baseUrl + '/base.html').then(() => {
      }).then(() => {
        return driver.title()
      }).then((title) => {
        expect(title).to.equal('base page')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  it('refresh a basic page', function(done) {
      driver.navigate(baseUrl + '/base.html').then(() => {
      }).then(() => {
        return driver.reload()
      }).then(() => {
        return driver.title()
      }).then((title) => {
        expect(title).to.equal('base page')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  xit('return error if the url does not resolve', function(done) {
      driver.navigate('http://www.thisurldoesnotexist.comx/').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('return error if the url is malformed', function(done) {
      driver.navigate('www.test.com').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('return error if the url is malformed in port part', function(done) {
      driver.navigate('http://localhost:3001bla').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('should return when url does not connect', function(done) {
      driver.navigate('http://localhost:3001').then(() => {
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  xit('wait for all frames to load', function(done) {
    // need to implement frame support
    //
    // the 'complete' strategy should wait for all the frames to load
  })

  xit('handle browser history', function(done) {
    // i don't see this used much in browser automation so i'm going to procrastinate on it a bit
  })
})
<commit_msg>test page with document write and no document close<commit_after>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const Wait = require('./../index').Wait
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

describe('page load', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  beforeEach(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  afterEach(function (done) {
    service.stop().then(() => {
        done()
    })
  })

  it('undefined strategy should not wait for page load', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=5', pageLoadStrategy: 'none'}).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(1000)

  it('undefined strategy should not wait for page refresh', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=5', pageLoadStrategy: 'none'}).then(() => {
        return new Wait({parent: driver, timeout: 10000}).until(ExpectedConditions.isNodePresent('#greeting'))
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'none'})
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('loading strategy should not wait for resources', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'loading'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('interactive strategy should not wait for resources', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('loading strategy should not wait for resources on refresh', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'loading'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'loading'})
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(6000)

  it('interactive strategy should not wait for resources on refresh', function(done) {
      driver.navigate({url: baseUrl + '/slowLoadingResourcePage.html', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        return driver.reload({pageLoadStrategy: 'interactive'})
      }).then(() => {
        return driver.waitForNodePresent('#peas')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(5000)

  it('interactive strategy should wait for document to be loaded', function(done) {
      driver.navigate({url: baseUrl + '/sleep?time=3', pageLoadStrategy: 'interactive'}).then(() => {
      }).then(() => {
        return driver.waitForNodePresent('body')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  }).timeout(4000)

  it('default strategy should wait for the document to be loaded', function(done) {
      driver.navigate(baseUrl + '/base.html').then(() => {
      }).then(() => {
        return driver.title()
      }).then((title) => {
        expect(title).to.equal('base page')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  it('refresh a basic page', function(done) {
      driver.navigate(baseUrl + '/base.html').then(() => {
      }).then(() => {
        return driver.reload()
      }).then(() => {
        return driver.title()
      }).then((title) => {
        expect(title).to.equal('base page')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  xit('return error if the url does not resolve', function(done) {
      driver.navigate('http://www.thisurldoesnotexist.comx/').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('return error if the url is malformed', function(done) {
      driver.navigate('www.test.com').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('return error if the url is malformed in port part', function(done) {
      driver.navigate('http://localhost:3001bla').then(() => {
      }).then(() => {
        done(new Error('this url should not resolve'))
      }).catch((err) => {
        done()
      })
  })

  it('should return when url does not connect', function(done) {
      driver.navigate('http://localhost:3001').then(() => {
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

  xit('wait for all frames to load', function(done) {
    // need to implement frame support
    //
    // the 'complete' strategy should wait for all the frames to load
  })

  xit('handle browser history', function(done) {
    // i don't see this used much in browser automation so i'm going to procrastinate on it a bit
  })

  it('should load page with document write and no document close', function(done) {
      driver.navigate({url: baseUrl + '/document_write.html', pageLoadStrategy: 'loading'}).then(() => {
        return driver.waitForNodePresent('body')
      }).then((node) => {
        return node.text()
      }).then((text) => {
        expect(text).to.contain('world')
      }).then(() => {
        done()
      }).catch((err) => {
        done(err)
      })
  })

})
<|endoftext|>


<commit_before>if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5
            // internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () {},
            fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}
<commit_msg>Fix jshint errors<commit_after>(function () {
    "use strict";

    if (!Function.prototype.bind) {
        Function.prototype.bind = function (oThis) {
            if (typeof this !== "function") {
                // closest thing possible to the ECMAScript 5
                // internal IsCallable function
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }

            var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                FNOP = function () {},
                fBound = function () {
                    return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
                };

            FNOP.prototype = this.prototype;
            fBound.prototype = new FNOP();

            return fBound;
        };
    }
}());
<|endoftext|>


<commit_before>var sinon = require('sinon'),
    assert = require('assert'),
    request = require('request-promise'),
    OpenAMClient = require('../lib/openam').OpenAMClient;

describe('Test with private IP', function () {
    var hostname, serverUrl, privateIP;

    beforeEach(function () {

        serverUrl = 'http://openam.example.com:8080/openam';
        hostname = 'openam.example.com';
        privateIP = '127.0.0.1';

        // client instance
        client = new OpenAMClient(serverUrl, privateIP);

        // spies
        getRequests = sinon.spy(request, 'get');
        postRequests = sinon.spy(request, 'post');

    });

    afterEach(function () {
        // restore stubs
        getRequests.restore();
        postRequests.restore();
    });

    describe('getServerInfo', function () {
        it('request should have private ip in url', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('authenticate', function () {
        it('request should have private ip in url', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('logout', function () {
        it('request should have private ip in url', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateSession', function () {
        it('request should have private ip in url', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getPolicyDecision', function () {
        it('request should have private ip in url', function () {
            client.getPolicyDecision(null, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getPolicyDecision(null, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('sessionServiceRequest', function () {
        it('request should have private ip in url', function () {
            client.sessionServiceRequest('requestSet');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.sessionServiceRequest('requestSet');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateAccessToken', function () {
        it('request should have private ip in url', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getProfile', function () {
        it('request should have private ip in url', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
});
describe('Test without private IP', function () {
    var hostname, serverUrl;

    beforeEach(function () {

        serverUrl = 'http://openam.example.com:8080/openam';
        hostname = 'openam.example.com';

        // client instance
        client = new OpenAMClient(serverUrl);

        // spies
        getRequests = sinon.spy(request, 'get');
        postRequests = sinon.spy(request, 'post');

    });

    afterEach(function () {
        // restore stubs
        getRequests.restore();
        postRequests.restore();
    });

    describe('getServerInfo', function () {
        it('request should have serverUrl in url', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('authenticate', function () {
        it('request should have serverUrl in url', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('logout', function () {
        it('request should have serverUrl in url', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateSession', function () {
        it('request should have serverUrl in url', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getPolicyDecision', function () {
        it('request should have serverUrl in url', function () {
            client.getPolicyDecision(null, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getPolicyDecision(null, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('sessionServiceRequest', function () {
        it('request should have serverUrl in url', function () {
            client.sessionServiceRequest('requestSet');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.sessionServiceRequest('requestSet');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateAccessToken', function () {
        it('request should have serverUrl in url', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getProfile', function () {
        it('request should have serverUrl in url', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
});<commit_msg>fixed parameters in testcase for earlier versions of node<commit_after>var sinon = require('sinon'),
    assert = require('assert'),
    request = require('request-promise'),
    OpenAMClient = require('../lib/openam').OpenAMClient;

describe('Test with private IP', function () {
    var hostname, serverUrl, privateIP;

    beforeEach(function () {

        serverUrl = 'http://openam.example.com:8080/openam';
        hostname = 'openam.example.com';
        privateIP = '127.0.0.1';

        // client instance
        client = new OpenAMClient(serverUrl, privateIP);

        // spies
        getRequests = sinon.spy(request, 'get');
        postRequests = sinon.spy(request, 'post');

    });

    afterEach(function () {
        // restore stubs
        getRequests.restore();
        postRequests.restore();
    });

    describe('getServerInfo', function () {
        it('request should have private ip in url', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('authenticate', function () {
        it('request should have private ip in url', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('logout', function () {
        it('request should have private ip in url', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateSession', function () {
        it('request should have private ip in url', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getPolicyDecision', function () {
        it('request should have private ip in url', function () {
            client.getPolicyDecision({}, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getPolicyDecision({}, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('sessionServiceRequest', function () {
        it('request should have private ip in url', function () {
            client.sessionServiceRequest();
            assert.equal(request.post.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.sessionServiceRequest();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateAccessToken', function () {
        it('request should have private ip in url', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getProfile', function () {
        it('request should have private ip in url', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[0].includes(privateIP), true);
        });
        it('request should have header host value', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
});
describe('Test without private IP', function () {
    var hostname, serverUrl;

    beforeEach(function () {

        serverUrl = 'http://openam.example.com:8080/openam';
        hostname = 'openam.example.com';

        // client instance
        client = new OpenAMClient(serverUrl);

        // spies
        getRequests = sinon.spy(request, 'get');
        postRequests = sinon.spy(request, 'post');

    });

    afterEach(function () {
        // restore stubs
        getRequests.restore();
        postRequests.restore();
    });

    describe('getServerInfo', function () {
        it('request should have serverUrl in url', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getServerInfo();
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('authenticate', function () {
        it('request should have serverUrl in url', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.authenticate();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('logout', function () {
        it('request should have serverUrl in url', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.logout('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateSession', function () {
        it('request should have serverUrl in url', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.validateSession('sessionid');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getPolicyDecision', function () {
        it('request should have serverUrl in url', function () {
            client.getPolicyDecision({}, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getPolicyDecision({}, 'sessionId', 'cookieName');
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('sessionServiceRequest', function () {
        it('request should have serverUrl in url', function () {
            client.sessionServiceRequest();
            assert.equal(request.post.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.sessionServiceRequest();
            assert.equal(request.post.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('validateAccessToken', function () {
        it('request should have serverUrl in url', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.validateAccessToken('accessToken');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
    describe('getProfile', function () {
        it('request should have serverUrl in url', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[0].includes(serverUrl), true);
        });
        it('request should have header host value', function () {
            client.getProfile('userId', 'realm', 'sessionId', 'cookieName');
            assert.equal(request.get.getCall(0).args[1].headers.host, hostname);
        });
    });
});<|endoftext|>