<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var Buffer = require('buffer').Buffer;
var allocCluster = require('./lib/alloc-cluster.js');
var TChannel = require('../channel.js');

allocCluster.test('request().send() to a busy server', 2, function t(cluster, assert) {
    var two = cluster.channels[1];

    var count = 0;

    function isBusy() {
        count += 1;

        if (count < 2) {
            return null;
        }

        else {
            return 'server is too busy';
        }
    }

    var one = TChannel({
        isBusy: isBusy
    });

    one.listen(0, '127.0.0.1', listening);

    var twoSubChan;

    function listening () {
        twoSubChan = two.makeSubChannel({
            serviceName: 'server',
            peers: [one.hostPort]
        });

        one.makeSubChannel({
            serviceName: 'server'
        }).register('foo', function foo(req, res, arg2, arg3) {
            assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
            assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
            res.headers.as = 'raw';
            res.sendOk(arg2, arg3);
        });

        twoSubChan.request({
            serviceName: 'server',
            hasNoParent: true,
            headers: {
                as: 'raw',
                cn: 'two'
            }
        }).send('foo', 'arg1', 'arg2', onResp);
    }

    function onResp(err, res, arg2, arg3) {
        twoSubChan.request({
            serviceName: 'server',
            hasNoParent: true,
            headers: {
                as: 'raw',
                cn: 'two'
            }
        }).send('foo', 'arg1', 'arg2', onResp2);
    }

    function onResp2(err, res, arg2, arg3) {
        assert.ok(err.isErrorFrame, 'got an error frame');
        assert.equals(err.type, 'tchannel.busy');
        assert.ok(err.isErrorFrame, 'err isErrorFrame');
        assert.equals(err.codeName, 'Busy', 'error code name busy');
        assert.equals(err.fullType, 'tchannel.busy');

        one.close();

        assert.end();
    }
});
<commit_msg>test/busy: verify handler only called once<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var Buffer = require('buffer').Buffer;
var allocCluster = require('./lib/alloc-cluster.js');
var TChannel = require('../channel.js');

allocCluster.test('request().send() to a busy server', 2, function t(cluster, assert) {
    var two = cluster.channels[1];

    var count = 0;

    function isBusy() {
        count += 1;

        if (count < 2) {
            return null;
        }

        else {
            return 'server is too busy';
        }
    }

    var one = TChannel({
        isBusy: isBusy
    });

    one.listen(0, '127.0.0.1', listening);

    var twoSubChan;
    var called = 0;

    function listening () {
        twoSubChan = two.makeSubChannel({
            serviceName: 'server',
            peers: [one.hostPort]
        });

        one.makeSubChannel({
            serviceName: 'server'
        }).register('foo', function foo(req, res, arg2, arg3) {
            called++;

            assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
            assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
            res.headers.as = 'raw';
            res.sendOk(arg2, arg3);
        });

        twoSubChan.request({
            serviceName: 'server',
            hasNoParent: true,
            headers: {
                as: 'raw',
                cn: 'two'
            }
        }).send('foo', 'arg1', 'arg2', onResp);
    }

    function onResp(err, res, arg2, arg3) {
        twoSubChan.request({
            serviceName: 'server',
            hasNoParent: true,
            headers: {
                as: 'raw',
                cn: 'two'
            }
        }).send('foo', 'arg1', 'arg2', onResp2);
    }

    function onResp2(err, res, arg2, arg3) {
        assert.ok(err.isErrorFrame, 'got an error frame');
        assert.equals(err.type, 'tchannel.busy');
        assert.ok(err.isErrorFrame, 'err isErrorFrame');
        assert.equals(err.codeName, 'Busy', 'error code name busy');
        assert.equals(err.fullType, 'tchannel.busy');

        one.close();
        assert.equal(called, 1);

        assert.end();
    }
});
<|endoftext|>


<commit_before>module.exports = {
    master: {
        product: require('./data-util/master/product-data-util'),
        uom: require('./data-util/master/uom-data-util'),
        vat: require('./data-util/master/vat-data-util'),
        currency: require('./data-util/master/currency-data-util'),
        buyer: require('./data-util/master/buyer-data-util'),
        budget: require('./data-util/master/budget-data-util'),
        supplier: require('./data-util/master/supplier-data-util'),
        unit: require('./data-util/master/unit-data-util'),
        category: require('./data-util/master/category-data-util')
    },
    transaction: {
        purchaseRequest: require('./data-util/transaction/purchase-request-data-util'),
        purchaseOrder: require('./data-util/transaction/purchase-order-data-util'),
        purchaseOrderExternal: require('./data-util/transaction/purchase-order-external-data-util')
    }
};
<commit_msg>add purchaseOrderExternal, deliveryOrder, unitReceiptNote, unitPaymentOrder, unitPaymentPriceCorrectionNote data-util<commit_after>module.exports = {
    master: {
        product: require('./data-util/master/product-data-util'),
        uom: require('./data-util/master/uom-data-util'),
        vat: require('./data-util/master/vat-data-util'),
        currency: require('./data-util/master/currency-data-util'),
        buyer: require('./data-util/master/buyer-data-util'),
        budget: require('./data-util/master/budget-data-util'),
        supplier: require('./data-util/master/supplier-data-util'),
        unit: require('./data-util/master/unit-data-util'),
        category: require('./data-util/master/category-data-util')
    },
    transaction: {
        purchaseRequest: require('./data-util/transaction/purchase-request-data-util'),
        purchaseOrder: require('./data-util/transaction/purchase-order-data-util'),
        purchaseOrderExternal: require('./data-util/transaction/purchase-order-external-data-util'),
        deliveryOrder: require('./data-util/transaction/delivery-order-data-util'),
        unitReceiptNote: require('./data-util/transaction/unit-receipt-note-data-util'),
        unitPaymentOrder: require('./data-util/transaction/unit-payment-order-data-util'),
        unitPaymentPriceCorrectionNote: require('./data-util/transaction/unit-payment-price-correction-note-data-util')
    }
};
<|endoftext|>


<commit_before>let expect = require('chai').expect

let logger = require('../lib/logger');
logger.silent = true;

let datafire = require('../index');
datafire.integrationsDirectory = __dirname + '/integrations';

describe('Flows', () => {
  let flow = integration = null;

  before(done => {
    require('./util/server').listen(3333, done);
  });

  beforeEach(() => {
    flow = new datafire.Flow('test', 'test_flow');
    integration = new datafire.Integration('test');
  })

  it('should run', (done) => {
    flow.step('succeed', integration.get('/succeed'));
    flow.step('result',
              (data) => {
                expect(data.succeed).to.not.be.null;
                expect(data.succeed).to.equal('OK');
                done();
              })
    flow.execute();
  })

  it('should not use auth by default', (done) => {
    flow.step('fail', integration.get('/secret'))
    flow.catch((err, data) => {
          expect(err.statusCode).to.equal(401);
          data.error = true;
        })
    flow.step('result',
        (data) => {
          expect(data.error).to.equal(true);
          done();
        })
    flow.execute();
  })
})

<commit_msg>add cred tests<commit_after>let expect = require('chai').expect

let logger = require('../lib/logger');
logger.silent = true;

let datafire = require('../index');
datafire.integrationsDirectory = __dirname + '/integrations';
datafire.credentialsDirectory = __dirname + '/credentials';

describe('Flows', () => {
  let flow = integration = null;

  before(done => {
    require('./util/server').listen(3333, done);
  });

  beforeEach(() => {
    flow = new datafire.Flow('test', 'test_flow');
    integration = new datafire.Integration('test');
  })

  it('should run', (done) => {
    flow.step('succeed', integration.get('/succeed'));
    flow.step('result',
              (data) => {
                expect(data.succeed).to.not.be.null;
                expect(data.succeed).to.equal('OK');
                done();
              })
    flow.execute();
  })

  it('should not use auth by default', (done) => {
    flow.step('fail', integration.get('/secret'))
    flow.catch((err, data) => {
          expect(err.statusCode).to.equal(401);
          data.error = true;
        })
    flow.step('result',
        (data) => {
          expect(data.error).to.equal(true);
          done();
        })
    flow.execute();
  })

  it('should throw error for non existant user', () => {
    expect(() => {
      integration.as('someone');
    }).to.throw();
  })

  it('should not throw error for existing user', () => {
    expect(() => {
      integration.as('user1');
    }).to.not.throw();
  })

})

<|endoftext|>


<commit_before>const assert = require("assert");
const jsdom = require("jsdom");

const { FORM_URL, FORM_FIELDS } = require("./constants.js");

describe("Browser tests with JSDOM", function() {
    describe("Check form for used inputs", function() {
        let document, inputs;
        before(function(done) {
            jsdom.env({
                url: FORM_URL,
                done: function(err, window) {
                    document = window.document;
                    inputs = document.querySelector("form.webform-client-form").querySelectorAll("[name]");
                    done();
                },
            });
        });

        for (let name in FORM_FIELDS) {
            it(FORM_FIELDS[name], function() {
                let present = false;
                for (let j = 0; j < inputs.length; j++) {
                    if (FORM_FIELDS[name] === inputs[j].name) {
                        present = true;
                        break;
                    }
                }
                assert.ok(present, FORM_FIELDS[name] + " is missing");
            });
        }

        it("button with name Join The ACLU", function() {
            const button = document.getElementById("edit-submit");
            assert.ok(button, "Submit button missing");
            assert.equal(button.value, "Join The ACLU");
        });
    });
});
<commit_msg>Fix path error.<commit_after>const assert = require("assert");
const jsdom = require("jsdom");

const { FORM_URL, FORM_FIELDS } = require("../constants.js");

describe("Browser tests with JSDOM", function() {
    describe("Check form for used inputs", function() {
        let document, inputs;
        before(function(done) {
            jsdom.env({
                url: FORM_URL,
                done: function(err, window) {
                    document = window.document;
                    inputs = document.querySelector("form.webform-client-form").querySelectorAll("[name]");
                    done();
                },
            });
        });

        for (let name in FORM_FIELDS) {
            it(FORM_FIELDS[name], function() {
                let present = false;
                for (let j = 0; j < inputs.length; j++) {
                    if (FORM_FIELDS[name] === inputs[j].name) {
                        present = true;
                        break;
                    }
                }
                assert.ok(present, FORM_FIELDS[name] + " is missing");
            });
        }

        it("button with name Join The ACLU", function() {
            const button = document.getElementById("edit-submit");
            assert.ok(button, "Submit button missing");
            assert.equal(button.value, "Join The ACLU");
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Test HMAC functionality.
 */
var assert = require('assert');
var jsHashes = require('../');

var MD5 = new jsHashes.MD5;
MD5.setUTF8(false);

// test vectors from http://www.ietf.org/rfc/rfc2104.txt
describe('Test MD5 HMAC (rfc2104)', function() {
    it("should pass test vector #1", function() {
        var key = '\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b';
        assert.equal(MD5.hex_hmac(key, 'Hi There'),
                     "9294727a3638bb1c13f48ef8158bfc9d");
    });
    it("should pass test vector #2", function() {
        assert.equal(MD5.hex_hmac("Jefe", "what do ya want for nothing?"),
                     "750c783e6ab0b503eaa86e310a5db738");
    });
    it("should pass test vector #3", function() {
        var key = '', data = '', i;
        for (i=0; i<16; i++) {
            key += '\xAA';
        }
        for (i=0; i<50; i++) {
            data += '\xDD';
        }
        assert.equal(MD5.hex_hmac(key, data),
                     '56be34521d144c88dbb8c733f0e8b3f6');
    });
});

// test vectors from
// http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
var testVectors = [
    {
        key: "",
        data: "",
        hmac: {
            MD5: "74e6f7298a9c2d168935f58c001bad88",
            SHA1: "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d",
            SHA256: "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"
        }
    },
    {
        key: "key",
        data: "The quick brown fox jumps over the lazy dog",
        hmac: {
            MD5: "80070713463e7749b90c2dc24911e275",
            SHA1: "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9",
            SHA256: "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
        }
    }
];
describe('Test HMAC (wikipedia test vectors)', function() {
    testVectors.forEach(function(tv) {
        var key = tv.key, data = tv.data;
        describe('key='+JSON.stringify(key)+" data="+JSON.stringify(data), function() {
            Object.keys(tv.hmac).forEach(function(h) {
                it('should have the correct HMAC_'+h, function() {
                    HF = new jsHashes[h]();
                    assert.equal(HF.hex_hmac(key, data), tv.hmac[h]);
                });
            });
        });
    });
});
<commit_msg>Additional HMAC test cases.<commit_after>/**
 * Test HMAC functionality.
 */
var assert = require('assert');
var jsHashes = require('../');

var MD5 = new jsHashes.MD5;
MD5.setUTF8(false);

// test vectors from http://www.ietf.org/rfc/rfc2104.txt
describe('Test MD5 HMAC (rfc2104)', function() {
    it("should pass test vector #1", function() {
        var key = '\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b';
        assert.equal(MD5.hex_hmac(key, 'Hi There'),
                     "9294727a3638bb1c13f48ef8158bfc9d");
    });
    it("should pass test vector #2", function() {
        assert.equal(MD5.hex_hmac("Jefe", "what do ya want for nothing?"),
                     "750c783e6ab0b503eaa86e310a5db738");
    });
    it("should pass test vector #3", function() {
        var key = '', data = '', i;
        for (i=0; i<16; i++) {
            key += '\xAA';
        }
        for (i=0; i<50; i++) {
            data += '\xDD';
        }
        assert.equal(MD5.hex_hmac(key, data),
                     '56be34521d144c88dbb8c733f0e8b3f6');
    });
});

// test vectors from
// http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
// SHA512/RMD160 from https://quickhash.com/
var testVectors = [
    {
        key: "",
        data: "",
        hmac: {
            MD5: "74e6f7298a9c2d168935f58c001bad88",
            SHA1: "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d",
            SHA256: "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad",
            SHA512: "b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47",
            RMD160: "44d86b658a3e7cbc1a2010848b53e35c917720ca"
        }
    },
    {
        key: "key",
        data: "The quick brown fox jumps over the lazy dog",
        hmac: {
            MD5: "80070713463e7749b90c2dc24911e275",
            SHA1: "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9",
            SHA256: "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8",
            SHA512: "b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a",
            RMD160: "50278a77d4d7670561ab72e867383aef6ce50b3e"
        }
    },
    // Test key > block size
    // These vectors are from https://quickhash.com/
    {
        key: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
        data: "The quick brown fox jumps over the lazy dog",
        hmac: {
            MD5: "8e86bf7840bbe52ba3f45030dba9d39a",
            SHA1: "ee114807434bea4ab839b940286f0c3f5b4f8a11",
            SHA256: "359706cae34991529dbf545ed055bed283da8b7339807db6affa2ae517d8b389",
            SHA512: "3135e1514cd8f6b471feb6980eedd1858047dd0c1fd44b135fade32d053b9a649f6c448fb81a6f0dc77f28f7d2505cd475aea018f90ff6961bd775acf3b8daad",
            RMD160: "5031d8b3399e949d4a48c9fcf10ae537b7294cbb"
        }
    }
];
describe('Test HMAC (wikipedia test vectors)', function() {
    testVectors.forEach(function(tv) {
        var key = tv.key, data = tv.data;
        describe('key='+JSON.stringify(key)+" data="+JSON.stringify(data), function() {
            Object.keys(tv.hmac).forEach(function(h) {
                it('should have the correct HMAC_'+h, function() {
                    HF = new jsHashes[h]();
                    assert.equal(HF.hex_hmac(key, data), tv.hmac[h]);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

describe("http", function () {

    it("knows config.httpPort", function () {
        assert(typeof config === "object" && typeof config.httpPort === "number");
    });

    describe("gpf.http", function () {

        if (config.httpPort === 0) {
            it("is not tested in this environment because config.httpPorty = 0", function () {
                assert(true);
            });
            return;
        }

        var baseUrl;

        before(function () {
            baseUrl = "http://localhost:" + config.httpPort + "/echo/?";
        });

        describe("basics", function () {
            it("allows the GET operation", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200"

                }).then(function (response) {
                    assert(response.status === 200);
                    var echoed = JSON.parse(response.responseText);
                    assert(echoed.method === "GET");
                    assert(echoed.url === "/echo/?status=200");
                    done();
                })["catch"](done);
            });

            it("offers the GET shortcut (using string parameter)", function (done) {
                gpf.http.get(baseUrl + "status=200").then(function (response) {
                    assert(response.status === 200);
                    var echoed = JSON.parse(response.responseText);
                    assert(echoed.method === "GET");
                    assert(echoed.url === "/echo/?status=200");
                    done();
                })["catch"](done);
            });

            it("offers the GET shortcut (using object parameter)", function (done) {
                gpf.http.get({
                    url: baseUrl + "status=200&response=Hello%20World"
                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.responseText === "Hello World");
                    done();
                })["catch"](done);
            });

            it("succeeds when the HTTP request fails", function (done) {
                gpf.http.get(baseUrl + "status=500").then(function (response) {
                    assert(response.status === 500);
                    done();
                })["catch"](done);
            });

            it("succeeds when the HTTP response is empty", function (done) {
                gpf.http.get(baseUrl + "response=").then(function (response) {
                    assert(response.responseText === "");
                    done();
                })["catch"](done);
            });
        });

        describe("headers", function () {
            it("forwards request headers", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200",
                    headers: {
                        "x-test": "Value"
                    }

                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.headers["x-test"] === "Value");
                    done();

                })["catch"](done);
            });

            it("gives access to response headers", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200&headers={\"x-test-1\":\"OK\",\"x-test-2\":123}"

                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.headers["x-test-1"] === "OK");
                    assert(response.headers["x-test-2"] === "123");
                    done();
                })["catch"](done);
            });
        });

        describe("methods", function () {
            [
                "post",
                "put",
                "options",
                "delete",
                "head"

            ].forEach(function (method, index) {

                var uppercasedMethod = method.toUpperCase(),
                    body,
                    checkResponse;

                if (index < 2) { // post & put
                    body = "Hello World";
                }

                if (method === "head") {
                    checkResponse = function () {}; // No response expected
                } else {
                    checkResponse = function (responseText) {
                        var echoed = JSON.parse(responseText);
                        assert(echoed.method === uppercasedMethod);
                        assert(echoed.url === "/echo/?status=200");
                        if (body) {
                            assert(echoed.body === body);
                        } else {
                            assert(!echoed.body);
                        }
                    };
                }

                it("allows the " + uppercasedMethod + " operation", function (done) {
                    gpf.http.request({
                        method: gpf.http.methods[method],
                        url: baseUrl + "status=200",
                        data: body

                    }).then(function (response) {
                        assert(response.status === 200);
                        checkResponse(response.responseText);
                        done();
                    })["catch"](done);
                });

                it("offers the " + uppercasedMethod + " shortcut", function (done) {
                    gpf.http[method](baseUrl + "status=200", body).then(function (response) {
                        assert(response.status === 200);
                        checkResponse(response.responseText);
                        done();
                    })["catch"](done);
                });

            });

            if (gpf.host() !== gpf.hosts.phantomjs) {
                it("allows any verb (MERGE)", function (done) {
                    gpf.http.request({
                        method: "merge",
                        url: baseUrl + "status=200"

                    }).then(function (response) {
                        assert(response.status === 200);
                        var echoed = JSON.parse(response.responseText);
                        assert(echoed.method === "MERGE");
                        assert(echoed.url === "/echo/?status=200");
                        done();
                    })["catch"](done);
                });
            }
        });

        if (gpf.hosts.browser !== gpf.host()) {

            describe("https", function () {

                it("handles https access", function (done) {
                    gpf.http.get("https://www.google.com/").then(function (response) {
                        assert(response.status === 200);
                        done();
                    })["catch"](done);
                });

            });

        }

    });

});
<commit_msg>Excluding java hosts (#298)<commit_after>"use strict";

describe("http", function () {

    it("knows config.httpPort", function () {
        assert(typeof config === "object" && typeof config.httpPort === "number");
    });

    describe("gpf.http", function () {

        if (config.httpPort === 0) {
            it("is not tested in this environment because config.httpPorty = 0", function () {
                assert(true);
            });
            return;
        }

        var baseUrl;

        before(function () {
            baseUrl = "http://localhost:" + config.httpPort + "/echo/?";
        });

        describe("basics", function () {
            it("allows the GET operation", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200"

                }).then(function (response) {
                    assert(response.status === 200);
                    var echoed = JSON.parse(response.responseText);
                    assert(echoed.method === "GET");
                    assert(echoed.url === "/echo/?status=200");
                    done();
                })["catch"](done);
            });

            it("offers the GET shortcut (using string parameter)", function (done) {
                gpf.http.get(baseUrl + "status=200").then(function (response) {
                    assert(response.status === 200);
                    var echoed = JSON.parse(response.responseText);
                    assert(echoed.method === "GET");
                    assert(echoed.url === "/echo/?status=200");
                    done();
                })["catch"](done);
            });

            it("offers the GET shortcut (using object parameter)", function (done) {
                gpf.http.get({
                    url: baseUrl + "status=200&response=Hello%20World"
                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.responseText === "Hello World");
                    done();
                })["catch"](done);
            });

            it("succeeds when the HTTP request fails", function (done) {
                gpf.http.get(baseUrl + "status=500").then(function (response) {
                    assert(response.status === 500);
                    done();
                })["catch"](done);
            });

            it("succeeds when the HTTP response is empty", function (done) {
                gpf.http.get(baseUrl + "response=").then(function (response) {
                    assert(response.responseText === "");
                    done();
                })["catch"](done);
            });
        });

        describe("headers", function () {
            it("forwards request headers", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200",
                    headers: {
                        "x-test": "Value"
                    }

                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.headers["x-test"] === "Value");
                    done();

                })["catch"](done);
            });

            it("gives access to response headers", function (done) {
                gpf.http.request({
                    method: gpf.http.methods.get,
                    url: baseUrl + "status=200&headers={\"x-test-1\":\"OK\",\"x-test-2\":123}"

                }).then(function (response) {
                    assert(response.status === 200);
                    assert(response.headers["x-test-1"] === "OK");
                    assert(response.headers["x-test-2"] === "123");
                    done();
                })["catch"](done);
            });
        });

        describe("methods", function () {
            [
                "post",
                "put",
                "options",
                "delete",
                "head"

            ].forEach(function (method, index) {

                var uppercasedMethod = method.toUpperCase(),
                    body,
                    checkResponse;

                if (index < 2) { // post & put
                    body = "Hello World";
                }

                if (method === "head") {
                    checkResponse = function () {}; // No response expected
                } else {
                    checkResponse = function (responseText) {
                        var echoed = JSON.parse(responseText);
                        assert(echoed.method === uppercasedMethod);
                        assert(echoed.url === "/echo/?status=200");
                        if (body) {
                            assert(echoed.body === body);
                        } else {
                            assert(!echoed.body);
                        }
                    };
                }

                it("allows the " + uppercasedMethod + " operation", function (done) {
                    gpf.http.request({
                        method: gpf.http.methods[method],
                        url: baseUrl + "status=200",
                        data: body

                    }).then(function (response) {
                        assert(response.status === 200);
                        checkResponse(response.responseText);
                        done();
                    })["catch"](done);
                });

                it("offers the " + uppercasedMethod + " shortcut", function (done) {
                    gpf.http[method](baseUrl + "status=200", body).then(function (response) {
                        assert(response.status === 200);
                        checkResponse(response.responseText);
                        done();
                    })["catch"](done);
                });

            });

            if ([gpf.hosts.nashorn, gpf.hosts.phantomjs, gpf.hosts.rhino].indexOf(gpf.host()) === -1) {
                it("allows any verb (MERGE)", function (done) {
                    gpf.http.request({
                        method: "merge",
                        url: baseUrl + "status=200"

                    }).then(function (response) {
                        assert(response.status === 200);
                        var echoed = JSON.parse(response.responseText);
                        assert(echoed.method === "MERGE");
                        assert(echoed.url === "/echo/?status=200");
                        done();
                    })["catch"](done);
                });
            }
        });

        if (gpf.hosts.browser !== gpf.host()) {

            describe("https", function () {

                it("handles https access", function (done) {
                    gpf.http.get("https://www.google.com/").then(function (response) {
                        assert(response.status === 200);
                        done();
                    })["catch"](done);
                });

            });

        }

    });

});
<|endoftext|>


<commit_before>var assert = require("assert"),
    hull = require('../src/hull.js');

module.exports = function() {
    it('should return correct hull of the "?" symbol', function() {
        var points = [[162, 332], [182, 299], [141, 292], [158, 264], [141, 408], [160, 400], [177, 430], [151, 442], [155, 425], [134, 430], [126, 447], [139, 466], [160, 471], [167, 447], [182, 466], [192, 442], [187, 413], [173, 403], [168, 425], [153, 413], [179, 275], [163, 292], [134, 270], [143, 315], [177, 320], [163, 311], [162, 281], [182, 255], [141, 226], [156, 235], [173, 207], [187, 230], [204, 194], [165, 189], [145, 201], [158, 167], [190, 165], [206, 145], [179, 153], [204, 114], [221, 138], [243, 112], [248, 139], [177, 122], [179, 99], [196, 82], [219, 90], [240, 75], [218, 61], [228, 53], [211, 34], [197, 51], [179, 65], [155, 70], [165, 85], [134, 80], [124, 58], [153, 44], [173, 34], [192, 27], [156, 19], [119, 32], [128, 17], [138, 36], [100, 58], [112, 73], [100, 92], [78, 100], [83, 78], [61, 63], [80, 44], [100, 26], [60, 39], [43, 71], [34, 54], [32, 90], [53, 104], [60, 82], [66, 99], [247, 94], [187, 180], [221, 168]];
        var expected = [[248, 139], [221, 168], [204, 194], [187, 230], [179, 275], [182, 299], [177, 320], [162, 332], [160, 400], [173, 403], [187, 413], [192, 442], [182, 466], [160, 471], [139, 466], [126, 447], [134, 430], [141, 408], [143, 315], [141, 292], [134, 270], [141, 226], [145, 201], [158, 167], [177, 122], [179, 99], [165, 85], [134, 80], [100, 92], [78, 100], [53, 104], [32, 90], [34, 54], [60, 39], [100, 26], [128, 17], [156, 19], [192, 27], [211, 34], [228, 53], [240, 75], [247, 94], [248, 139]];

        assert.deepEqual(hull(points, 50), expected);
    });

    it('should return only outer hull of the polygon with hole', function() {
        var points = [[141, 408], [160, 400], [177, 430], [151, 442], [155, 425], [134, 430], [126, 447], [139, 466], [160, 471], [167, 447], [182, 466], [192, 442], [187, 413], [173, 403], [165, 430], [171, 430], [177, 437], [175, 443], [172, 444], [163, 448], [156, 447], [153, 438], [154, 431], [160, 428]];
        var expected = [[192,442], [182,466], [160,471], [139,466], [126,447], [141,408], [160,400], [173,403], [187,413], [192,442]];
        assert.deepEqual(hull(points, 50), expected);
    });

    it('should return concave hull with lngs and lats', function() {
        var points = [{lng:-0.206792373176235, lat:51.4911165465815 }, {lng:-0.207062672933557, lat:51.4915703125214 }, {lng:-0.207465840096923, lat:51.4912077781219 }, {lng:-0.210193421020222, lat:51.4918159814458 }, {lng:-0.214944392455692, lat:51.4929945001276 }, {lng:-0.208133371509344, lat:51.4910830915252 }, {lng:-0.214162055384851, lat:51.4905275966855 }, {lng:-0.208161917730384, lat:51.4903551232517 }, {lng:-0.209680931181673, lat:51.4901894811742 }, {lng:-0.212571431609104, lat:51.4903145141462 }, {lng:-0.216849005460861, lat:51.4921781720221}];
        var expected = [{lng: -0.206792373176235, lat: 51.4911165465815 }, {lng: -0.207062672933557, lat: 51.4915703125214 }, {lng: -0.207465840096923, lat: 51.4912077781219 }, {lng: -0.210193421020222, lat: 51.4918159814458 }, {lng: -0.214944392455692, lat: 51.4929945001276 }, {lng: -0.216849005460861, lat: 51.4921781720221 }, {lng: -0.214162055384851, lat: 51.4905275966855 }, {lng: -0.212571431609104, lat: 51.4903145141462 }, {lng: -0.209680931181673, lat: 51.4901894811742 }, {lng: -0.208161917730384, lat: 51.4903551232517 }, {lng: -0.208133371509344, lat: 51.4910830915252 }, {lng: -0.206792373176235, lat: 51.4911165465815}];
        assert.deepEqual(hull(points, 0.0011, ['.lng', '.lat']), expected);
    });
}<commit_msg>test fixed<commit_after>var assert = require("assert"),
    hull = require('../src/hull.js');

module.exports = function() {
    it('should return correct hull of the "?" symbol', function() {
        var points = [[162, 332], [182, 299], [141, 292], [158, 264], [141, 408], [160, 400], [177, 430], [151, 442], [155, 425], [134, 430], [126, 447], [139, 466], [160, 471], [167, 447], [182, 466], [192, 442], [187, 413], [173, 403], [168, 425], [153, 413], [179, 275], [163, 292], [134, 270], [143, 315], [177, 320], [163, 311], [162, 281], [182, 255], [141, 226], [156, 235], [173, 207], [187, 230], [204, 194], [165, 189], [145, 201], [158, 167], [190, 165], [206, 145], [179, 153], [204, 114], [221, 138], [243, 112], [248, 139], [177, 122], [179, 99], [196, 82], [219, 90], [240, 75], [218, 61], [228, 53], [211, 34], [197, 51], [179, 65], [155, 70], [165, 85], [134, 80], [124, 58], [153, 44], [173, 34], [192, 27], [156, 19], [119, 32], [128, 17], [138, 36], [100, 58], [112, 73], [100, 92], [78, 100], [83, 78], [61, 63], [80, 44], [100, 26], [60, 39], [43, 71], [34, 54], [32, 90], [53, 104], [60, 82], [66, 99], [247, 94], [187, 180], [221, 168]];
        var expected = [[248,139], [221,168], [204,194], [187,230], [182,255], [182,299], [177,320], [162,332], [160,400], [173,403], [187,413], [192,442], [182,466], [160,471], [139,466], [126,447], [134,430], [141,408], [143,315], [141,292], [134,270], [141,226], [145,201], [158,167], [177,122], [179,99], [165,85], [134,80], [100,92], [78,100], [53,104], [32,90], [34,54], [60,39], [100,26], [128,17], [156,19], [192,27], [211,34], [228,53], [240,75], [247,94], [248,139]];
        assert.deepEqual(hull(points, 50), expected);
    });

    it('should return only outer hull of the polygon with hole', function() {
        var points = [[141, 408], [160, 400], [177, 430], [151, 442], [155, 425], [134, 430], [126, 447], [139, 466], [160, 471], [167, 447], [182, 466], [192, 442], [187, 413], [173, 403], [165, 430], [171, 430], [177, 437], [175, 443], [172, 444], [163, 448], [156, 447], [153, 438], [154, 431], [160, 428]];
        var expected = [[192,442], [182,466], [160,471], [139,466], [126,447], [141,408], [160,400], [173,403], [187,413], [192,442]];
        assert.deepEqual(hull(points, 50), expected);
    });

    it('should return concave hull with lngs and lats', function() {
        var points = [{lng:-0.206792373176235, lat:51.4911165465815 }, {lng:-0.207062672933557, lat:51.4915703125214 }, {lng:-0.207465840096923, lat:51.4912077781219 }, {lng:-0.210193421020222, lat:51.4918159814458 }, {lng:-0.214944392455692, lat:51.4929945001276 }, {lng:-0.208133371509344, lat:51.4910830915252 }, {lng:-0.214162055384851, lat:51.4905275966855 }, {lng:-0.208161917730384, lat:51.4903551232517 }, {lng:-0.209680931181673, lat:51.4901894811742 }, {lng:-0.212571431609104, lat:51.4903145141462 }, {lng:-0.216849005460861, lat:51.4921781720221}];
        var expected = [{lng: -0.206792373176235, lat: 51.4911165465815 }, {lng: -0.207062672933557, lat: 51.4915703125214 }, {lng: -0.207465840096923, lat: 51.4912077781219 }, {lng: -0.210193421020222, lat: 51.4918159814458 }, {lng: -0.214944392455692, lat: 51.4929945001276 }, {lng: -0.216849005460861, lat: 51.4921781720221 }, {lng: -0.214162055384851, lat: 51.4905275966855 }, {lng: -0.212571431609104, lat: 51.4903145141462 }, {lng: -0.209680931181673, lat: 51.4901894811742 }, {lng: -0.208161917730384, lat: 51.4903551232517 }, {lng: -0.208133371509344, lat: 51.4910830915252 }, {lng: -0.206792373176235, lat: 51.4911165465815}];
        assert.deepEqual(hull(points, 0.0011, ['.lng', '.lat']), expected);
    });
}<|endoftext|>


<commit_before>describe('Incr/Decr', function() {
  'use strict';

  var client = gazel.createClient();

  var set = function(key, value, then) {
    client.set(key, value, function(res) {
      if(res !== 'OK') {
        done(new Error('Set value is not OK'));

        return;
      }

      then(res);
    });
  };

  it('incr should increment a set value by 1', function(done) {
    client.set('foo', 1, function(err) {
      if(err !== 'OK') {
        done(new Error());
      }

      client.incr('foo', function(res) {
        done(assert.equal(res, 2));
      });
    });
  });

  it('incrby should increment by value told', function(done) {
    client.set('foo', 1, function(err) {
      if(err !== 'OK') {
        done(new Error());
      }

      client.incrby('foo', 13, function(res) {
        done(assert.equal(res, 14));
      });
    });
  });

  it('decr should decrement value by 1', function(done) {
    set('foo', 1, function() {
      client.decr('foo', function(res) {
       done(assert.equal(res, 0));
      });
    });
  });

  it('decrby should decrement by given amount', function(done) {
    set('foo', 5, function() {
      client.decrby('foo', 6, function(res) {
        done(assert.equal(res, -1));
      });
    });
  });

  it('incr should set value to 1 if value not existant', function(done) {
    client.incr('notexists', function(res) {
      done(assert.equal(res, 1));
    });
  });

  it('should return error if incrementing string', function(done) {
    set('foo', 'bar', function() {
      client.incr('foo', function(res) {
        done(assert.ok(false, 'We should not get here.'));
      });
    });
  });
});
<commit_msg>Not-exists test on incr should delete the key first.<commit_after>describe('Incr/Decr', function() {
  'use strict';

  var client = gazel.createClient();

  var set = function(key, value, then) {
    client.set(key, value, function(res) {
      if(res !== 'OK') {
        done(new Error('Set value is not OK'));

        return;
      }

      then(res);
    });
  };

  it('incr should increment a set value by 1', function(done) {
    client.set('foo', 1, function(err) {
      if(err !== 'OK') {
        done(new Error());
      }

      client.incr('foo', function(res) {
        done(assert.equal(res, 2));
      });
    });
  });

  it('incrby should increment by value told', function(done) {
    client.set('foo', 1, function(err) {
      if(err !== 'OK') {
        done(new Error());
      }

      client.incrby('foo', 13, function(res) {
        done(assert.equal(res, 14));
      });
    });
  });

  it('decr should decrement value by 1', function(done) {
    set('foo', 1, function() {
      client.decr('foo', function(res) {
       done(assert.equal(res, 0));
      });
    });
  });

  it('decrby should decrement by given amount', function(done) {
    set('foo', 5, function() {
      client.decrby('foo', 6, function(res) {
        done(assert.equal(res, -1));
      });
    });
  });

  it('incr should set value to 1 if value not existant', function(done) {
    client.del('notexists', function(resp) {
      client.incr('notexists', function(res) {
        done(assert.equal(res, 1));
      });
    });
  });

  it('should return error if incrementing string', function(done) {
    set('foo', 'bar', function() {
      client.incr('foo', function(res) {
        done(assert.ok(false, 'We should not get here.'));
      });
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');
var Common = require('./helpers/common');
var debug = require('debug')('oshi-test:logging');
var Oshi = require('..');
var Package = require('../package.json');

suite('Process Info', function ()
{
	var procs = {
		'simple-test-app:5107': null,
		'simple-test-app:5108': null,
		'another-test-app:5109': null,
		'another-test-app:5110': null,
	};

	suiteSetup(function (done)
	{
		Common.suiteSetup(function ()
		{
			var names = Object.keys(procs);
			var pending = names.length;
			function checkDone(name, err, info)
			{
				if (err) return done(err);
				procs[name] = info;
				if (--pending === 0)
					done();
			}

			names.forEach(function (name)
			{
				var parts = name.split(/:/);
				var script = 'test/helpers/' + parts[0] + '.js';
				Common.prepareAndStart(script, name, checkDone.bind(null, name));
			});
		});
	});

	suiteTeardown(function (done)
	{
		var names = Object.keys(procs);
		var pending = names.length;

		function checkDone(name, err, info)
		{
			if (err) return done(err);
			procs[name] = null;
			if (--pending === 0)
				Common.suiteTeardown(done);
		}

		names.forEach(function (name)
		{
			Common.api.stop(name, checkDone.bind(null, name));
		});
	});

	function infoTest(name, names, cb)
	{
		test(name, function (done)
		{
			Common.api.info(names, function (err, info)
			{
				if (err) return done(err);
				cb(info);
				done();
			});
		});
	}

	suite('Single', function ()
	{
		var name = 'simple-test-app:5107';

		infoTest('returns info object', name, function (info)
		{
			debug('info: %j', info);
			assert(!!info, 'info object not returned');
		});

		infoTest('info object has group', name, function (info)
		{
			assert('simple-test-app' in info, 'expected group not found');
			assert(typeof info['simple-test-app'] === 'object', 'group name property is not object');
		});

		infoTest('group object has port', name, function (info)
		{
			var g1 = info['simple-test-app'];
			assert('5107' in g1, 'port number not in group object');
		});

		infoTest('info object looks right', name, function (info)
		{
			var i1 = info['simple-test-app']['5107'];
			assert(typeof i1 === 'object', 'info member is not an object');

			assert('cpu' in i1, 'cpu property not found');
			assert('memory' in i1, 'memory property not found');

			assert(typeof i1.cpu === 'number', 'cpu property is not a number');
			assert(typeof i1.memory === 'number', 'memory property is not a number');
		});
	});

	suite('Multiple', function ()
	{
		var names = [
			'simple-test-app:5107',
			'simple-test-app:5108',
			'another-test-app:5109',
			'another-test-app:5110'
		];

		infoTest('info object has all groups', names, function (info)
		{
			assert('simple-test-app' in info, 'simple-test-app not found');
			assert('another-test-app' in info, 'another-test-app not found');

			assert(typeof info['simple-test-app'] === 'object', 'simple-test-app name property is not object');
			assert(typeof info['another-test-app'] === 'object', 'another-test-app property is not object');
		});

		infoTest('info object has all children', names, function (info)
		{

			assert(typeof info['simple-test-app'] === 'object', 'simple-test-app name property is not object');
			assert(typeof info['another-test-app'] === 'object', 'another-test-app property is not object');
		});
	});

});
<commit_msg>report actual type when assert fails<commit_after>"use strict";

var assert = require('assert');
var Common = require('./helpers/common');
var debug = require('debug')('oshi-test:logging');
var Oshi = require('..');
var Package = require('../package.json');

suite('Process Info', function ()
{
	var procs = {
		'simple-test-app:5107': null,
		'simple-test-app:5108': null,
		'another-test-app:5109': null,
		'another-test-app:5110': null,
	};

	suiteSetup(function (done)
	{
		Common.suiteSetup(function ()
		{
			var names = Object.keys(procs);
			var pending = names.length;
			function checkDone(name, err, info)
			{
				if (err) return done(err);
				procs[name] = info;
				if (--pending === 0)
					done();
			}

			names.forEach(function (name)
			{
				var parts = name.split(/:/);
				var script = 'test/helpers/' + parts[0] + '.js';
				Common.prepareAndStart(script, name, checkDone.bind(null, name));
			});
		});
	});

	suiteTeardown(function (done)
	{
		var names = Object.keys(procs);
		var pending = names.length;

		function checkDone(name, err, info)
		{
			if (err) return done(err);
			procs[name] = null;
			if (--pending === 0)
				Common.suiteTeardown(done);
		}

		names.forEach(function (name)
		{
			Common.api.stop(name, checkDone.bind(null, name));
		});
	});

	function infoTest(name, names, cb)
	{
		test(name, function (done)
		{
			Common.api.info(names, function (err, info)
			{
				if (err) return done(err);
				cb(info);
				done();
			});
		});
	}

	suite('Single', function ()
	{
		var name = 'simple-test-app:5107';

		infoTest('returns info object', name, function (info)
		{
			debug('info: %j', info);
			assert(!!info, 'info object not returned');
		});

		infoTest('info object has group', name, function (info)
		{
			assert('simple-test-app' in info, 'expected group not found');
			assert(typeof info['simple-test-app'] === 'object', 'group name property is not object');
		});

		infoTest('group object has port', name, function (info)
		{
			var g1 = info['simple-test-app'];
			assert('5107' in g1, 'port number not in group object');
		});

		infoTest('info object looks right', name, function (info)
		{
			var i1 = info['simple-test-app']['5107'];
			assert(typeof i1 === 'object', 'info member is not an object');

			assert('cpu' in i1, 'cpu property not found');
			assert('memory' in i1, 'memory property not found');

			assert(typeof i1.cpu === 'number', 'cpu property is not a number (' + (typeof i1.cpu) + ' instead)');
			assert(typeof i1.memory === 'number', 'memory property is not a number (' + (typeof i1.memory) + ' instead)');
		});
	});

	suite('Multiple', function ()
	{
		var names = [
			'simple-test-app:5107',
			'simple-test-app:5108',
			'another-test-app:5109',
			'another-test-app:5110'
		];

		infoTest('info object has all groups', names, function (info)
		{
			assert('simple-test-app' in info, 'simple-test-app not found');
			assert('another-test-app' in info, 'another-test-app not found');

			assert(typeof info['simple-test-app'] === 'object', 'simple-test-app name property is not object');
			assert(typeof info['another-test-app'] === 'object', 'another-test-app property is not object');
		});

		infoTest('info object has all children', names, function (info)
		{

			assert(typeof info['simple-test-app'] === 'object', 'simple-test-app name property is not object');
			assert(typeof info['another-test-app'] === 'object', 'another-test-app property is not object');
		});
	});

});
<|endoftext|>


<commit_before>import File from './models/file'
import { MongoMemoryServer } from 'mongodb-memory-server'
import Person from './models/person'
import Product from './models/product'
import Starship from './models/starship'
import Story from './models/story'
import fileData from './data/files.json'
import mongoose from 'mongoose'
import productData from './data/products.json'
import starshipData from './data/starships.json'

const mongoServer = new MongoMemoryServer({
  autoStart: false
})

mongoose.Promise = global.Promise

function clearDB () {
  return Promise.all([
    Starship.deleteMany(),
    Product.deleteMany(),
    File.deleteMany(),
    Story.deleteMany(),
    Person.deleteMany()
  ])
}

function populateStarship () {
  const { data: { allStarships: { edges } } } = starshipData
  return Promise.all(edges.map(({ node }) => {
    const ship = new Starship(node)
    return ship.save()
  }))
}

function populateProduct () {
  return Promise.all(productData.map(p => {
    const product = new Product(p)
    return product.save()
  }))
}

function populateFile () {
  return Promise.all(fileData.map(f => {
    const file = new File(f)
    return file.save()
  }))
}

async function populateStory () {
  const p1 = new Person({ name: 'Richard Feynman', age: 69 })
  const p2 = new Person({ name: 'Nikola Tesla', age: 86 })
  const s1 = new Story({ title: 'Feynman Diagram', author: p1._id })
  const s2 = new Story({ title: 'Tesla Coil', author: p2._id })
  await Promise.all([
    p1.save(),
    p2.save(),
    s1.save()
  ])
  await s2.save() // so that s2 is saved after s1
}

function populateData () {
  return Promise.all([
    populateStarship(),
    populateProduct(),
    populateFile(),
    populateStory()
  ])
}

// executed only once
before(async () => {
  if (!mongoServer.isRunning) {
    await mongoServer.start()
  }

  const mongoUri = await mongoServer.getConnectionString()
  await mongoose.connect(mongoUri, { useNewUrlParser: true })

  await clearDB()
  await populateData()
})

after(() => {
  mongoose.connection.close()
  mongoServer.stop()
})
<commit_msg>:green_heart: try increasing timeout for travis<commit_after>import File from './models/file'
import { MongoMemoryServer } from 'mongodb-memory-server'
import Person from './models/person'
import Product from './models/product'
import Starship from './models/starship'
import Story from './models/story'
import fileData from './data/files.json'
import mongoose from 'mongoose'
import productData from './data/products.json'
import starshipData from './data/starships.json'

const mongoServer = new MongoMemoryServer({
  autoStart: false
})

mongoose.Promise = global.Promise

function clearDB () {
  return Promise.all([
    Starship.deleteMany(),
    Product.deleteMany(),
    File.deleteMany(),
    Story.deleteMany(),
    Person.deleteMany()
  ])
}

function populateStarship () {
  const { data: { allStarships: { edges } } } = starshipData
  return Promise.all(edges.map(({ node }) => {
    const ship = new Starship(node)
    return ship.save()
  }))
}

function populateProduct () {
  return Promise.all(productData.map(p => {
    const product = new Product(p)
    return product.save()
  }))
}

function populateFile () {
  return Promise.all(fileData.map(f => {
    const file = new File(f)
    return file.save()
  }))
}

async function populateStory () {
  const p1 = new Person({ name: 'Richard Feynman', age: 69 })
  const p2 = new Person({ name: 'Nikola Tesla', age: 86 })
  const s1 = new Story({ title: 'Feynman Diagram', author: p1._id })
  const s2 = new Story({ title: 'Tesla Coil', author: p2._id })
  await Promise.all([
    p1.save(),
    p2.save(),
    s1.save()
  ])
  await s2.save() // so that s2 is saved after s1
}

function populateData () {
  return Promise.all([
    populateStarship(),
    populateProduct(),
    populateFile(),
    populateStory()
  ])
}

// executed only once
before(async function () {
  this.timeout(60000)
  if (!mongoServer.isRunning) {
    await mongoServer.start()
  }

  const mongoUri = await mongoServer.getConnectionString()
  await mongoose.connect(mongoUri, { useNewUrlParser: true })

  await clearDB()
  await populateData()
})

after(() => {
  mongoose.connection.close()
  mongoServer.stop()
})
<|endoftext|>


<commit_before>/* jshint node: true */
/* global describe, it */

'use strict';

var assert      = require('assert');
var es          = require('event-stream');
var fs          = require('fs');
var gutil       = require('gulp-util');
var PassThrough = require('stream').PassThrough;
var through     = require('through2');
var path        = require('path');
var indexpipe   = require('../index');

var jsmin   = require('gulp-uglify');
var htmlmin = require('gulp-minify-html');
var cssmin  = require('gulp-minify-css');

function getFile(filePath) {
  return new gutil.File({
    path:     filePath,
    base:     path.dirname(filePath),
    contents: fs.readFileSync(filePath)
  });
}

function getActual(filePath) {
  return getFile(path.join('test', 'fixtures', filePath));
}

function getExpected(filePath) {
  return getFile(path.join('test', 'expected', filePath));
}

function compare(actualName, expectedName, args, done) {

  function onData(file) {
    if (path.basename(file.path) !== expectedName)
      throw('File emitted that was not expected index');

    var expectedContent = String(getExpected(expectedName).contents);
    var actualContent   = String(file.contents);
    assert.equal(expectedContent, actualContent);
  }

  function onEnd() {
    done();
  }

  var stream = indexpipe(args);
  stream.on('data', onData);
  stream.on('end', onEnd);
  stream.write(getActual(actualName));
  stream.end();
}

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

  it('section identity transform', function(done) {

    var args = {
      jsmin: through.obj(function (file, enc, callback) {
        this.push(file);
        callback();
      })
    };

    compare('simple-identity.html', 'simple-identity.html', args, done);
  });

  // describe('negative test:', function() {
  //  it('shouldn\'t work in stream mode', function(done) {
  //    var stream = usemin();
  //    var t;
  //    var fakeStream = new PassThrough();
  //    var fakeFile = new gutil.File({
  //      contents: fakeStream
  //    });
  //    fakeStream.end();

  //    stream.on('error', function() {
  //      clearTimeout(t);
  //      done();
  //    });

  //    t = setTimeout(function() {
  //      assert.fail('', '', 'Should throw error', '');
  //      done();
  //    }, 1000);

  //    stream.write(fakeFile);
  //    stream.end();
  //  });

  //  it('html without blocks', function(done) {
  //    var stream = usemin();
  //    var content = '
content
';
  //    var fakeFile = new gutil.File({
  //      contents: new Buffer(content)
  //    });

  //    stream.on('data', function(newFile) {
  //      assert.equal(content, String(newFile.contents));
  //    });

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

  //    stream.write(fakeFile);
  //    stream.end();
  //  });
  // });

    //  it('simple js block with path', function(done) {
    //    compare('simple-js-path.html', 'min-simple-js-path.html', done);
    //  });

    //  it('simple css block', function(done) {
    //    compare('simple-css.html', 'min-simple-css.html', done);
    //  });

    //  it('simple css block with path', function(done) {
    //    compare('simple-css-path.html', 'min-simple-css-path.html', done);
    //  });

    //  it('complex (css + js)', function(done) {
    //    compare('complex.html', 'min-complex.html', done);
    //  });

    //  it('complex with path (css + js)', function(done) {
    //    compare('complex-path.html', 'min-complex-path.html', done);
    //  });
    // });

    // describe('not minified HTML:', function() {
    //  function compare(name, expectedName, done) {
    //    var stream = usemin();

    //    stream.on('data', function(newFile) {
    //      if (path.basename(newFile.path) === name)
    //        assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //    });
    //    stream.on('end', function() {
    //      done();
    //    });

    //    stream.write(getFixture(name));
    //    stream.end();
    //  }

    //  it('simple (js block)', function(done) {
    //    compare('simple-js.html', 'simple-js.html', done);
    //  });

    //  it('simple (js block) (html minified)', function(done) {
    //    compare('min-html-simple-js.html', 'min-html-simple-js.html', done);
    //  });

    //  it('simple with path (js block)', function(done) {
    //    compare('simple-js-path.html', 'simple-js-path.html', done);
    //  });

    //  it('simple (css block)', function(done) {
    //    compare('simple-css.html', 'simple-css.html', done);
    //  });

    //  it('simple (css block) (html minified)', function(done) {
    //    compare('min-html-simple-css.html', 'min-html-simple-css.html', done);
    //  });

    //  it('simple with path (css block)', function(done) {
    //    compare('simple-css-path.html', 'simple-css-path.html', done);
    //  });

    //  it('complex (css + js)', function(done) {
    //    compare('complex.html', 'complex.html', done);
    //  });

    //  it('complex with path (css + js)', function(done) {
    //    compare('complex-path.html', 'complex-path.html', done);
    //  });
    // });

    // describe('minified CSS:', function() {
    //  function compare(name, callback, end) {
    //    var stream = usemin({cssmin: cssmin()});

    //    stream.on('data', callback);
    //    stream.on('end', end);

    //    stream.write(getFixture(name));
    //    stream.end();
    //  }

    //  it('simple (css block)', function(done) {
    //    var name = 'style.css';
    //    var expectedName = 'min-style.css';
    //    var exist = false;

    //    compare(
    //      'simple-css.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with path (css block)', function(done) {
    //    var name = path.join('data', 'css', 'style.css');
    //    var expectedName = path.join('data', 'css', 'min-style.css');
    //    var exist = false;

    //    compare(
    //      'simple-css-path.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with alternate path (css block)', function(done) {
    //    var name = path.join('data', 'css', 'style.css');
    //    var expectedName = path.join('data', 'css', 'min-style.css');
    //    var exist = false;

    //    compare(
    //      'simple-css-alternate-path.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });
    // });

    // describe('not minified CSS:', function() {
    //  function compare(name, callback, end) {
    //    var stream = usemin();

    //    stream.on('data', callback);
    //    stream.on('end', end);

    //    stream.write(getFixture(name));
    //    stream.end();
    //  }

    //  it('simple (css block)', function(done) {
    //    var expectedName = 'style.css';
    //    var exist = false;

    //    compare(
    //      'simple-css.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple (css block) (minified html)', function(done) {
    //    var expectedName = 'style.css';
    //    var exist = false;

    //    compare(
    //      'min-html-simple-css.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with path (css block)', function(done) {
    //    var expectedName = path.join('data', 'css', 'style.css');
    //    var exist = false;

    //    compare(
    //      'simple-css-path.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with alternate path (css block)', function(done) {
    //    var expectedName = path.join('data', 'css', 'style.css');
    //    var exist = false;

    //    compare(
    //      'simple-css-alternate-path.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });
    // });

    // describe('minified JS:', function() {
    //  function compare(name, callback, end) {
    //    var stream = usemin({jsmin: jsmin()});

    //    stream.on('data', callback);
    //    stream.on('end', end);

    //    stream.write(getFixture(name));
    //    stream.end();
    //  }

    //  it('simple (js block)', function(done) {
    //    var name = 'app.js';
    //    var expectedName = 'min-app.js';
    //    var exist = false;

    //    compare(
    //      'simple-js.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with path (js block)', function(done) {
    //    var name = path.join('data', 'js', 'app.js');
    //    var expectedName = path.join('data', 'js', 'min-app.js');
    //    var exist = false;

    //    compare(
    //      'simple-js-path.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with alternate path (js block)', function(done) {
    //    var name = path.join('data', 'js', 'app.js');
    //    var expectedName = path.join('data', 'js', 'min-app.js');
    //    var exist = false;

    //    compare(
    //      'simple-js-alternate-path.html',
    //      function(newFile) {
    //        if (newFile.path === name) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });
    // });

    // describe('not minified JS:', function() {
    //  function compare(name, callback, end) {
    //    var stream = usemin();

    //    stream.on('data', callback);
    //    stream.on('end', end);

    //    stream.write(getFixture(name));
    //    stream.end();
    //  }

    //  it('simple (js block)', function(done) {
    //    var expectedName = 'app.js';
    //    var exist = false;

    //    compare(
    //      'simple-js.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple (js block) (minified html)', function(done) {
    //    var expectedName = 'app.js';
    //    var exist = false;

    //    compare(
    //      'min-html-simple-js.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with path (js block)', function(done) {
    //    var expectedName = path.join('data', 'js', 'app.js');
    //    var exist = false;

    //    compare(
    //      'simple-js-path.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });

    //  it('simple with alternate path (js block)', function(done) {
    //    var expectedName = path.join('data', 'js', 'app.js');
    //    var exist = false;

    //    compare(
    //      'simple-js-alternate-path.html',
    //      function(newFile) {
    //        if (newFile.path === expectedName) {
    //          exist = true;
    //          assert.equal(String(getExpected(expectedName).contents), String(newFile.contents));
    //        }
    //      },
    //      function() {
    //        assert.ok(exist);
    //        done();
    //      }
    //    );
    //  });
});
<commit_msg>Removed unused code<commit_after>/* jshint node: true */
/* global describe, it */

'use strict';

var assert      = require('assert');
var es          = require('event-stream');
var fs          = require('fs');
var gutil       = require('gulp-util');
var PassThrough = require('stream').PassThrough;
var through     = require('through2');
var path        = require('path');
var indexpipe   = require('../index');

var jsmin   = require('gulp-uglify');
var htmlmin = require('gulp-minify-html');
var cssmin  = require('gulp-minify-css');

function getFile(filePath) {
  return new gutil.File({
    path:     filePath,
    base:     path.dirname(filePath),
    contents: fs.readFileSync(filePath)
  });
}

function getActual(filePath) {
  return getFile(path.join('test', 'fixtures', filePath));
}

function getExpected(filePath) {
  return getFile(path.join('test', 'expected', filePath));
}

function compare(actualName, expectedName, args, done) {

  function onData(file) {
    if (path.basename(file.path) !== expectedName)
      throw('File emitted that was not expected index');

    var expectedContent = String(getExpected(expectedName).contents);
    var actualContent   = String(file.contents);
    assert.equal(expectedContent, actualContent);
  }

  function onEnd() {
    done();
  }

  var stream = indexpipe(args);
  stream.on('data', onData);
  stream.on('end', onEnd);
  stream.write(getActual(actualName));
  stream.end();
}

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

  it('section identity', function(done) {
    var args = {
      jsmin: new PassThrough()
    };

    compare('simple-identity.html', 'simple-identity.html', args, done);
  });

  it('section transform', function(done) {
    var reduced = false
    var args = {
      jsmin: through.obj(function (file, enc, callback) {
        if(reduced)
          return
        this.push(new gutil.File({
          path    : 'app.js',
          contents: ''
        }));
        callback();
        reduced = true
      })
    };

    compare('simple-transform.html', 'simple-transform.html', args, done);
  });
});
<|endoftext|>


<commit_before>'use strict';

var path      = require('path');
var pkg       = require('../package.json');
var Path      = require(path.join(__dirname, '..', pkg.main));
var should    = require('should');

require('mocha');

describe('Path', function () {
    it('should throw an error when instanciated without parameter', function () {
        (function () {
            new Path()
        }).should.throw();
    });

    it('should throw an error if Path is used like a function', function () {
        (function () {
            Path()
        }).should.throw();
    });

    it('should throw an error if a path cannot be tokenised', function () {
        (function () {
            new Path('/!#')
        }).should.throw();
    });

    it('should return a path if createPath is used', function () {
        should.exist(Path.createPath('/users'));
    });

    it('should match and build paths with url parameters', function () {
        var path = new Path('/users/profile/:id-:id2.html');
        // Successful match & partial match
        path.match('/users/profile/123-abc.html').should.eql({ id: '123', id2: 'abc' });
        path.partialMatch('/users/profile/123-abc.html?what').should.eql({ id: '123', id2: 'abc' });
        // Unsuccessful match
        should.not.exist(path.match('/users/details/123-abc'));
        should.not.exist(path.match('/users/details/123-abc.html'));
        should.not.exist(path.match('/users/profile/123-abc.html?what'));

        path.build({ id: '123', id2: 'abc' }).should.equal('/users/profile/123-abc.html');
        (function () {
            path.build({ id: '123'});
        }).should.throw('Missing parameters');
    });

    it('should match and build paths with query parameters', function () {
        var path = new Path('/users?offset&limit');
        // Successful match & partial match
        path.match('/users?offset=31&limit=15').should.eql({ offset: '31', limit: '15' });
        path.match('/users?offset=31&offset=30&limit=15').should.eql({ offset: ['31', '30'], limit: '15' });
        path.match('/users?offset&limit=15').should.eql({ offset: '', limit: '15' });
        path.match('/users?limit=15').should.eql({ limit: '15' });
        path.partialMatch('/users?offset&limits=1').should.eql({ offset: '' });
        path.partialMatch('/users').should.eql({});

        // Unsuccessful match
        should.not.exist(path.match('/users?offset=31&order=asc'));
        should.not.exist(path.match('/users?offset=31&limit=10&order=asc'));

        path.build({ offset: 31, limit: 15 }).should.equal('/users?offset=31&limit=15');
        path.build({ offset: 31 }).should.equal('/users?offset=31');
        path.build({ offset: 31, limit: '' }).should.equal('/users?offset=31&limit');
        path.build({ offset: 31, limit: undefined  }).should.equal('/users?offset=31&limit');
        path.build({ offset: 31, limit: false  }).should.equal('/users?offset=31&limit=false');
        path.build({ offset: [31, 30], limit: false  }).should.equal('/users?offset=31&offset=30&limit=false');
        path.build({ offset: 31, limit: 15 }, {ignoreSearch: true}).should.equal('/users');
    });

    it('should match and build paths with url and query parameters', function () {
        var path = new Path('/users/profile/:id-:id2?:id3');
        path.hasQueryParams.should.be.true;
        // Successful match & partial match
        path.match('/users/profile/123-456?id3=789').should.eql({ id: '123', id2: '456', id3: '789' });
        path.partialMatch('/users/profile/123-456').should.eql({ id: '123', id2: '456' });
        // Un,successful match
        should.not.exist(path.match('/users/details/123-456'));
        should.not.exist(path.match('/users/profile/123-456?id3=789&id4=000'));

        path.build({ id: '123', id2: '456', id3: '789' }).should.equal('/users/profile/123-456?id3=789')
    });

    it('should match and build paths with splat parameters', function () {
        var path = new Path('/users/*splat');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/123').should.eql({ splat: 'profile/123'});
        path.match('/users/admin/manage/view/123').should.eql({ splat: 'admin/manage/view/123'});
        // Build path
        path.build({ splat: 'profile/123'}).should.equal('/users/profile/123');
    });

    it('should match and build paths with splat and url parameters', function () {
        var path = new Path('/users/*splat/view/:id');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/view/123').should.eql({ splat: 'profile', id: '123' });
        path.match('/users/admin/manage/view/123').should.eql({ splat: 'admin/manage', id: '123' });
    });

    it('should match and build paths with url, splat and query parameters', function () {
        var path = new Path('/:section/*splat?id');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/view?id=123').should.eql({ section: 'users', splat: 'profile/view', id: '123' });
        path.build({section: 'users', splat: 'profile/view', id: '123'}).should.equal('/users/profile/view?id=123');
    })

    it('should match and build paths with matrix parameters', function () {
        var path = new Path('/users/;section;id');
        path.hasMatrixParams.should.be.true;
        // Build path
        path.build({ section: 'profile', id: '123'}).should.equal('/users/;section=profile;id=123');
        // Successful match
        path.match('/users/;section=profile;id=123').should.eql({ section: 'profile', id: '123' });
    });

    it('should match and build paths with constrained parameters', function () {
        var path = new Path('/users/:id<\\d+>');
        // Build path
        path.build({id: 99}).should.equal('/users/99');
        // Match path
        path.match('/users/11').should.eql({id: '11'});
        should.not.exist(path.match('/users/thomas'));

        path = new Path('/users/;id<[A-F0-9]{6}>');
        // Build path
        path.build({id: 'A76FE4'}).should.equal('/users/;id=A76FE4');
        // Error because of incorrect parameter format
        (function () {
            path.build({id: 'incorrect-param'});
        }).should.throw();
        // Force
        path.build({id: 'fake'}, {ignoreConstraints: true}).should.equal('/users/;id=fake');

        // Match path
        path.match('/users/;id=A76FE4').should.eql({id: 'A76FE4'});
        should.not.exist(path.match('/users;id=Z12345'));
    });

    it('should match paths with optional trailing slashes', function () {
        var path = new Path('/my-path');
        should.not.exist(path.match('/my-path/'));
        path.match('/my-path/', true).should.eql({});
        path.match('/my-path/', 1).should.eql({});

        path = new Path('/my-path/');
        should.not.exist(path.match('/my-path'));
        path.match('/my-path', true).should.eql({});
        path.match('/my-path', 1).should.eql({});

        path = new Path('/');
        should.not.exist(path.match(''));
        path.match('/', true).should.eql({});
        path.match('', 1).should.eql({});
    });
});
<commit_msg>test: test partial matching with array query param<commit_after>'use strict';

var path      = require('path');
var pkg       = require('../package.json');
var Path      = require(path.join(__dirname, '..', pkg.main));
var should    = require('should');

require('mocha');

describe('Path', function () {
    it('should throw an error when instanciated without parameter', function () {
        (function () {
            new Path()
        }).should.throw();
    });

    it('should throw an error if Path is used like a function', function () {
        (function () {
            Path()
        }).should.throw();
    });

    it('should throw an error if a path cannot be tokenised', function () {
        (function () {
            new Path('/!#')
        }).should.throw();
    });

    it('should return a path if createPath is used', function () {
        should.exist(Path.createPath('/users'));
    });

    it('should match and build paths with url parameters', function () {
        var path = new Path('/users/profile/:id-:id2.html');
        // Successful match & partial match
        path.match('/users/profile/123-abc.html').should.eql({ id: '123', id2: 'abc' });
        path.partialMatch('/users/profile/123-abc.html?what').should.eql({ id: '123', id2: 'abc' });
        // Unsuccessful match
        should.not.exist(path.match('/users/details/123-abc'));
        should.not.exist(path.match('/users/details/123-abc.html'));
        should.not.exist(path.match('/users/profile/123-abc.html?what'));

        path.build({ id: '123', id2: 'abc' }).should.equal('/users/profile/123-abc.html');
        (function () {
            path.build({ id: '123'});
        }).should.throw('Missing parameters');
    });

    it('should match and build paths with query parameters', function () {
        var path = new Path('/users?offset&limit');
        // Successful match & partial match
        path.match('/users?offset=31&limit=15').should.eql({ offset: '31', limit: '15' });
        path.match('/users?offset=31&offset=30&limit=15').should.eql({ offset: ['31', '30'], limit: '15' });
        path.match('/users?offset&limit=15').should.eql({ offset: '', limit: '15' });
        path.match('/users?limit=15').should.eql({ limit: '15' });
        path.partialMatch('/users?offset&limits=1').should.eql({ offset: '' });
        path.partialMatch('/users?offset=1&offset=2&limits=1').should.eql({ offset: ['1', '2'] });
        path.partialMatch('/users').should.eql({});

        // Unsuccessful match
        should.not.exist(path.match('/users?offset=31&order=asc'));
        should.not.exist(path.match('/users?offset=31&limit=10&order=asc'));

        path.build({ offset: 31, limit: 15 }).should.equal('/users?offset=31&limit=15');
        path.build({ offset: 31 }).should.equal('/users?offset=31');
        path.build({ offset: 31, limit: '' }).should.equal('/users?offset=31&limit');
        path.build({ offset: 31, limit: undefined  }).should.equal('/users?offset=31&limit');
        path.build({ offset: 31, limit: false  }).should.equal('/users?offset=31&limit=false');
        path.build({ offset: [31, 30], limit: false  }).should.equal('/users?offset=31&offset=30&limit=false');
        path.build({ offset: 31, limit: 15 }, {ignoreSearch: true}).should.equal('/users');
    });

    it('should match and build paths with url and query parameters', function () {
        var path = new Path('/users/profile/:id-:id2?:id3');
        path.hasQueryParams.should.be.true;
        // Successful match & partial match
        path.match('/users/profile/123-456?id3=789').should.eql({ id: '123', id2: '456', id3: '789' });
        path.partialMatch('/users/profile/123-456').should.eql({ id: '123', id2: '456' });
        // Un,successful match
        should.not.exist(path.match('/users/details/123-456'));
        should.not.exist(path.match('/users/profile/123-456?id3=789&id4=000'));

        path.build({ id: '123', id2: '456', id3: '789' }).should.equal('/users/profile/123-456?id3=789')
    });

    it('should match and build paths with splat parameters', function () {
        var path = new Path('/users/*splat');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/123').should.eql({ splat: 'profile/123'});
        path.match('/users/admin/manage/view/123').should.eql({ splat: 'admin/manage/view/123'});
        // Build path
        path.build({ splat: 'profile/123'}).should.equal('/users/profile/123');
    });

    it('should match and build paths with splat and url parameters', function () {
        var path = new Path('/users/*splat/view/:id');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/view/123').should.eql({ splat: 'profile', id: '123' });
        path.match('/users/admin/manage/view/123').should.eql({ splat: 'admin/manage', id: '123' });
    });

    it('should match and build paths with url, splat and query parameters', function () {
        var path = new Path('/:section/*splat?id');
        path.hasSpatParam.should.be.true;
        // Successful match
        path.match('/users/profile/view?id=123').should.eql({ section: 'users', splat: 'profile/view', id: '123' });
        path.build({section: 'users', splat: 'profile/view', id: '123'}).should.equal('/users/profile/view?id=123');
    })

    it('should match and build paths with matrix parameters', function () {
        var path = new Path('/users/;section;id');
        path.hasMatrixParams.should.be.true;
        // Build path
        path.build({ section: 'profile', id: '123'}).should.equal('/users/;section=profile;id=123');
        // Successful match
        path.match('/users/;section=profile;id=123').should.eql({ section: 'profile', id: '123' });
    });

    it('should match and build paths with constrained parameters', function () {
        var path = new Path('/users/:id<\\d+>');
        // Build path
        path.build({id: 99}).should.equal('/users/99');
        // Match path
        path.match('/users/11').should.eql({id: '11'});
        should.not.exist(path.match('/users/thomas'));

        path = new Path('/users/;id<[A-F0-9]{6}>');
        // Build path
        path.build({id: 'A76FE4'}).should.equal('/users/;id=A76FE4');
        // Error because of incorrect parameter format
        (function () {
            path.build({id: 'incorrect-param'});
        }).should.throw();
        // Force
        path.build({id: 'fake'}, {ignoreConstraints: true}).should.equal('/users/;id=fake');

        // Match path
        path.match('/users/;id=A76FE4').should.eql({id: 'A76FE4'});
        should.not.exist(path.match('/users;id=Z12345'));
    });

    it('should match paths with optional trailing slashes', function () {
        var path = new Path('/my-path');
        should.not.exist(path.match('/my-path/'));
        path.match('/my-path/', true).should.eql({});
        path.match('/my-path/', 1).should.eql({});

        path = new Path('/my-path/');
        should.not.exist(path.match('/my-path'));
        path.match('/my-path', true).should.eql({});
        path.match('/my-path', 1).should.eql({});

        path = new Path('/');
        should.not.exist(path.match(''));
        path.match('/', true).should.eql({});
        path.match('', 1).should.eql({});
    });
});
<|endoftext|>